Simira kuzvirimo
Kuyerera

Kuyerera

Isa stream ku-true uye mhinduro inouya se-server-sent events apo model ichiinyora: reasoning kutanga, wozoteverwa nemhinduro, wozoita chunk yekupedzisira ine finish reason ne-usage. Shandisa pese apo munhu ari kumirira text, uye pamhinduro dzakareba.

POST https://api.shannon-ai.com/v1/chat/completions

OpenAI SDKs dzinokupa ma-chunk rimwe nerimwe. Verenga chunk imwe neimwe nezvainotakura: chimedu che-reasoning, chimedu chemhinduro, tool call, kana kupera kwemhinduro.

from openai import OpenAI, APIError

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.shannon-ai.com/v1",
)

stream = client.chat.completions.create(
    model="shannon-3",
    messages=[{"role": "user", "content": "Explain server-sent events in three sentences."}],
    stream=True,
)

answer, reasoning, tool_calls = [], [], []
finish_reason = usage = None

try:
    for chunk in stream:
        if chunk.usage:
            usage = chunk.usage
        if not chunk.choices:
            continue
        choice = chunk.choices[0]
        delta = choice.delta

        thought = getattr(delta, "reasoning_content", None)
        if thought:
            reasoning.append(thought)
        if delta.content:
            answer.append(delta.content)
            print(delta.content, end="", flush=True)
        for call in delta.tool_calls or []:
            tool_calls.append((call.id, call.function.name, call.function.arguments))
        if choice.finish_reason:
            finish_reason = choice.finish_reason
except APIError as error:
    # A failure after the stream started arrives as an error chunk.
    print(f"\nstream failed: {error}")

print(f"\n{finish_reason} {usage}")

Kuti stream inorongwa sei

  • Mhinduro ine status 200 ne-headers content-type: text/event-stream ne-cache-control: no-cache.
  • Event imwe neimwe i-mutsara mumwe unotanga ne-data: uye unoteverwa nemutsara usina chinhu. Text iri mushure me-data: i-JSON chunk imwe. Hapana mitsara ye-event: kana id:.
  • Mutsara unotanga ne-colon, sa-: ping, i-comment inochengeta connection yakavhurika. Uusiye.
  • Stream inopera ne-data: [DONE]. Stream inomira isina iyo haina kupera.

Ma-chunk nenhevedzano

Chunk imwe neimwe i-chat.completion.chunk object:

JSON
{
  "id": "chatcmpl-5f0c1e7a9b3d4c62a8e1f07d2b46c9a3",
  "object": "chat.completion.chunk",
  "created": 1791625200,
  "model": "shannon-3",
  "choices": [
    {
      "index": 0,
      "delta": {
        "content": "Server-sent"
      },
      "finish_reason": null
    }
  ]
}

Ma-chunk ese e-stream imwe anotakura id, created ne-model zvakafanana. choices inogara iine entry imwe. delta yayo ine zvitsva, uye finish_reason i-null kusvika pa-chunk yekupedzisira.

Key mu-delta Mhando Tsananguro Inotumirwa ne
role string Inogara iri assistant. Inouya kamwe, pakutanga kwe-stream. Hosted open-weight models, shannon-2-lite, shannon-2-pro
reasoning_content string Chimedu che-reasoning ye-model. Batanidza zvimedu nenhevedzano. Hosted open-weight models, mhuri ye-Shannon 3, shannon-1.6-pro, shannon-coder-1
content string Chimedu chemhinduro. Batanidza zvimedu nenhevedzano. Ma-model ese
tool_calls array Tool call imwe yakazara. Tarisa Tool call deltas. Ma-model ese

Reasoning inouya kutanga, wozoteverwa nemhinduro, wozoita tool calls chero dzipi. Verenga chunk nema-key ari mu-delta yayo, kwete nenzvimbo yayo mu-stream: delta inogona kuva ne-role pamwe chete nechimedu chekutanga che-text, uye yekupedzisira haina chinhu.

Stream yose sezvainofamba. Kuti mitsara ive pfupi, id, object, created ne-model zvakasiiwa pa-chunk imwe neimwe pano.

200 text/event-stream
data: {"choices":[{"index":0,"delta":{"reasoning_content":"Three sentences:"},"finish_reason":null}]}

data: {"choices":[{"index":0,"delta":{"reasoning_content":" what it is, how it is framed, why it is used."},"finish_reason":null}]}

: ping

data: {"choices":[{"index":0,"delta":{"content":"Server-sent"},"finish_reason":null}]}

data: {"choices":[{"index":0,"delta":{"content":" events let a server push text to a client over one HTTP reply."},"finish_reason":null}]}

data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1190,"completion_tokens":84,"total_tokens":1274}}

data: [DONE]

Reasoning deltas

Model inofunga inotumira reasoning yayo mu-delta.reasoning_content pamberi pemhinduro. Chengeta ma-text maviri akaparadzaniswa: ratidza reasoning sechikamu chakasiyana, chinopetwa, kana uisiye.

Hosted open-weight models hadzitumire reasoning kana reasoning_effort i-off, uye hadzitumire kana request ine response_format.

shannon-2-lite ne-shannon-2-pro dzinofungawo dzisati dzapindura. Pa-endpoint iyi dzinotumira mitsara ye-comment : thinking apo dzichifunga, wozoteverwa nemhinduro.

reasoning_content haisi mu-typed models dze-OpenAI SDKs. Mu-Python iverenge ne-getattr(delta, "reasoning_content", None); mu-JavaScript delta.reasoning_content inoshanda sezvairi.

Tool call deltas

Tool call inouya yakazara: chunk imwe pa-call imwe, ine delta ine call pamwe chete ne-arguments string yakazara. index inoverenga calls dzemhinduro kubva pa-0. Code inobatanidza arguments chimedu nechimedu inoshanda isina kuchinjwa, nekuti inobatanidza chimedu chimwe.

delta
{
  "tool_calls": [
    {
      "index": 0,
      "id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
      "type": "function",
      "function": {
        "name": "get_weather",
        "arguments": "{\"city\":\"Paris\"}"
      }
    }
  ]
}

Mushure me-calls, chunk yekupedzisira ine finish_reason tool_calls.

Kana request ine tools, shannon-1.6-lite, shannon-1.6-pro ne-shannon-coder-1 dzinotumira text yemhinduro sa-delta imwe pakupera kwemhinduro.

Chunk yekupedzisira

Chunk yekupedzisira pamberi pe-data: [DONE] ine delta isina chinhu, finish_reason ne-usage ye-request, zvese mu-chunk imwechete. Stream imwe neimwe inayo; hauna kufanira stream_options.

JSON
{
  "id": "chatcmpl-5f0c1e7a9b3d4c62a8e1f07d2b46c9a3",
  "object": "chat.completion.chunk",
  "created": 1791625200,
  "model": "shannon-3",
  "choices": [
    {
      "index": 0,
      "delta": {},
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1190,
    "completion_tokens": 84,
    "total_tokens": 1274
  }
}

Pa-hosted open-weight models usage inewo prompt_tokens_details.cached_tokens ne-completion_tokens_details.reasoning_tokens.

Mushure me-request ine web_search: true ine search yakawana chimwe chinhu, chunk yekupedzisira inotakurawo sources, uye chunk imwe pamberi payo inotakura citation marks se-delta.annotations. Kutsvaga pawebhu

finish_reason Tsananguro Inotumirwa ne
stop Model yapedza mhinduro yayo, kana stop string yaonekwa. Ma-model ese
tool_calls Mhinduro ine tool call imwe kana dzakawanda. Ma-model ese
length Mhinduro yadimburwa pa-output limit. Mhuri ye-Shannon 3, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1

Ma-field e-usage akatsanangurwa pamwe chete ne-endpoint. Chat Completions

Keep-alive lines

Apo model ichishanda uye isina chekutumira, stream inotakura comment lines. Hadzina data. SSE parser inodzisiya pachayo; code inoverenga raw lines inofanira kusiya mutsara wese unotanga ne-colon.

Mutsara Inotumirwa ne Rinhi
: ping Mhuri ye-Shannon 3, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 Masekonzi 15 ega ega.
: keepalive Hosted open-weight models Masekonzi 15 ega ega apo model ichishanda.
: thinking shannon-2-lite, shannon-2-pro Apo model ichifunga.

Errors mukati me-stream

Stream kana yatotanga status yayo i-200, saka kundikana kunouya mukati me-stream: chunk ine error member panzvimbo pa-choices.

200 text/event-stream
data: {"error":{"message":"The model backend failed to answer. Please retry.","type":"api_error","code":null,"param":null}}

data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1190,"completion_tokens":12,"total_tokens":1202}}

data: [DONE]

Mushure me-error chunk, chunk yekupedzisira, ine finish_reason ne-usage, ne-data: [DONE] zvinoteverazve. Tarisa chunk imwe neimwe kuti ine error here. Pasina check iyi mhinduro yakakundikana pakati inoratidzika seyakapera.

Mhando Code Message Rinhi
api_error The model backend failed to answer. Please retry. Model yakundikana, kana haina kunyora chinhu. Tumira request zvakare.
rate_limit_error Shannon routes are temporarily busy. Please retry. Model iri busy panguva ino. Mirira masekonzi mashoma uye utumire request zvakare.
invalid_request_error context_length_exceeded Hurukuro yakareba kupfuura context window ye-model. Pfupisa usati watumira zvakare. Text ye-message inosiyana.

Hosted open-weight models dzinotumira error member ine type ne-message chete.

OpenAI Python ne-JavaScript SDKs dzinoburitsa error chunk se-API error apo uri kuiterate, saka isa loop mu-error handling yako yenguva dzese.

Status codes, error body nezvekuedza zvakare zvine peji razvo. Zvikanganiso

Kuvhara connection

Kuvhara connection kunomisa kuendesa, kwete request. Model inonyora mhinduro kusvika kuguma uye request inobhadharwa sekunge waiverenga yose. Kuti ubhadhare shoma, kumbira shoma: isa max_tokens yakaderera pa-model inoishandisa.

Stream inogonawo kupera nekukurumidza ichiuya kwauri, semuenzaniso network ichitsemuka kana server ichivandudzwa. Inobva yamira isina chunk yekupedzisira uye isina data: [DONE]. Tora mhinduro iyoyo seisina kupera uye utumire request zvakare.

Kuverenga stream pasina SDK

Reader chaiyo inoita zvinhu zvishanu: inotumira errors dzinouya stream isati yatanga kune error handling yayo, inoparadzanisa body kuita mitsara, inosiya comment lines, inomira pa-data: [DONE], uye inotarisa chunk imwe neimwe kuti ine error here.

import json
import requests

response = requests.post(
    "https://api.shannon-ai.com/v1/chat/completions",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "model": "shannon-3",
        "messages": [{"role": "user", "content": "Explain server-sent events in three sentences."}],
        "stream": True,
    },
    stream=True,
)

# 1. Errors before the stream are plain JSON with their own status.
if response.status_code != 200:
    raise RuntimeError(f"{response.status_code}: {response.text}")

answer, done = [], False
for raw in response.iter_lines():          # 2. one line at a time
    line = raw.decode("utf-8")
    if not line.startswith("data: "):      # 3. empty lines and ": ping" comments
        continue
    data = line[len("data: "):]
    if data == "[DONE]":                   # 4. the end of the stream
        done = True
        break
    chunk = json.loads(data)
    if "error" in chunk:                   # 5. a failure inside the stream
        raise RuntimeError(chunk["error"]["message"])
    delta = chunk["choices"][0]["delta"]
    if delta.get("content"):
        answer.append(delta["content"])
    if chunk.get("usage"):
        print(chunk["choices"][0]["finish_reason"], chunk["usage"])

if not done:
    raise RuntimeError("the stream ended before [DONE]")
print("".join(answer))

Sample ye-Python inoshandisa requests package. Sample ye-JavaScript inomhanya pa-Node.js 18 kana mushure mayo.

Streams dze-formats dzimwe

Responses ne-Messages endpoints dzinoita streaming zvakare. Ma-frame adzo anotakura mutsara we-event: une zita re-event nemutsara we-data: une JSON yayo. Peji rimwe nerimwe rinoratidza ma-event aro nenhevedzano.

Mu-stream Chat CompletionsResponsesMessages
Frames Mitsara ye-data:Mitsara ye-event: ne-data:Mitsara ye-event: ne-data:
Reasoning inouya mu delta.reasoning_contentresponse.reasoning_summary_text.deltathinking_delta
Text yemhinduro inouya mu delta.contentresponse.output_text.deltatext_delta
Usage inouya mu Chunk yekupedzisiraresponse.completedmessage_delta
Stream inopera ne Chunk yekupedzisira, wozoita data: [DONE]response.completedmessage_stop