Kutsitsa nthawi yeniyeni
Khazikitsani stream kukhala true ndipo yankho limafika ngati server-sent events pamene model ikulilemba: reasoning poyamba, kenako yankho, kenako chunk yomaliza yokhala ndi chifukwa chotsirizira ndi usage. Gwiritsani ntchito nthawi iliyonse munthu akudikira text, komanso pa mayankho aatali.
POST https://api.shannon-ai.com/v1/chat/completions
Ma OpenAI SDK amakupatsani ma chunk imodzi ndi imodzi. Werengani chunk iliyonse ndi zomwe imanyamula: chigawo cha reasoning, chigawo cha yankho, call ya tool, kapena mapeto a yankho.
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}") import OpenAI from "openai";
const client = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.shannon-ai.com/v1",
});
const stream = await client.chat.completions.create({
model: "shannon-3",
messages: [{ role: "user", content: "Explain server-sent events in three sentences." }],
stream: true,
});
let answer = "";
let reasoning = "";
const toolCalls = [];
let finishReason = null;
let usage = null;
try {
for await (const chunk of stream) {
if (chunk.usage) usage = chunk.usage;
const choice = chunk.choices?.[0];
if (!choice) continue;
const delta = choice.delta;
if (delta.reasoning_content) reasoning += delta.reasoning_content;
if (delta.content) {
answer += delta.content;
process.stdout.write(delta.content);
}
for (const call of delta.tool_calls ?? []) {
toolCalls.push({ id: call.id, name: call.function.name, arguments: call.function.arguments });
}
if (choice.finish_reason) finishReason = choice.finish_reason;
}
} catch (error) {
// A failure after the stream started arrives as an error chunk.
console.error("\nstream failed:", error.message);
}
console.log("\n", finishReason, usage); curl -N https://api.shannon-ai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "shannon-3",
"messages": [{"role": "user", "content": "Explain server-sent events in three sentences."}],
"stream": true
}' Momwe stream imapangidwira ma frame
- Yankho lili ndi status
200ndi ma headercontent-type: text/event-streamndicache-control: no-cache. - Event iliyonse ndi mzere umodzi woyambira ndi
data:wotsatiridwa ndi mzere wopanda kanthu. Text yotsatiradata:ndi JSON chunk imodzi. Palibe mizere yaevent:kapenaid:. - Mzere woyambira ndi colon, monga
: ping, ndi comment yosunga connection yotsegula. Uudumpheni. - Stream imatha ndi
data: [DONE]. Stream yomwe imaima popanda iyo ndi yosakwanira.
Ma chunk motsatira
Chunk iliyonse ndi object ya chat.completion.chunk:
{
"id": "chatcmpl-5f0c1e7a9b3d4c62a8e1f07d2b46c9a3",
"object": "chat.completion.chunk",
"created": 1791625200,
"model": "shannon-3",
"choices": [
{
"index": 0,
"delta": {
"content": "Server-sent"
},
"finish_reason": null
}
]
} Ma chunk onse a stream imodzi amanyamula id, created ndi model zofanana. choices nthawi zonse ili ndi entry imodzi. delta yake ili ndi zatsopano, ndipo finish_reason ndi null mpaka chunk yomaliza.
| Key mu delta | Mtundu | Kufotokozera | Yotumizidwa ndi |
|---|---|---|---|
role | string | Nthawi zonse assistant. Imafika kamodzi, poyamba pa stream. | Hosted open-weight model, shannon-2-lite, shannon-2-pro |
reasoning_content | string | Chigawo cha reasoning ya model. Lumikizani zigawozo motsatira. | Hosted open-weight model, banja la Shannon 3, shannon-1.6-pro, shannon-coder-1 |
content | string | Chigawo cha yankho. Lumikizani zigawozo motsatira. | Ma model onse |
tool_calls | array | Call imodzi yathunthu ya tool. Onani Tool call deltas. | Ma model onse |
Reasoning imabwera poyamba, kenako yankho, kenako ma call a tool. Werengani chunk ndi ma key a delta yake, osati malo ake mu stream: delta ikhoza kukhala ndi role pamodzi ndi chigawo choyamba cha text, ndipo yomaliza ilibe kanthu.
Stream yonse monga imayendera. Kuti mizere ikhale yaifupi, id, object, created ndi model zasiyidwa pa chunk iliyonse pano.
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] Ma delta a reasoning
Model yomwe imaganiza imatumiza reasoning yake mu delta.reasoning_content yankho lisanafike. Sungani ma text awiriwo padera: onetsani reasoning ngati gawo losiyana lopindika, kapena isiyeni.
Hosted open-weight model sizitumiza reasoning pamene reasoning_effort ndi off, komanso pamene pempho lili ndi response_format.
shannon-2-lite ndi shannon-2-pro zimaganizanso zisanayankhe. Pa endpoint iyi zimatumiza mizere ya comment : thinking pamene zikuganiza, kenako yankho.
reasoning_content siili mu ma typed model a OpenAI SDK. Mu Python iwerengeni ndi getattr(delta, "reasoning_content", None); mu JavaScript delta.reasoning_content imagwira ntchito monga ilili.
Ma delta a call ya tool
Call ya tool imafika yonse: chunk imodzi pa call iliyonse, yomwe delta yake ili ndi call ndi string yathunthu ya arguments. index imawerenga ma call a yankho kuyambira 0. Code yomwe imalumikiza arguments chigawo ndi chigawo imagwira ntchito popanda kusintha, chifukwa imalumikiza chigawo chimodzi.
{
"tool_calls": [
{
"index": 0,
"id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
} Pambuyo pa ma call, chunk yomaliza ili ndi finish_reason tool_calls.
Pempho likakhala ndi tools, shannon-1.6-lite, shannon-1.6-pro ndi shannon-coder-1 zimatumiza text ya yankho ngati delta imodzi kumapeto kwa yankho.
Chunk yomaliza
Chunk yomaliza isanafike data: [DONE] ili ndi delta yopanda kanthu, finish_reason ndi usage ya pempho, zonse mu chunk imodzi. Stream iliyonse imakhala nayo; simufuna stream_options.
{
"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 model usage imakhalanso ndi prompt_tokens_details.cached_tokens ndi completion_tokens_details.reasoning_tokens.
Pambuyo pa pempho lokhala ndi web_search: true lomwe kusaka kwake kwapeza kanthu, chunk yomaliza imanyamulanso sources, ndipo chunk imodzi isanafike imanyamula zizindikiro za mawu otchulidwa ngati delta.annotations. Kusaka pa web
| finish_reason | Kufotokozera | Yotumizidwa ndi |
|---|---|---|
stop | Model yamaliza yankho lake, kapena string ya stop yaoneka. | Ma model onse |
tool_calls | Yankho lili ndi call imodzi kapena zingapo za tool. | Ma model onse |
length | Yankho lidadulidwa pa malire a output. | Banja la Shannon 3, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 |
Ma field a usage afotokozedwa pamodzi ndi endpoint. Chat Completions
Mizere ya keep-alive
Pamene model ikugwira ntchito ndipo ilibe chotumiza, stream imanyamula mizere ya comment. Ilibe data. SSE parser imaidumpha yokha; code yomwe imawerenga mizere yeniyeni iyenera kudumpha mzere uliwonse woyambira ndi colon.
| Mzere | Yotumizidwa ndi | Liti |
|---|---|---|
: ping | Banja la Shannon 3, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 | Masekondi 15 aliwonse. |
: keepalive | Hosted open-weight model | Masekondi 15 aliwonse pamene model ikugwira ntchito. |
: thinking | shannon-2-lite, shannon-2-pro | Pamene model ikuganiza. |
Zolakwika mkati mwa stream
Stream ikayamba status yake ndi 200, choncho cholakwika chimafika mkati mwa stream: chunk yokhala ndi member ya error pamene choices ikanakhala.
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] Pambuyo pa chunk ya cholakwika, chunk yomaliza, yokhala ndi finish_reason ndi usage, ndi data: [DONE] zimatsatirabe. Yang'anani chunk iliyonse kuti muone error. Popanda kuyang'ana kumeneku, yankho lomwe lalephera pakati limaoneka lathunthu.
| Type | Code | Message | Liti |
|---|---|---|---|
api_error | The model backend failed to answer. Please retry. | Model yalephera, kapena sinalembe kanthu. Tumizaninso pempho. | |
rate_limit_error | Shannon routes are temporarily busy. Please retry. | Model ili otanganidwa pakali pano. Dikirani masekondi ochepa ndipo tumizaninso pempho. | |
invalid_request_error | context_length_exceeded | Zokambirana ndi zazitali kuposa context window ya model. Zichepetseni musanatumizenso. Text ya message imasiyana. |
Hosted open-weight model zimatumiza member ya error yokhala ndi type ndi message zokha.
Ma OpenAI SDK a Python ndi JavaScript amatulutsa chunk ya cholakwika ngati API error pamene mukubwereza, choncho likani loop mu error handling yanu yanthawi zonse.
Ma status code, body ya cholakwika ndi zoyenera kuyesanso zili patsamba lawo. Zolakwika
Kutseka connection
Kutseka connection kumaimitsa kutumiza, osati pempho. Model imalemba yankho mpaka kumapeto ndipo pempho limaperekedwa mtengo ngati mwawerenga zonse. Kuti mulipire zochepa, pemphani zochepa: khazikitsani max_tokens yocheperako pa model yomwe imaigwiritsa ntchito.
Stream ikhozanso kutha msanga pa njira yopita kwa inu, mwachitsanzo network ikasweka kapena server ikasinthidwa. Imaima popanda chunk yomaliza komanso popanda data: [DONE]. Ganizirani yankho limenelo ngati losakwanira ndipo tumizaninso pempho.
Kuwerenga stream popanda SDK
Reader yolondola imachita zinthu zisanu: imatumiza zolakwika zomwe zimafika stream isanayambe ku error handling yake, imagawa body kukhala mizere, imadumpha mizere ya comment, imaima pa data: [DONE], ndipo imayang'ana chunk iliyonse kuti ione error.
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)) const response = await fetch("https://api.shannon-ai.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "shannon-3",
messages: [{ role: "user", content: "Explain server-sent events in three sentences." }],
stream: true,
}),
});
// 1. Errors before the stream are plain JSON with their own status.
if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
const decoder = new TextDecoder();
let buffer = "";
let answer = "";
let done = false;
read: for await (const bytes of response.body) {
buffer += decoder.decode(bytes, { stream: true });
const lines = buffer.split("\n"); // 2. one line at a time
buffer = lines.pop(); // keep the unfinished line
for (const line of lines) {
if (!line.startsWith("data: ")) continue; // 3. empty lines and ": ping" comments
const data = line.slice(6);
if (data === "[DONE]") { // 4. the end of the stream
done = true;
break read;
}
const chunk = JSON.parse(data);
if (chunk.error) throw new Error(chunk.error.message); // 5. a failure inside the stream
const choice = chunk.choices[0];
if (choice.delta.content) answer += choice.delta.content;
if (chunk.usage) console.log(choice.finish_reason, chunk.usage);
}
}
if (!done) throw new Error("the stream ended before [DONE]");
console.log(answer); Chitsanzo cha Python chimagwiritsa ntchito package ya requests. Chitsanzo cha JavaScript chimayenda pa Node.js 18 kapena yatsopano.
Ma stream a mitundu ina
Ma endpoint a Responses ndi Messages amachitanso stream. Ma frame awo amanyamula mzere wa event: wokhala ndi dzina la event ndi mzere wa data: wokhala ndi JSON yake. Tsamba lililonse limalemba ma event ake motsatira.
| Mu stream | Chat Completions | Responses | Messages |
|---|---|---|---|
| Ma frame | Mizere ya data: | Mizere ya event: ndi data: | Mizere ya event: ndi data: |
| Reasoning imafika mu | delta.reasoning_content | response.reasoning_summary_text.delta | thinking_delta |
| Text ya yankho imafika mu | delta.content | response.output_text.delta | text_delta |
| Usage imafika mu | Chunk yomaliza | response.completed | message_delta |
| Stream imatha ndi | Chunk yomaliza, kenako data: [DONE] | response.completed | message_stop |