Sruthú SSE
Ar an leathanach seo
Freagairtí fíor-ama
Sa ghnáthmhód, fanann tú go gcríochnaíonn an tsamhail an fhreagairt iomlán a ghiniúint sula bhfaigheann tú í. Le sruthú SSE (Imeachtaí Seirbhíse-Seolta), tagann na tokení de réir mar a ghintear iad. Tá sé seo ríthábhachtach do chomhéadain chomhráite ina bhfuil úsáideoirí ag iarraidh an fhreagairt a fheiceáil ag teacht chun cinn go céimniúil.
Sruthú a chumasú
Cuir "stream": true le do iarratas:
curl https://api.x.ai/v1/responses \
-H "Authorization: Bearer $XAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "grok-4.20-0309-reasoning",
"input": "Write a poem about programming.",
"stream": true
}'
Tagann an fhreagairt mar shruth SSE:
data: {"type": "response.created", "response": {...}}
data: {"type": "response.output_item.added", ...}
data: {"type": "response.content_part.added", ...}
data: {"type": "response.output_text.delta", "delta": "La "}
data: {"type": "response.output_text.delta", "delta": "programmation "}
data: {"type": "response.output_text.delta", "delta": "est "}
...
data: {"type": "response.completed", "response": {...}}
Cineálacha imeachtaí
| Imeacht | Cur síos |
|---|---|
response.created | Tosaíonn an ghiniúint |
response.output_item.added | Mír nua san aschur |
response.content_part.added | Páirt nua ábhair |
response.output_text.delta | Blúire téacs (an ceann is minice) |
response.output_text.done | Téacs iomlán míre |
response.completed | Freagairt chríochnaithe le húsáid |
response.failed | Earráid le linn na giniúna |
Sruthú i bPython
stream = client.responses.create(
model="grok-4.20-0309-reasoning",
input="Explain how a compiler works.",
stream=True
)
full_text = ""
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
full_text += event.delta
elif event.type == "response.completed":
usage = event.response.usage
print(f"\n\nTokens: {usage.total_tokens}")
print(f"Cost: {usage.cost_in_nano_usd / 1e9:.6f} USD")
Cuireann flush=True iallach ar gach blúire a thaispeáint láithreach.
Sruthú le huirlisí
Nuair a úsáideann an tsamhail uirlisí sa mhód sruthaithe, faigheann tú imeachtaí breise:
data: {"type": "response.output_item.added", "item": {"type": "web_search_call"}}
data: {"type": "response.web_search_call.in_progress", ...}
data: {"type": "response.web_search_call.completed", ...}
data: {"type": "response.output_text.delta", "delta": "Selon les résultats..."}
I gcás glaonna feidhme cliant, faigheann tú argóintí go céimniúil:
data: {"type": "response.function_call.arguments.delta", "delta": "{\"city\""}
data: {"type": "response.function_call.arguments.delta", "delta": ": \"Paris\"}"}
data: {"type": "response.function_call.arguments.done", ...}
Comhtháthú Frontend
Chun feidhmchlár gréasáin a chruthú, seol an sruth SSE chuig an mbrabhsálaí trí phointe deiridh freastalaí:
const response = await fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({ message: userInput })
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = decoder.decode(value);
outputElement.textContent += text;
}
Sruthú agus billeáil
Ní athraíonn an sruthú an billeáil. Tá an costas mar an gcéanna cibé an bhfuil sé cumasaithe nó nach bhfuil—níl difríocht ach sa mhód seachadta. Tá an oibiacht usage iomlán ar fáil san imeacht response.completed.
Príomhphointí
- Cumasaíonn
stream: truesruthú SSE—tagann tokení de réir mar a ghintear iad - Tá gach blúire téacs san imeacht
response.output_text.delta - Tá an fhreagairt dheireanach le meiteashonraí úsáide san imeacht
response.completed - Oibríonn an sruthú le huirlisí (web_search, feidhmeanna)
- Tá an costas mar an gcéanna le sruthú nó gan é