Umsinga
Misela i-stream ibe yi-true kwaye impendulo ifika njengemisitho ethunyelwe yi-server ngoxa imodeli iyibhala: ukuqiqa kuqala, emva koko impendulo, emva koko i-chunk yokugqibela enesizathu sokuphela kunye ne-usage. Yisebenzise nanini na umntu elindele umbhalo, nakwiimpendulo ezinde.
POST https://api.shannon-ai.com/v1/chat/completions
Ii-OpenAI SDK zikunika ii-chunk enye ngenye. Funda i-chunk nganye ngoko ikuthwalileyo: isahlulo sokuqiqa, isahlulo sempendulo, ubizo lwe-tool, okanye isiphelo sempendulo.
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
}' Indlela i-stream equlunqwe ngayo
- Impendulo inesimo
200kunye nee-headercontent-type: text/event-streamkunye ne-cache-control: no-cache. - Umsitho ngamnye ngumgca omnye oqala nge-
data:kwaye ulandelwa ngumgca ongenanto. Umbhalo emva kwe-data:yi-chunk enye ye-JSON. Akukho migca ye-event:okanye ye-id:. - Umgca oqala ngekholoni, onjenge-
: ping, yingcaciso egcina uqhagamshelo luvulekile. Uyishiye. - I-stream iphela nge-
data: [DONE]. I-stream eyeka ngaphandle kwayo ayiphelelanga.
Ii-chunk ngolandelelwano
I-chunk nganye yi-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
}
]
} Zonke ii-chunk ze-stream enye zithwala i-id, i-created kunye ne-model efanayo. I-choices ihlala iqulathe into enye. I-delta yayo iqulathe into entsha, kwaye i-finish_reason yi-null de kube yi-chunk yokugqibela.
| Isitshixo kwi-delta | Uhlobo | Inkcazelo | Ithunyelwa yi |
|---|---|---|---|
role | string | Ihlala i-assistant. Ifika kanye, ekuqaleni kwe-stream. | Iimodeli ze-open-weight ezisingathiweyo, i-shannon-2-lite, i-shannon-2-pro |
reasoning_content | string | Isahlulo sokuqiqa kwemodeli. Dibanisa izahlulo ngolandelelwano. | Iimodeli ze-open-weight ezisingathiweyo, intsapho yeShannon 3, i-shannon-1.6-pro, i-shannon-coder-1 |
content | string | Isahlulo sempendulo. Dibanisa izahlulo ngolandelelwano. | Zonke iimodeli |
tool_calls | array | Ubizo olunye olupheleleyo lwe-tool. Jonga Ii-delta zobizo lwe-tool. | Zonke iimodeli |
Ukuqiqa kuza kuqala, emva koko impendulo, emva koko naluphi na ubizo lwee-tool. Funda i-chunk ngezitshixo ezikwi-delta yayo, hayi ngendawo yayo kwi-stream: i-delta inokuqulatha i-role kunye nesahlulo sokuqala sombhalo, kwaye eyokugqibela ayinanto.
Yonke i-stream njengoko ihamba. Ukugcina imigca imfutshane, i-id, i-object, i-created kunye ne-model zishiywe ngaphandle kwi-chunk nganye apha.
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] Ii-delta zokuqiqa
Imodeli eqiqayo ithumela ukuqiqa kwayo kwi-delta.reasoning_content phambi kwempendulo. Gcina imibhalo emibini ohlukene: bonisa ukuqiqa njengenxalenye eyahlukileyo enokusongwa, okanye uyishiye.
Iimodeli ze-open-weight ezisingathiweyo azithumeli kuqiqa xa i-reasoning_effort yi-off, kwaye azithumeli nalapho isicelo sinayo i-response_format.
I-shannon-2-lite kunye ne-shannon-2-pro ziyaqiqa phambi kokuphendula nazo. Kule endpoint zithumela imigca yengcaciso : thinking ngoxa zenjenjalo, emva koko impendulo.
I-reasoning_content ayikho kwiimodeli ezinohlobo ze-OpenAI SDK. KwiPython yifunde nge-getattr(delta, "reasoning_content", None); kwiJavaScript i-delta.reasoning_content isebenza njengoko injalo.
Ii-delta zobizo lwe-tool
Ubizo lwe-tool lufika lupheleleyo: i-chunk enye ngobizo ngalunye, apho i-delta iqulathe ubizo kunye nomtya opheleleyo we-arguments. I-index inombolo ubizo lwempendulo ukususela kwi-0. Ikhowudi edibanisa i-arguments isahlulo ngesahlulo isebenza ngaphandle kotshintsho, kuba idibanisa isahlulo esinye.
{
"tool_calls": [
{
"index": 0,
"id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
} Emva kobizo, i-chunk yokugqibela inayo i-finish_reason tool_calls.
Xa isicelo sinayo i-tools, i-shannon-1.6-lite, i-shannon-1.6-pro kunye ne-shannon-coder-1 zithumela umbhalo wempendulo njenge-delta enye ekupheleni kwempendulo.
I-chunk yokugqibela
I-chunk yokugqibela phambi kwe-data: [DONE] inayo i-delta engenanto, i-finish_reason kunye ne-usage yesicelo, konke kwi-chunk enye. Yonke i-stream inayo; akufuni 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
}
} Kwiimodeli ze-open-weight ezisingathiweyo i-usage ikwanayo i-prompt_tokens_details.cached_tokens kunye ne-completion_tokens_details.reasoning_tokens.
Emva kwesicelo esine-web_search: true esikhangelo salo sifumene into, i-chunk yokugqibela iphethe ne-sources, kwaye i-chunk enye ngaphambi kwayo iphethe iimpawu zokucatshulwa njenge-delta.annotations. Uphendlo lwewebhu olwakhelwe ngaphakathi
| finish_reason | Inkcazelo | Ithunyelwa yi |
|---|---|---|
stop | Imodeli igqibile impendulo yayo, okanye umtya we-stop uvele. | Zonke iimodeli |
tool_calls | Impendulo iqulathe ubizo olunye okanye ngaphezulu lwee-tool. | Zonke iimodeli |
length | Impendulo inqunyulwe kumda wokuphuma. | Intsapho yeShannon 3, i-shannon-1.6-lite, i-shannon-1.6-pro, i-shannon-coder-1 |
Iintsimi ze-usage zichazwe kunye ne-endpoint. Chat Completions
Imigca ye-keep-alive
Ngoxa imodeli isebenza kwaye ingekabi nanto yokuthumela, i-stream ithwala imigca yengcaciso. Ayinaso idatha. Umhlalutyi we-SSE uyashiya ngokwakhe; ikhowudi efunda imigca ekrwada kufuneka ishiye yonke imigca eqala ngekholoni.
| Umgca | Ithunyelwa yi | Xa |
|---|---|---|
: ping | Intsapho yeShannon 3, i-shannon-1.6-lite, i-shannon-1.6-pro, i-shannon-coder-1 | Rhoqo emva kwemizuzwana eli-15. |
: keepalive | Iimodeli ze-open-weight ezisingathiweyo | Rhoqo emva kwemizuzwana eli-15 ngoxa imodeli isebenza. |
: thinking | shannon-2-lite, shannon-2-pro | Ngoxa imodeli iqiqa. |
Iimpazamo ngaphakathi kwe-stream
Emva kokuba i-stream iqalile isimo sayo si-200, ngoko ukusilela kufika ngaphakathi kwe-stream: i-chunk enelungu le-error apho kwakuya kuba 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] Emva kwe-chunk yempazamo, i-chunk yokugqibela, kunye ne-finish_reason ne-usage, kunye ne-data: [DONE] isalandela. Hlola yonke i-chunk ukufumana i-error. Ngaphandle kohlolo olo, impendulo esilele phakathi ibonakala igqityiwe.
| Uhlobo | I-Code | Umyalezo | Xa |
|---|---|---|---|
api_error | The model backend failed to answer. Please retry. | Imodeli isilele, okanye ayibhalanga nto. Thumela isicelo kwakhona. | |
rate_limit_error | Shannon routes are temporarily busy. Please retry. | Imodeli ixakekile ngeli xesha. Linda imizuzwana embalwa uze uthumele isicelo kwakhona. | |
invalid_request_error | context_length_exceeded | Incoko inde kuneyefestile ye-context yemodeli. Yinciphise phambi kokuba uyithumele kwakhona. Umbhalo womyalezo uyahluka. |
Iimodeli ze-open-weight ezisingathiweyo zithumela ilungu le-error kunye ne-type ne-message kuphela.
Ii-OpenAI SDK zePython neJavaScript zikhupha i-chunk yempazamo njengempazamo ye-API ngoxa uphindaphinda, ngoko songa iluphu ngokuphatha kwakho okuqhelekileyo kweempazamo.
Iikhowudi zesimo, umzimba wempazamo nento ekufuneka uyizame kwakhona zinephepha lazo. Ukuphatha imposiso
Ukuvala uqhagamshelo
Ukuvala uqhagamshelo kuyayeka ukuhanjiswa, hayi isicelo. Imodeli ibhala impendulo ide iphele kwaye isicelo sihlawulwa ngokungathi uyifundile yonke. Ukuhlawula kancinci, cela kancinci: misela i-max_tokens ephantsi kwimodeli eyisebenzisayo.
I-stream inokuphela ngaphambi kwexesha endleleni eya kuwe, umzekelo ngokophuka kwenethiwekhi okanye ngoxa i-server ihlaziywa. Emva koko iyama ngaphandle kwe-chunk yokugqibela nangaphandle kwe-data: [DONE]. Thatha loo mpendulo njengengaphelelanga uze uthumele isicelo kwakhona.
Ukufunda i-stream ngaphandle kwe-SDK
Umfundi olungileyo wenza izinto ezintlanu: uthumela iimpazamo ezifika phambi kwe-stream kwindlela yakhe yokuphatha iimpazamo, wahlula umzimba ube yimigca, ushiya imigca yengcaciso, uyeka kwi-data: [DONE], kwaye ahlole i-chunk nganye ukufumana i-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); Umzekelo wePython usebenzisa ipakethi ye-requests. Umzekelo weJavaScript usebenza kwi-Node.js 18 okanye entsha.
Ii-stream zezinye iifomathi
Ii-endpoint ze-Responses ne-Messages nazo ziyi-stream. Ii-frame zazo zithwala umgca we-event: onegama lomsitho kunye nomgca we-data: one-JSON yawo. Iphepha ngalinye lidwelisa imisitho yalo ngolandelelwano.
| Kwi-stream | Chat Completions | Responses | Messages |
|---|---|---|---|
| Ii-frame | Imigca ye-data: | Imigca ye-event: kunye ne-data: | Imigca ye-event: kunye ne-data: |
| Ukuqiqa kufika kwi | delta.reasoning_content | response.reasoning_summary_text.delta | thinking_delta |
| Umbhalo wempendulo ufika kwi | delta.content | response.output_text.delta | text_delta |
| I-usage ifika kwi | I-chunk yokugqibela | response.completed | message_delta |
| I-stream iphela nge | I-chunk yokugqibela, emva koko i-data: [DONE] | response.completed | message_stop |