Akış (streaming)
stream true ile yanıtı üretildikçe Server-Sent Events olarak alın; parça biçimini, kullanım bilgisinin nerede geldiğini, akış sırasında hataların nasıl göründüğünü ve akışı iptal etmeyi öğrenin.
MarkdownBu sayfada
Akış olmadan kullanıcınız, model yanıtın tamamını bitirene kadar hiçbir şey görmez. Akışta ise metin, model ilk token'ı üretir üretmez görünmeye başlar. Lykia akışı OpenAI ile aynı biçimde, Server-Sent Events (SSE) olarak gönderir; OpenAI SDK'ları ve SSE okuyabilen her istemci akışı olduğu gibi işler.
Akışı açmak
POST /chat/completions gövdesine "stream": true ekleyin. SDK kullanıyorsanız parçaları sırayla dolaşırsınız; kullanım bilgisi sonuncusunda gelir:
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])
stream = client.chat.completions.create(
model="google/gemini-2.5-flash",
messages=[{"role": "user", "content": "Name three uses of a message queue."}],
stream=True,
)
usage = None
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
usage = chunk.usage
print()
if usage is None:
raise RuntimeError("stream ended without a usage chunk; treat the response as incomplete")
# cost is a Lykia field, so it is not a typed attribute of the SDK object.
print("tokens:", usage.total_tokens, "cost (USD):", getattr(usage, "cost", None))import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });
const stream = await client.chat.completions.create({
model: "google/gemini-2.5-flash",
messages: [{ role: "user", content: "Name three uses of a message queue." }],
stream: true,
});
let usage: (OpenAI.CompletionUsage & { cost?: number }) | undefined;
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
if (chunk.usage) usage = chunk.usage;
}
process.stdout.write("\n");
if (!usage) throw new Error("stream ended without a usage chunk; treat the response as incomplete");
// cost is a Lykia field, so it is not part of the SDK's CompletionUsage type.
console.log("tokens:", usage.total_tokens, "cost (USD):", usage.cost);Akışlı istekler de akışsız isteklerle aynı yönlendirme, yedekleme ve faturalandırma kurallarına tabidir. Lykia yanıt başlıklarını bir sağlayıcıdan ilk parça geldikten sonra gönderir; o ana kadar hata veren bir sağlayıcının yerine sıradaki aday denenebilir. Başlıklarda X-Generation-Id ve Lykia istek için çıktı sınırını koyduysa ya da düşürdüyse X-Max-Tokens-Applied bulunur (Rezervasyon).
Akışın biçimi
Yanıt Content-Type: text/event-stream ile gelir. Her olay data: ile başlayan bir satır ve ardından boş bir satırdır. Olayın verisi bir chat.completion.chunk nesnesidir; akış data: [DONE] satırıyla biter.
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"role":"assistant","content":"1. "},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"Decoupling "},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"services\n"},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"2. "},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"Smoothing "},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"traffic "},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"spikes\n"},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"3. "},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"Running "},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"background "},"finish_reason":null}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[{"index":0,"delta":{"content":"jobs"},"finish_reason":"stop"}]}
data: {"id":"gen-1795373697-zxSS3yQ9Y2wsMD67","object":"chat.completion.chunk","created":1795373697,"model":"google/gemini-2.5-flash","provider":"google-ai-studio","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":12,"total_tokens":26,"cost":0.000034,"is_byok":false,"cost_details":{"upstream_cost":0.000034,"platform_fee":0,"is_byok":false},"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":0},"completion_tokens_details":{"reasoning_tokens":0}}}
data: [DONE]Bir parçada şunlar bulunur:
idstringİsteğin Lykia'daki kimliği; her parçada ve X-Generation-Id yanıt başlığında aynıdır. Akış bittikten sonra bu kimlikle GET /generation sorgulanabilir.
objectstringHer zaman "chat.completion.chunk".
createdintegerUnix zaman damgası (saniye).
modelstringİsteği karşılayan model.
providerstringİsteği karşılayan sağlayıcının kimliği (ör. openai).
choicesarrayBu parçadaki değişiklikler. Son kullanım parçasında boştur.
indexintegerSeçeneğin sırası.
deltaobjectÖncekilere eklenecek kısım: ilk parçada role, sonra content parçaları; araç çağrısında tool_calls parçaları; akıl yürütmesini bildiren modellerde reasoning parçaları.
finish_reasonstring | nullÜretim bitene kadar null; bitince "stop", "length" ya da "tool_calls" gibi bir değer.
usageobjectYalnız son veri parçasında bulunur: akışsız yanıttakiyle aynı nesne; prompt_tokens, completion_tokens, total_tokens, USD cinsinden cost, is_byok, cost_details, prompt_tokens_details ve completion_tokens_details.
Bazı sağlayıcılar parçaya system_fingerprint ya da logprobs gibi kendi alanlarını ekler; Lykia bunları olduğu gibi iletir. content parçalarını sırayla birleştirdiğinizde yanıtın tamamını elde edersiniz. Araç çağrılarında tool_calls[].function.arguments da parça parça gelir; argümanları bütün parçaları birleştirdikten sonra JSON olarak ayrıştırın.
Kullanım bilgisi ve maliyet
Token sayıları ve maliyet ancak yanıt tamamlanınca belli olur; bu yüzden usage son veri parçasında, data: [DONE] satırından hemen önce gelir. Lykia kullanım bilgisini sağlayıcıdan kendisi ister, isteğinize bir şey eklemeniz gerekmez. OpenAI'ın stream_options: { "include_usage": true } alanını zaten gönderiyorsanız bırakabilirsiniz.
SDK olmadan okumak
SSE okumak için özel bir kütüphane gerekmez. Satır satır okuyun, data: ile başlamayan satırları atlayın, [DONE] gelince durun. Lykia SSE yorum satırı (: ile başlayan satır) göndermez, ama SSE standardı bunlara izin verdiği için sağlam bir istemci yorum satırlarını yok sayar.
# -N turns off curl's output buffering so chunks print as they arrive.
curl -N https://api.getlykia.com/v1/chat/completions \
-H "Authorization: Bearer $LYKIA_API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: text/event-stream" \
-d '{
"model": "google/gemini-2.5-flash",
"stream": true,
"messages": [{ "role": "user", "content": "Name three uses of a message queue." }]
}'import json
import os
import requests
response = requests.post(
"https://api.getlykia.com/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
json={
"model": "google/gemini-2.5-flash",
"stream": True,
"messages": [{"role": "user", "content": "Name three uses of a message queue."}],
},
stream=True,
timeout=120,
)
response.raise_for_status()
usage = None
for raw in response.iter_lines(decode_unicode=True):
# Skip blank separators and SSE comment lines (they start with ":").
if not raw or raw.startswith(":") or not raw.startswith("data: "):
continue
data = raw[len("data: "):]
if data == "[DONE]":
break
chunk = json.loads(data)
# A provider failure after the stream started arrives as an event with "error" and no "choices"
if "error" in chunk:
error = chunk["error"]
raise RuntimeError(f"{error['status']} {error['code']}: {error['message']}")
for choice in chunk.get("choices", []):
print(choice.get("delta", {}).get("content") or "", end="", flush=True)
if chunk.get("usage"):
usage = chunk["usage"]
print()
if usage is None:
raise RuntimeError("stream ended without a usage chunk; treat the response as incomplete")
print("cost (USD):", usage["cost"])const response = await fetch("https://api.getlykia.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.LYKIA_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "google/gemini-2.5-flash",
stream: true,
messages: [{ role: "user", content: "Name three uses of a message queue." }],
}),
});
if (!response.ok || !response.body) {
throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);
}
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
let usage: { cost: number } | undefined;
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
// Skip blank separators and SSE comment lines (they start with ":").
if (!line.startsWith("data: ")) continue;
const data = line.slice("data: ".length);
if (data === "[DONE]") continue;
const chunk = JSON.parse(data);
// A provider failure after the stream started arrives as an event with `error` and no `choices`
if (chunk.error) throw new Error(`${chunk.error.status} ${chunk.error.code}: ${chunk.error.message}`);
process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
if (chunk.usage) usage = chunk.usage;
}
}
process.stdout.write("\n");
if (!usage) throw new Error("stream ended without a usage chunk; treat the response as incomplete");
console.log("cost (USD):", usage.cost);package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
type chunk struct {
Choices []struct {
Delta struct {
Content string `json:"content"`
} `json:"delta"`
} `json:"choices"`
Usage *struct {
Cost float64 `json:"cost"`
} `json:"usage"`
// A provider failure after the stream started arrives as an event with "error" and no "choices"
Error *struct {
Code string `json:"code"`
Status int `json:"status"`
Message string `json:"message"`
} `json:"error"`
}
func main() {
payload, _ := json.Marshal(map[string]any{
"model": "google/gemini-2.5-flash",
"stream": true,
"messages": []map[string]string{{"role": "user", "content": "Name three uses of a message queue."}},
})
req, err := http.NewRequest(http.MethodPost, "https://api.getlykia.com/v1/chat/completions", bytes.NewReader(payload))
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("LYKIA_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
panic(fmt.Sprintf("Lykia returned %d", resp.StatusCode))
}
var cost *float64
scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for scanner.Scan() {
line := scanner.Text()
// Skip blank separators and SSE comment lines (they start with ":").
if !strings.HasPrefix(line, "data: ") {
continue
}
data := strings.TrimPrefix(line, "data: ")
if data == "[DONE]" {
break
}
var c chunk
if err := json.Unmarshal([]byte(data), &c); err != nil {
panic(err)
}
if c.Error != nil {
panic(fmt.Sprintf("%d %s: %s", c.Error.Status, c.Error.Code, c.Error.Message))
}
if len(c.Choices) > 0 {
fmt.Print(c.Choices[0].Delta.Content)
}
if c.Usage != nil {
cost = &c.Usage.Cost
}
}
if err := scanner.Err(); err != nil {
panic(err)
}
fmt.Println()
if cost == nil {
panic("stream ended without a usage chunk; treat the response as incomplete")
}
fmt.Println("cost (USD):", *cost)
}Hatalar
Hata ilk parçadan önce oluşursa (geçersiz anahtar, boş bakiye, bilinmeyen model ya da bütün sağlayıcıların başarısız olması gibi) akış hiç başlamaz; olağan bir HTTP hata yanıtı ve bilinen hata gövdesini alırsınız. Akışı okumaya başlamadan önce durum kodunu denetleyin.
Akış başladıktan sonra durum kodu 200 kalır. Sağlayıcı bu noktadan sonra hata verirse ya da çok uzun süre bir şey göndermezse Lykia ayrı bir hata olayı, ardından data: [DONE] gönderir. Olay id, object, created, model, provider ve hata gövdesiyle aynı alanları (message, type, code, status, metadata.reason) taşıyan bir error nesnesi içerir; choices taşımaz. choices'ı okumadan önce her olayda error olup olmadığına bakın. Bu akışta kullanım parçası yoktur. Hatadan önce üretilen token'lar faturalanır ve kaydın durumu error olur.
data: {"id":"gen-…","object":"chat.completion.chunk","created":1795373697,"model":"anthropic/claude-sonnet-4.5","provider":"anthropic","error":{"message":"The provider reported an error","type":"provider_error","code":"provider_error","status":502,"metadata":{"reason":"provider_error","provider":"anthropic"}}}
data: [DONE]Olayda choices olmadığı için OpenAI SDK'ları onu döngü sırasında bir API hatası olarak fırlatır; Vercel AI SDK da olağan bir bitiş yerine error parçası olarak bildirir.
Akışı iptal etmek
Kullanıcı yanıtı durdurduğunda bağlantıyı kapatın. Lykia bağlantınızın kapandığını görünce sağlayıcıya giden isteği de iptal eder; böylece kimsenin okumayacağı token'lara para ödemeye devam etmezsiniz.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])
stream = client.chat.completions.create(
model="google/gemini-2.5-flash",
messages=[{"role": "user", "content": "Write a long story about a lighthouse keeper."}],
stream=True,
)
received = ""
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
received += chunk.choices[0].delta.content
if len(received) > 500:
# Closing the stream closes the connection; Lykia cancels the request to the provider.
stream.close()
break
print(received)import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });
const stream = await client.chat.completions.create({
model: "google/gemini-2.5-flash",
messages: [{ role: "user", content: "Write a long story about a lighthouse keeper." }],
stream: true,
});
let received = "";
for await (const chunk of stream) {
received += chunk.choices[0]?.delta?.content ?? "";
if (received.length > 500) {
// Aborting closes the connection; Lykia cancels the request to the provider.
stream.controller.abort();
break;
}
}
console.log(received);Sonraki adımlar
- Araç çağırma: Akıştaki
tool_callsparçalarını birleştirin. - Hatalar: Akış başlamadan dönen hataları ele alın.
POST /chat/completions: Akış parçası nesnesinin başvurusu.