Léim go dtí an príomhábhar
Gaeilge— Roghnaigh teanga
Roghchlár

Sruthú SSE

Ceacht 13 as 16 Nuashonraithe 30 Iúil 2026 Forbróir
Ar an leathanach seo
  1. Freagairtí fíor-ama
  2. Sruthú a chumasú
  3. Cineálacha imeachtaí
  4. Sruthú i bPython
  5. Sruthú le huirlisí
  6. Comhtháthú Frontend
  7. Sruthú agus billeáil
  8. Príomhphointí

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.

SSE
Server-Sent Events
~50ms
An chéad token le feiceáil
text/event-stream
Content-Type
stream: true
Paraiméadar amháin

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í

ImeachtCur síos
response.createdTosaíonn an ghiniúint
response.output_item.addedMír nua san aschur
response.content_part.addedPáirt nua ábhair
response.output_text.deltaBlúire téacs (an ceann is minice)
response.output_text.doneTéacs iomlán míre
response.completedFreagairt chríochnaithe le húsáid
response.failedEarrá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: true sruthú 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 é