Ukusakaza
Setha i-stream ibe true futhi impendulo ifika njenge-server-sent events ngenkathi i-model iyibhala: kuqala ukucabanga, bese impendulo, bese i-chunk yokugcina enesizathu sokuphela ne-usage. Yisebenzise noma nini lapho umuntu elindele umbhalo, nasezimpendulweni ezinde.
POST https://api.shannon-ai.com/v1/chat/completions
Ama-SDK e-OpenAI akunikeza ama-chunk eyodwa ngeyodwa. Funda i-chunk ngayinye ngalokho eyiphethe: ucezu lokucabanga, ucezu lwempendulo, isicelo sethuluzi, noma ukuphela kwempendulo.
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
}' Ukuthi i-stream yakhiwa kanjani
- Impendulo inesimo
200nama-headercontent-type: text/event-streamne-cache-control: no-cache. - Umcimbi ngamunye ngumugqa owodwa oqala ngo-
data:ulandelwe umugqa ongenalutho. Umbhalo ngemuva kwe-data:uyi-chunk eyodwa ye-JSON. Akukho migqa ye-event:noma ye-id:. - Umugqa oqala ngekholoni, njenge-
: ping, uyinoma egcina uxhumano luvulekile. Yeqe. - I-stream iphela nge-
data: [DONE]. I-stream emisa ngaphandle kwayo ayiphelele.
Ama-chunk ngokulandelana
I-chunk ngayinye iyi-object ye-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
}
]
} Wonke ama-chunk e-stream eyodwa aphethe i-id, created ne-model efanayo. I-choices ihlala iphethe into eyodwa. I-delta yayo iphethe okusha, futhi i-finish_reason iyi-null kuze kube yi-chunk yokugcina.
| Igama ku-delta | Uhlobo | Incazelo | Ithunyelwa yi- |
|---|---|---|---|
role | string | Njalo assistant. Ifika kanye, ekuqaleni kwe-stream. | Ama-model e-open-weight ahlinzekiwe, shannon-2-lite, shannon-2-pro |
reasoning_content | string | Ucezu lokucabanga kwe-model. Hlanganisa izingcezu ngokulandelana. | Ama-model e-open-weight ahlinzekiwe, umndeni we-Shannon 3, shannon-1.6-pro, shannon-coder-1 |
content | string | Ucezu lwempendulo. Hlanganisa izingcezu ngokulandelana. | Wonke ama-model |
tool_calls | array | Isicelo sethuluzi esiphelele esisodwa. Bheka Tool call deltas. | Wonke ama-model |
Ukucabanga kuza kuqala, bese impendulo, bese izicelo zamathuluzi uma zikhona. Funda i-chunk ngamagama aku-delta yayo, hhayi ngendawo yayo ku-stream: i-delta ingaphatha i-role kanye nocezu lokuqala lombhalo, futhi eyokugcina ayinalutho.
I-stream yonke njengoba ihamba. Ukugcina imigqa ifushane, i-id, object, created ne-model kushiywe ngaphandle kwe-chunk ngayinye lapha.
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] Ama-delta okucabanga
I-model ecabangayo ithumela ukucabanga kwayo ku-delta.reasoning_content ngaphambi kwempendulo. Gcina yomibili imibhalo ihlukene: bonisa ukucabanga njengengxenye ehlukile ongayigoqa, noma ukushiye.
Ama-model e-open-weight ahlinzekiwe awathumeli ukucabanga uma i-reasoning_effort iyi-off, futhi awathumeli lutho uma isicelo sinayo i-response_format.
I-shannon-2-lite ne-shannon-2-pro nazo zicabanga ngaphambi kokuphendula. Kule-endpoint zithumela imigqa yezimvo : thinking ngenkathi zicabanga, bese kuza impendulo.
I-reasoning_content ayikho kuma-typed model ama-SDK e-OpenAI. Ku-Python yifunde nge-getattr(delta, "reasoning_content", None); ku-JavaScript i-delta.reasoning_content isebenza injengoba injalo.
Ama-delta ezicelo zamathuluzi
Isicelo sethuluzi sifika siphelele: i-chunk eyodwa ngesicelo ngasinye, okuyi-delta yayo iphethe isicelo nesikhwama (string) esiphelele se-arguments. I-index inombolo izicelo zempendulo kusukela ku-0. Ikhodi ehlanganisa i-arguments ucezu ngocezu isebenza ngaphandle kokushintshwa, ngoba ihlanganisa ucezu olulodwa.
{
"tool_calls": [
{
"index": 0,
"id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
} Ngemuva kwezicelo, i-chunk yokugcina inayo i-finish_reason tool_calls.
Uma isicelo sinayo i-tools, i-shannon-1.6-lite, shannon-1.6-pro ne-shannon-coder-1 zithumela umbhalo wempendulo njenge-delta eyodwa ekugcineni kwempendulo.
I-chunk yokugcina
I-chunk yokugcina ngaphambi kwe-data: [DONE] inayo i-delta engenalutho, i-finish_reason ne-usage yesicelo, konke ku-chunk efanayo. Zonke ama-stream anayo; akudingi i-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
}
} Kuma-model e-open-weight ahlinzekiwe i-usage iphinde ibe ne-prompt_tokens_details.cached_tokens ne-completion_tokens_details.reasoning_tokens.
Ngemuva kwesicelo esine-web_search: true okusesha kwaso kuthole okuthile, i-chunk yokugcina iphinde iphathe i-sources, futhi i-chunk eyodwa ngaphambi kwayo iphethe izimpawu zezingcaphuno njenge-delta.annotations. Usesho lwewebhu
| finish_reason | Incazelo | Ithunyelwa yi- |
|---|---|---|
stop | I-model iqedile impendulo yayo, noma kuvele i-string ye-stop. | Wonke ama-model |
tool_calls | Impendulo iphethe isicelo sethuluzi esisodwa noma ngaphezulu. | Wonke ama-model |
length | Impendulo inqunyelwe emkhawulweni wokuphumayo. | Umndeni we-Shannon 3, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 |
Ama-field e-usage achazwe nge-endpoint. Chat Completions
Imigqa ye-keep-alive
Ngenkathi i-model isebenza futhi ingakabi nalutho lokuthumela, i-stream iphatha imigqa yezimvo. Ayiphethe idatha. I-SSE parser iyayeqa ngokwayo; ikhodi efunda imigqa eluhlaza kufanele iyeqe yonke imigqa eqala ngekholoni.
| Umugqa | Ithunyelwa yi- | Nini |
|---|---|---|
: ping | Umndeni we-Shannon 3, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 | Njalo ngamasekhondi angu-15. |
: keepalive | Ama-model e-open-weight ahlinzekiwe | Njalo ngamasekhondi angu-15 ngenkathi i-model isebenza. |
: thinking | shannon-2-lite, shannon-2-pro | Ngenkathi i-model icabanga. |
Amaphutha ngaphakathi kwe-stream
Uma i-stream isiqalile isimo sayo siyi-200, ngakho ukwehluleka kufika ngaphakathi kwe-stream: i-chunk enelungu le-error lapho kwakuyoba khona i-choices.
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] Ngemuva kwe-chunk yephutha i-chunk yokugcina, ene-finish_reason ne-usage, ne-data: [DONE] kusalandela. Hlola yonke i-chunk ngokuthi ine-error. Ngaphandle kokuhlola lokho impendulo ehlulekile phakathi nendlela ibukeka iphelele.
| Uhlobo | Ikhodi | Umlayezo | Nini |
|---|---|---|---|
api_error | The model backend failed to answer. Please retry. | I-model ihlulekile, noma ayibhalanga lutho. Phinda uthumele isicelo. | |
rate_limit_error | Shannon routes are temporarily busy. Please retry. | I-model ixakekile njengamanje. Linda amasekhondi ambalwa bese uphinda uthumele isicelo. | |
invalid_request_error | context_length_exceeded | Ingxoxo mide kune-context window ye-model. Yifinyeze ngaphambi kokuphinda uyithumele. Umbhalo womlayezo uyahlukahluka. |
Ama-model e-open-weight ahlinzekiwe athumela ilungu le-error elinge-type ne-message kuphela.
Ama-SDK e-OpenAI e-Python ne-JavaScript aphonsa i-chunk yephutha njengephutha le-API ngenkathi ulandelela, ngakho vala i-loop ngokuphathwa kwamaphutha okujwayelekile.
Amakhodi esimo, umzimba wephutha nokufanele kuphindwe kunekhasi lawo. Ukuphathwa kwamaphutha
Ukuvala uxhumano
Ukuvala uxhumano kumisa ukulethwa, hhayi isicelo. I-model ibhala impendulo iyiqede futhi isicelo sikhokhiswa sengathi uyifundile yonke. Ukukhokha okuncane, cela okuncane: setha i-max_tokens ephansi ku-model eyisebenzisayo.
I-stream ingaphinda iphele ngaphambi kwesikhathi endleleni iza kuwe, isibonelo ekuphukeni kwenethiwekhi noma ngenkathi iseva ivuselelwa. Iyama ngaphandle kwe-chunk yokugcina nangaphandle kwe-data: [DONE]. Thatha leyo mpendulo njengengaphelele bese uphinda uthumele isicelo.
Ukufunda i-stream ngaphandle kwe-SDK
Isifundi esilungile senza izinto ezinhlanu: sithumela amaphutha afika ngaphambi kwe-stream ekuphathweni kwamaphutha kwaso, sihlukanisa umzimba ube yimigqa, siyeqa imigqa yezimvo, simisa ku-data: [DONE], futhi sihlola i-chunk ngayinye ngokuthi ine-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); Isibonelo se-Python sisebenzisa iphakheji ye-requests. Isibonelo se-JavaScript sisebenza ku-Node.js 18 noma kamuva.
Ama-stream ezinye izimo
Ama-endpoint e-Responses ne-Messages nawo ayasakaza. Ama-frame awo aphatha umugqa we-event: onegama lomcimbi nomugqa we-data: one-JSON yawo. Ikhasi ngalinye libhala imicimbi yalo ngokulandelana.
| Ku-stream | Chat Completions | Responses | Messages |
|---|---|---|---|
| Ama-frame | Imigqa ye-data: | Imigqa ye-event: ne-data: | Imigqa ye-event: ne-data: |
| Ukucabanga kufika ku- | delta.reasoning_content | response.reasoning_summary_text.delta | thinking_delta |
| Umbhalo wempendulo ufika ku- | delta.content | response.output_text.delta | text_delta |
| I-usage ifika ku- | I-chunk yokugcina | response.completed | message_delta |
| I-stream iphela nge- | I-chunk yokugcina, bese i-data: [DONE] | response.completed | message_stop |