Nzipu ozugbo
Tọọ stream na true azịza ahụ na-abịa dị ka server-sent events ka model na-ede ya: reasoning buru ụzọ, wee azịza, wee chunk ikpeazụ nwere finish reason na usage. Jiri ya mgbe ọ bụla mmadụ na-eche text, na maka azịza ogologo.
POST https://api.shannon-ai.com/v1/chat/completions
OpenAI SDKs na-enye gị chunks otu otu. Gụọ chunk ọ bụla site n'ihe ọ na-ebu: akụkụ reasoning, akụkụ azịza, tool call, ma ọ bụ njedebe nke azịza.
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
}' Otu e si akpụ stream
- Azịza nwere status
200na headerscontent-type: text/event-streamnacache-control: no-cache. - Event ọ bụla bụ otu ahịrị na-amalite na
data:ma ahịrị efu na-eso ya. Ederede mgbedata:bụ otu JSON chunk. Enweghị ahịrịevent:ma ọ bụid:. - Ahịrị na-amalite na colon, dị ka
: ping, bụ comment na-edebe njikọ mepere. Gafee ya. - Stream na-agwụ na
data: [DONE]. Stream kwụsịrị na-enweghị ya zughị ezu.
Chunks n'usoro
Chunk ọ bụla bụ chat.completion.chunk object:
{
"id": "chatcmpl-5f0c1e7a9b3d4c62a8e1f07d2b46c9a3",
"object": "chat.completion.chunk",
"created": 1791625200,
"model": "shannon-3",
"choices": [
{
"index": 0,
"delta": {
"content": "Server-sent"
},
"finish_reason": null
}
]
} Chunks niile nke otu stream na-ebu otu id, created na model. choices nwere otu entry mgbe niile. delta ya nwere ihe ọhụrụ, finish_reason bụkwa null ruo chunk ikpeazụ.
| Key na delta | Ụdị | Nkọwa | Onye zipụrụ |
|---|---|---|---|
role | string | Mgbe niile assistant. Ọ na-abịa otu ugboro, na mmalite nke stream. | Hosted open-weight models, shannon-2-lite, shannon-2-pro |
reasoning_content | string | Otu akụkụ nke reasoning model. Jikọta akụkụ ndị ahụ n'usoro. | Hosted open-weight models, Shannon 3 family, shannon-1.6-pro na shannon-coder-1 |
content | string | Otu akụkụ nke azịza. Jikọta akụkụ ndị ahụ n'usoro. | Models niile |
tool_calls | array | Otu tool call zuru ezu. Lee Tool call deltas. | Models niile |
Reasoning na-abịa buru ụzọ, wee azịza, wee tool calls ọ bụla. Gụọ chunk site na keys dị na delta ya, ọ bụghị site n'ọnọdụ ya na stream: delta nwere ike ibu role ya na akụkụ text mbụ, nke ikpeazụ bụkwa efu.
Stream dum dị ka ọ si aga. Iji mee ka ahịrị dị mkpụmkpụ, id, object, created na model ka hapụrụ n'ime chunk ọ bụla ebe a.
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 na-eche echiche na-ezipu reasoning ya na delta.reasoning_content tupu azịza. Debe ederede abụọ ahụ iche: gosi reasoning dị ka akụkụ dị iche enwere ike ịpịkọta, ma ọ bụ hapụ ya.
Hosted open-weight models anaghị ezipu reasoning mgbe reasoning_effort bụ off, na mgbe request nwere response_format.
shannon-2-lite na shannon-2-pro na-eche echiche tupu ha aza nkekwa. Na endpoint a ha na-ezipu comment lines : thinking mgbe ha na-eme nke ahụ, wee azịza.
reasoning_content anọghị na typed models nke OpenAI SDKs. Na Python gụọ ya site na getattr(delta, "reasoning_content", None); na JavaScript delta.reasoning_content na-arụ ọrụ dị ka ọ dị.
Tool call deltas
Tool call na-abịa zuru ezu: otu chunk maka call ọ bụla, nke delta ya nwere call ahụ na string arguments zuru ezu. index na-agụ calls nke azịza site na 0. Koodu na-ejikọta arguments akụkụ site na akụkụ na-arụ ọrụ na-enweghị mgbanwe, n'ihi na ọ na-ejikọta otu akụkụ.
{
"tool_calls": [
{
"index": 0,
"id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
} Mgbe calls gasịrị, chunk ikpeazụ nwere finish_reason tool_calls.
Mgbe request nwere tools, shannon-1.6-lite, shannon-1.6-pro na shannon-coder-1 na-ezipu ederede azịza dị ka otu delta na njedebe nke azịza.
Chunk ikpeazụ
Chunk ikpeazụ tupu data: [DONE] nwere delta efu, finish_reason na usage nke request, ha niile n'otu chunk. Stream ọ bụla nwere ya; ịchọghị 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
}
} Na hosted open-weight models usage nwekwara prompt_tokens_details.cached_tokens na completion_tokens_details.reasoning_tokens.
Mgbe request nwere web_search: true nke search ya chọtara ihe, chunk ikpeazụ na-ebukwa sources, otu chunk tupu ya na-ebukwa akara nkwughachi dị ka delta.annotations. Chọọ weebụ
| finish_reason | Nkọwa | Onye zipụrụ |
|---|---|---|
stop | Model mechiri azịza ya, ma ọ bụ string stop pụtara. | Models niile |
tool_calls | Azịza nwere otu tool call ma ọ bụ karịa. | Models niile |
length | E bipụrụ azịza na output limit. | Shannon 3 family, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 |
A kọwara fields nke usage na endpoint. Chat Completions
Keep-alive lines
Mgbe model na-arụ ọrụ ma enweghị ihe ọ ga-ezipu ugbu a, stream na-ebu comment lines. Ha enweghị data. SSE parser na-agafe ha n'onwe ya; koodu na-agụ raw lines ga-agafe ahịrị ọ bụla na-amalite na colon.
| Ahịrị | Onye zipụrụ | Mgbe |
|---|---|---|
: ping | Shannon 3 family, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 | Kwa sekọnd 15. |
: keepalive | Hosted open-weight models | Kwa sekọnd 15 mgbe model na-arụ ọrụ. |
: thinking | shannon-2-lite, shannon-2-pro | Mgbe model na-eche echiche. |
Njehie n'ime stream
Mgbe stream malitechara status ya bụ 200, ya mere ọdịda na-abịa n'ime stream: chunk nwere member error ebe choices ga-adị.
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] Mgbe error chunk gasịrị, chunk ikpeazụ, nwere finish_reason na usage, na data: [DONE] ka na-eso. Lelee chunk ọ bụla maka error. Na-enweghị nlele ahụ azịza dara n'etiti ụzọ dị ka nke zuru ezu.
| Ụdị | Koodu | Ozi | Mgbe |
|---|---|---|---|
api_error | The model backend failed to answer. Please retry. | Model dara, ma ọ bụ ede ihe ọ bụla. Zighachi request ahụ. | |
rate_limit_error | Shannon routes are temporarily busy. Please retry. | Model nọ n'ọrụ n'oge a. Chere sekọnd ole na ole ma zighachi request ahụ. | |
invalid_request_error | context_length_exceeded | Mkparịta ụka ka ogologo karịa context window nke model. Mee ka ọ dị mkpụmkpụ tupu ị zighachi ya. Ederede ozi na-agbanwe. |
Hosted open-weight models na-ezipu member error nwere naanị type na message.
OpenAI Python na JavaScript SDKs na-ebili error chunk dị ka API error mgbe ị na-eme iteration, ya mere kechie loop n'njikwa njehie gị nkịtị.
Status codes, error body na ihe a ga-ezighachi nwere peeji nke ha. Njikwa njehie
Imechi njikọ
Imechi njikọ na-akwụsị nnyefe, ọ bụghị request. Model na-ede azịza ruo njedebe ya, a na-akwụkwa ụgwọ request dị ka ị gụchara ya dum. Iji kwụọ obere, rịọ obere: tọọ max_tokens dị ala na model na-etinye ya.
Stream nwekwara ike ịkwụsị n'oge n'ụzọ ya gaa gị, dịka na nkwụsị netwọk ma ọ bụ mgbe a na-emelite server. Mgbe ahụ ọ na-akwụsị na-enweghị chunk ikpeazụ na-enweghị data: [DONE]. Lee azịza ahụ dị ka nke zughị ezu ma zighachi request ahụ.
Ịgụ stream na-enweghị SDK
Onye na-agụ ziri ezi na-eme ihe ise: ọ na-ezipu njehie na-abịa tupu stream gaa n'njikwa njehie ya, na-ekewa body n'ahịrị, na-agafe comment lines, na-akwụsị na data: [DONE], ma na-elele chunk ọ bụla maka 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); Python sample na-eji package requests. JavaScript sample na-agba na Node.js 18 ma ọ bụ nke ọhụrụ karịa.
Streams nke formats ndị ọzọ
Responses na Messages endpoints na-eme stream nkekwa. Frames ha na-ebu ahịrị event: nwere aha event na ahịrị data: nwere JSON ya. Peeji ọ bụla na-depụta events ya n'usoro.
| Na stream | Chat Completions | Responses | Messages |
|---|---|---|---|
| Frames | Ahịrị data: | Ahịrị event: na data: | Ahịrị event: na data: |
| Reasoning na-abịa na | delta.reasoning_content | response.reasoning_summary_text.delta | thinking_delta |
| Ederede azịza na-abịa na | delta.content | response.output_text.delta | text_delta |
| Usage na-abịa na | Chunk ikpeazụ | response.completed | message_delta |
| Stream na-agwụ na | Chunk ikpeazụ, wee data: [DONE] | response.completed | message_stop |