Phallela
Beha stream ho true mme karabo e fihla e le server-sent events ha model e e ngola: reasoning pele, ebe karabo, ebe chunk ea ho qetela e nang le lebaka la ho fela le usage. E sebelise neng kapa neng ha motho a emetse mongolo, le bakeng sa likarabo tse telele.
POST https://api.shannon-ai.com/v1/chat/completions
Li-SDK tsa OpenAI li u fa li-chunk e 'ngoe ka e 'ngoe. Bala chunk e 'ngoe le e 'ngoe ka seo e se nkang: sekhechana sa reasoning, sekhechana sa karabo, kopo ea tool, kapa qetello ea karabo.
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
}' Hore na stream e entsoe joang
- Karabo e na le boemo ba
200le li-headercontent-type: text/event-streamlecache-control: no-cache. - Event e 'ngoe le e 'ngoe ke mohala o le mong o qalang ka
data:mme o latelwa ke mohala o se nang letho. Mongolo o ka mor'adata:ke chunk e le 'ngoe ea JSON. Ha ho mela eaevent:kapaid:. - Mohala o qalang ka colon, o kang
: ping, ke maikutlo a bulang connection. O tlole. - Stream e fela ka
data: [DONE]. Stream e emang ntle le eona ha e phethahale.
Li-chunk ka tatellano
Chunk e 'ngoe le e 'ngoe ke ntho ea 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
}
]
} Li-chunk tsohle tsa stream e le 'ngoe li nka id, created le model tse tšoanang. choices kamehla e na le entry e le 'ngoe. delta ea eona e na le se secha, mme finish_reason ke null ho fihlela chunk ea ho qetela.
| Key ho delta | Mofuta | Tlhaloso | E rometsoe ke |
|---|---|---|---|
role | string | Kamehla ke assistant. E fihla hang, qalong ea stream. | Li-model tse hosted tsa open-weight, shannon-2-lite, shannon-2-pro |
reasoning_content | string | Sekhechana sa reasoning ea model. Kopanya likhechana ka tatellano. | Li-model tse hosted tsa open-weight, lelapa la Shannon 3, shannon-1.6-pro, shannon-coder-1 |
content | string | Sekhechana sa karabo. Kopanya likhechana ka tatellano. | Li-model tsohle |
tool_calls | array | Kopo e le 'ngoe e feletseng ea tool. Bona Tool call deltas. | Li-model tsohle |
Reasoning e tla pele, ebe karabo, ebe likopo leha e le life tsa tool. Bala chunk ka li-key tsa delta ea eona, eseng ka sebaka sa eona ho stream: delta e ka ba le role hammoho le sekhechana sa pele sa mongolo, mme ea ho qetela ha e na letho.
Stream eohle joalo ka ha e tsamaea. Ho boloka mela e khutšoane, id, object, created le model li siuoe ho chunk e 'ngoe le e 'ngoe mona.
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] Li-delta tsa reasoning
Model e nahanang e romela reasoning ea eona ho delta.reasoning_content pele ho karabo. Boloka mengolo e mebeli e arohane: bontša reasoning e le karolo e arohaneng, e ka kobehang, kapa u e tlose.
Li-model tse hosted tsa open-weight ha li romele reasoning ha reasoning_effort e le off, le ha kopo e na le response_format.
shannon-2-lite le shannon-2-pro li nahana pele li araba le tsona. Ho endpoint ena li romela mela ea maikutlo ea : thinking ha li ntse li etsa joalo, ebe karabo.
reasoning_content ha e ho li-model tse tlhalositsoeng tsa li-SDK tsa OpenAI. Ho Python e bale ka getattr(delta, "reasoning_content", None); ho JavaScript delta.reasoning_content e sebetsa joalo ka ha e le.
Li-delta tsa likopo tsa tool
Kopo ea tool e fihla e felletse: chunk e le 'ngoe ka kopo, eo delta ea eona e nang le kopo e nang le string e feletseng ea arguments. index e nomora likopo tsa karabo ho tloha ho 0. Code e kopanyang arguments sekhechana ka sekhechana e sebetsa ntle le phetoho, hobane e kopanya sekhechana se le seng.
{
"tool_calls": [
{
"index": 0,
"id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
} Ka mor'a likopo, chunk ea ho qetela e na le finish_reason tool_calls.
Ha kopo e na le tools, shannon-1.6-lite, shannon-1.6-pro le shannon-coder-1 li romela mongolo oa karabo e le delta e le 'ngoe qetellong ea karabo.
Chunk ea ho qetela
Chunk ea ho qetela pele ho data: [DONE] e na le delta e se nang letho, finish_reason le usage ea kopo, tsohle chunk e le 'ngoe. Stream e 'ngoe le e 'ngoe e na le eona; ha u hloke 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
}
} Ho li-model tse hosted tsa open-weight usage e boetse e na le prompt_tokens_details.cached_tokens le completion_tokens_details.reasoning_tokens.
Ka mor'a kopo e nang le web_search: true eo patlo ea eona e fumaneng eng kapa eng, chunk ea ho qetela e boetse e nka sources, mme chunk e le 'ngoe pele ho eona e nka matšoao a litšupiso e le delta.annotations. Patlo ya webe
| finish_reason | Tlhaloso | E rometsoe ke |
|---|---|---|
stop | Model e qetile karabo ea eona, kapa string ea stop e hlahile. | Li-model tsohle |
tool_calls | Karabo e na le kopo e le 'ngoe kapa tse ngata tsa tool. | Li-model tsohle |
length | Karabo e khaoloe moeling oa output. | Lelapa la Shannon 3, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 |
Li-field tsa usage li hlalositsoe le endpoint. Chat Completions
Mela ea keep-alive
Ha model e ntse e sebetsa mme e se na letho la ho romela, stream e nka mela ea maikutlo. Ha e na data. SSE parser e e tlola ka bo eona; code e balang mela e tala e tlameha ho tlola mohala o mong le o mong o qalang ka colon.
| Mohala | E rometsoe ke | Neng |
|---|---|---|
: ping | Lelapa la Shannon 3, shannon-1.6-lite, shannon-1.6-pro, shannon-coder-1 | Ka mor'a metsotsoana e 15 e 'ngoe le e 'ngoe. |
: keepalive | Li-model tse hosted tsa open-weight | Ka mor'a metsotsoana e 15 e 'ngoe le e 'ngoe ha model e ntse e sebetsa. |
: thinking | shannon-2-lite, shannon-2-pro | Ha model e ntse e nahana. |
Liphoso ka hare ho stream
Hang ha stream e qalile boemo ba eona ke 200, kahoo ho hloleha ho fihla ka hare ho stream: chunk e nang le setho sa error moo choices e neng e tla ba teng.
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] Ka mor'a chunk ea phoso chunk ea ho qetela, e nang le finish_reason le usage, le data: [DONE] li ntse li latela. Hlahloba chunk e 'ngoe le e 'ngoe bakeng sa error. Ntle le hlahlobo eo karabo e hlolehileng bohareng e shebahala e phethahetse.
| Mofuta | Code | Molaetsa | Neng |
|---|---|---|---|
api_error | The model backend failed to answer. Please retry. | Model e hlolehile, kapa ha ea ngola letho. Romela kopo hape. | |
rate_limit_error | Shannon routes are temporarily busy. Please retry. | Model e phathahane ka nako ena. Emela metsotsoana e seng mekae mme u romele kopo hape. | |
invalid_request_error | context_length_exceeded | Moqoqo o molelele ho feta context window ea model. O khutsufatse pele u o romela hape. Mongolo oa molaetsa oa fapana. |
Li-model tse hosted tsa open-weight li romela setho sa error se nang le type le message feela.
Li-SDK tsa OpenAI tsa Python le JavaScript li hlahisa chunk ea phoso e le phoso ea API ha u ntse u pheta, kahoo kenya loop ho error handling ea hau e tloaelehileng.
Likhoutu tsa boemo, body ea phoso le seo u lokelang ho se leka hape li na le leqephe la tsona. Diphoso
Ho koala connection
Ho koala connection ho emisa ho fana, eseng kopo. Model e ngola karabo ho fihlela qetellong mme kopo e lefisoa joalo ka hore u e baletse kaofela. Ho lefa tse fokolang, kopa tse fokolang: beha max_tokens e tlase ho model e e sebelisang.
Stream e ka boela ea fela kapele tseleng e eang ho uena, mohlala ha marang-rang a khaoha kapa ha server e ntse e nchafatsoa. Joale e emisa ntle le chunk ea ho qetela le ntle le data: [DONE]. Nka karabo eo e le e sa phethahalang mme u romele kopo hape.
Ho bala stream ntle le SDK
Moreki ea nepahetseng o etsa lintho tse hlano: o romela liphoso tse fihlang pele ho stream ho error handling ea oona, o arola body ka mela, o tlola mela ea maikutlo, o ema ho data: [DONE], mme o hlahloba chunk e 'ngoe le e 'ngoe bakeng sa 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); Mohlala oa Python o sebelisa package ea requests. Mohlala oa JavaScript o sebetsa ho Node.js 18 kapa e ncha.
Li-stream tsa mebopeho e meng
Li-endpoint tsa Responses le Messages li etsa streaming le tsona. Li-frame tsa tsona li nka mohala oa event: o nang le lebitso la event le mohala oa data: o nang le JSON ea eona. Leqephe le leng le le leng le thathamisa li-event tsa lona ka tatellano.
| Ho stream | Chat Completions | Responses | Messages |
|---|---|---|---|
| Li-frame | Mela ea data: | Mela ea event: le data: | Mela ea event: le data: |
| Reasoning e fihla ho | delta.reasoning_content | response.reasoning_summary_text.delta | thinking_delta |
| Mongolo oa karabo o fihla ho | delta.content | response.output_text.delta | text_delta |
| Usage e fihla ho | Chunk ea ho qetela | response.completed | message_delta |
| Stream e fela ka | Chunk ea ho qetela, ebe data: [DONE] | response.completed | message_stop |