Streaming
Empfange Antworten in Echtzeit mit Server-Sent Events.
Überblick
Aktiviere Streaming, um Antworten deines Agenten Token für Token über Server-Sent Events (SSE) zu empfangen. Das verbessert die Nutzererfahrung bei längeren Antworten.
Anfrage
Setze in deiner Chat-Anfrage stream: true:
curl https://api.your-domain.com/v1/chat \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"message": "Explain quantum computing",
"stream": true
}'Antwortformat
Die Antwort ist ein Strom von SSE-Ereignissen:
data: {"type": "start", "conversation_id": "conv_abc123"}
data: {"type": "token", "content": "Quantum"}
data: {"type": "token", "content": " computing"}
data: {"type": "token", "content": " is"}
data: {"type": "token", "content": " a"}
data: {"type": "sources", "sources": ["https://example.com/quantum"]}
data: {"type": "end", "message_id": "msg_xyz789"}Client-Implementierung
JavaScript
const response = await fetch("https://api.your-domain.com/v1/chat", {
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
message: "Explain quantum computing",
stream: true,
}),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split("\n").filter((l) => l.startsWith("data: "));
for (const line of lines) {
const data = JSON.parse(line.slice(6));
if (data.type === "token") {
process.stdout.write(data.content);
}
}
}Ereignistypen
| Typ | Beschreibung |
|---|---|
start | Stream wurde gestartet, enthält conversation_id |
token | Einzelnes Token der Antwort |
sources | Für die Antwort verwendete Quelldokumente |
end | Stream abgeschlossen, enthält message_id |
error | Bei der Erzeugung ist ein Fehler aufgetreten |