Responses API
НовоPOST /v1/responses прима упатства и листа од влезни ставки и враќа објект на одговор составен од излезни ставки, во форматот OpenAI Responses. Користете го со responses API на SDK-то на OpenAI и со алатки изградени врз него, како Codex CLI. Ендпоинтот не чува состојба: испраќајте го целиот разговор со секое барање.
POST https://api.shannon-ai.com/v1/responses
Најмалото барање е ид на модел и текст. Одговорот не е со streaming освен ако не го побарате.
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.shannon-ai.com/v1",
)
response = client.responses.create(
model="shannon-3",
input="Say hello in one sentence.",
)
print(response.output_text) import OpenAI from "openai";
const client = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.shannon-ai.com/v1",
});
const response = await client.responses.create({
model: "shannon-3",
input: "Say hello in one sentence.",
});
console.log(response.output_text); curl https://api.shannon-ai.com/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "shannon-3",
"input": "Say hello in one sentence."
}' Одговорот е објект response. Неговиот output го содржи reasoning-от, кога моделот правел reasoning, и пораката:
{
"id": "resp_5f0c1e7a9b3d4c62a8e1f07d2b46c9a3",
"object": "response",
"created_at": 1791625200,
"model": "shannon-3",
"status": "completed",
"error": null,
"incomplete_details": null,
"instructions": null,
"metadata": {},
"parallel_tool_calls": true,
"temperature": null,
"tool_choice": "auto",
"tools": [],
"top_p": null,
"output": [
{
"id": "rs_8a2e6c1f4b7d4e03b9c5a1d70f3e2b64",
"type": "reasoning",
"summary": [
{
"type": "summary_text",
"text": "The user wants a greeting in one sentence. Keep it short and friendly."
}
]
},
{
"id": "msg_1c7b9e3a5d2f4a86b0e4c8d19a6f7e25",
"type": "message",
"role": "assistant",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "Hello, it is good to meet you.",
"annotations": []
}
]
}
],
"usage": {
"input_tokens": 1184,
"output_tokens": 46,
"total_tokens": 1230
}
} Полиња за барање
model и input се она што го бара барањето. Колоната Го применуваат ги наведува моделите на кои полето го менува одговорот. Хостираните open-weight модели се дванаесетте идови од листата на модели; фамилијата Shannon 3 се shannon-3, shannon-3-pro, shannon-3.1 и shannon-3.1-pro. Модели и цени
| Поле | Тип | Стандардно | Опис | Го применуваат |
|---|---|---|---|---|
model | string | Задолжително. Ид од листата на модели. Совпаѓањето не е осетливо на големи и мали букви. Недостасувачки или необјавен ид враќа 400 unknown model. | Сите модели | |
input | string | array | Стринг, кој се чита како една порака од корисник, или низа од влезни ставки. Видете Влезни ставки подолу. | Сите модели | |
instructions | string | Упатства за моделот, system prompt-от на овој формат. | Хостирани open-weight модели, shannon-1.6-*, shannon-2-*, shannon-coder-1 | |
stream | boolean | false | true го испраќа одговорот како server-sent events. Видете Streaming подолу. | Сите модели |
max_output_tokens | integer | 4096 | Горна граница на одговорот, во токени. Вредност надвор од 1 до 65,536 се поместува во тој опсег. Тоа е и износот одвоен од вашето салдо додека барањето се извршува. Видете Излезно ограничување подолу. | Хостирани open-weight модели, shannon-1.6-*, shannon-2-*, shannon-coder-1 |
temperature | number | Температура на семплирање. На хостираните open-weight модели вредностите се држат помеѓу 0 и 2. | Хостирани open-weight модели; shannon-1.6-*, shannon-2-* и shannon-coder-1 во одговори без streaming | |
top_p | number | Nucleus семплирање. Вредностите се држат помеѓу 0 и 1. | Хостирани open-weight модели | |
tools | array | Функциите што моделот може да ги повика, во рамниот облик на овој формат: {"type": "function", "name", "description", "parameters"}. Видете Алатки подолу. | Сите модели | |
tool_choice | string | object | auto | "auto" му дозволува на моделот да одлучи. "required" го тера да повика алатка. {"type": "function", "name": "…"} го тера да ја повика таа алатка. | Хостирани open-weight модели |
reasoning | object | {"effort": "…"} со off, low, medium или high. Секоја друга вредност враќа 400. | Хостирани open-weight модели | |
text | object | {"format": {…}} бара JSON одговор. Видете Структуриран излез подолу. | Сите нивоа на Shannon; хостирани open-weight модели како што е наведено по ид |
previous_response_id, store, metadata, parallel_tool_calls, truncation, include, user и prompt_cache_key се прифаќаат за постоечкиот клиентски код да работи непроменет. Не го менуваат одговорот. Бидејќи не се чува разговор, следното барање ги носи претходните чекори во input.
Влезни ставки
Влезната ставка е или порака, со role и content, или типизирана ставка што носи повик на алатка или неговиот резултат. content е стринг или низа од делови.
| Ставка | Опис | Го применуваат |
|---|---|---|
{"role": "user", "content": …} | Тоа што го прашувате. content е стринг, или делови input_text и input_image. | Сите модели |
{"role": "assistant", "content": …} | Претходен одговор на моделот. content е стринг, или делови output_text. | Сите модели |
{"role": "system", "content": …}{"role": "developer", "content": …} | Упатства во рамките на разговорот. | Хостирани open-weight модели |
{"type": "function_call", "call_id": "…", "name": "…", "arguments": "…"} | Повик на алатка што моделот го направил во претходен одговор. arguments е JSON стринг. | Сите модели |
{"type": "function_call_output", "call_id": "…", "output": "…"} | Резултатот од тој повик. call_id е идот на повикот, а output е резултатот како стринг. | Сите модели |
Ставете ги упатствата во полето instructions. Со ид од фамилијата Shannon 3, упатствата што мора да важат ставете ги во пораката user.
Ставките од output на одговорот можат да се вратат во input какви што се: ставките message и function_call се читаат, ставките reasoning се прескокнуваат.
Делови на содржина
| Дел | Опис | Достапно на |
|---|---|---|
{"type": "input_text", "text": "…"} | Текст на порака од корисник. | Сите модели |
{"type": "output_text", "text": "…"} | Текст на порака од assistant. | Сите модели |
{"type": "input_image", "image_url": "…"} | Слика, како data: URL со base64 содржина или како http(s) URL. | Фамилијата Shannon 3, shannon-1.6-lite, shannon-1.6-pro и хостираните open-weight модели што наведуваат влез на слики |
{"type": "input_file", "file_data": "data:application/pdf;base64,…"} | Документ (PDF, Word, PowerPoint или Excel): file_data содржи data: URL, или file_url содржи http(s) URL. | Фамилијата Shannon 3 |
На нивоата на Shannon сликите и датотеките се читаат од последната ставка user во input. Големините и ограничувањата имаат своја страница. Слики и датотеки
Барање со упатства и опции
Ова барање испраќа упатства, разговор како влезни ставки, излезно ограничување, температура и напор на reasoning. Користи хостиран open-weight модел, кој ги применува сите.
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.shannon-ai.com/v1",
)
response = client.responses.create(
model="DeepSeek-V4-Flash-0731-W4A16-AUTOROUND-REAP",
instructions="You are a physics teacher. Answer in two sentences.",
input=[
{"role": "user", "content": "Why is the sky blue?"},
{"role": "assistant", "content": "Air scatters blue light more than red light."},
{"role": "user", "content": "And why are sunsets red?"},
],
max_output_tokens=512,
temperature=0.3,
reasoning={"effort": "low"},
)
for item in response.output:
if item.type == "reasoning":
print("reasoning:", item.summary[0].text)
elif item.type == "message":
print("answer:", item.content[0].text)
print(response.usage) import OpenAI from "openai";
const client = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.shannon-ai.com/v1",
});
const response = await client.responses.create({
model: "DeepSeek-V4-Flash-0731-W4A16-AUTOROUND-REAP",
instructions: "You are a physics teacher. Answer in two sentences.",
input: [
{ role: "user", content: "Why is the sky blue?" },
{ role: "assistant", content: "Air scatters blue light more than red light." },
{ role: "user", content: "And why are sunsets red?" },
],
max_output_tokens: 512,
temperature: 0.3,
reasoning: { effort: "low" },
});
for (const item of response.output) {
if (item.type === "reasoning") console.log("reasoning:", item.summary[0].text);
if (item.type === "message") console.log("answer:", item.content[0].text);
}
console.log(response.usage); curl https://api.shannon-ai.com/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "DeepSeek-V4-Flash-0731-W4A16-AUTOROUND-REAP",
"instructions": "You are a physics teacher. Answer in two sentences.",
"input": [
{"role": "user", "content": "Why is the sky blue?"},
{"role": "assistant", "content": "Air scatters blue light more than red light."},
{"role": "user", "content": "And why are sunsets red?"}
],
"max_output_tokens": 512,
"temperature": 0.3,
"reasoning": {"effort": "low"}
}' Одговорот на хостиран open-weight модел ги има id, object, model, created_at, status, output и usage. Неговиот usage додава токени прочитани од кешот и токени потрошени на reasoning:
{
"usage": {
"input_tokens": 58,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens": 67,
"output_tokens_details": {
"reasoning_tokens": 19
},
"total_tokens": 125
}
} Објектот на одговорот
id, object, status, output и usage се на секој одговор. Градете го вашиот код врз нив.
| Поле | Тип | Опис | Го испраќа |
|---|---|---|---|
id | string | resp_ проследено со 32 хексадецимални знаци. | Сите модели |
object | string | Секогаш response. | Сите модели |
status | string | completed. Во streaming прво е in_progress, а failed во настан response.failed. | Сите модели |
output | array | Излезните ставки по редоследот по кој ги создал моделот: reasoning, message, function_call. | Сите модели |
usage | object | input_tokens, output_tokens и total_tokens. | Сите модели |
usage.input_tokens_details | object | cached_tokens: влезните токени прочитани од кешот на prompt. | Хостирани open-weight модели |
usage.output_tokens_details | object | reasoning_tokens: излезните токени потрошени на reasoning. | Хостирани open-weight модели |
model | string | Каноничниот ид на моделот што одговорил. | Фамилијата Shannon 3, хостирани open-weight модели |
created_at | integer | Време на одговорот, во Unix секунди. | Фамилијата Shannon 3, хостирани open-weight модели |
instructions, tools, temperature, … | instructions, tools и temperature го повторуваат барањето. error и incomplete_details се null, metadata е {}, parallel_tool_calls е true, tool_choice е auto, а top_p е null. | Фамилијата Shannon 3 |
Излезни ставки
| Ставка | Опис |
|---|---|
{"id": "rs_…", "type": "reasoning", "summary": [{"type": "summary_text", "text": "…"}]} | Reasoning-от на моделот како еден дел summary_text. Присутно само кога моделот правел reasoning. |
{"id": "msg_…", "type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "…"}]} | Одговорот: еден дел output_text со текстот. |
{"id": "fc_…", "type": "function_call", "call_id": "call_…", "name": "…", "arguments": "…"} | Повик на алатка. arguments е JSON стринг. Испратете го резултатот назад со истиот call_id. |
SDK-ата на OpenAI го спојуваат текстот на пораката наместо вас во response.output_text.
Streaming
Поставете stream на true за server-sent events. Секој фрејм има ред event: со името на настанот и ред data: со JSON објект; објектот го повторува името во type. Поврзувајте ги delta-ите со нивната ставка преку output_index.
Со SDK на OpenAI, читајте ги настаните според нивниот type:
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.shannon-ai.com/v1",
)
stream = client.responses.create(
model="shannon-3",
input="Explain server-sent events in three sentences.",
stream=True,
)
for event in stream:
kind = getattr(event, "type", "error") # an event without a type is an error event
if kind == "response.reasoning_summary_text.delta":
pass # a piece of reasoning: event.delta
elif kind == "response.output_text.delta":
print(event.delta, end="", flush=True)
elif kind == "response.output_item.done" and event.item.type == "function_call":
print("\ntool call:", event.item.name, event.item.arguments)
elif kind == "response.completed":
print("\n", event.response.usage)
elif kind in ("response.failed", "error"):
raise RuntimeError("the stream failed, send the request again") import OpenAI from "openai";
const client = new OpenAI({
apiKey: "YOUR_API_KEY",
baseURL: "https://api.shannon-ai.com/v1",
});
const stream = await client.responses.create({
model: "shannon-3",
input: "Explain server-sent events in three sentences.",
stream: true,
});
for await (const event of stream) {
if (event.type === "response.reasoning_summary_text.delta") {
// a piece of reasoning: event.delta
} else if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
} else if (event.type === "response.output_item.done" && event.item.type === "function_call") {
console.log("\ntool call:", event.item.name, event.item.arguments);
} else if (event.type === "response.completed") {
console.log("\n", event.response.usage);
} else if (event.type === "response.failed" || event.type === "error") {
throw new Error("the stream failed, send the request again");
}
} curl -N https://api.shannon-ai.com/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "shannon-3",
"input": "Explain server-sent events in three sentences.",
"stream": true
}' Настаните пристигнуваат по овој редослед. Групите за reasoning, пораката и повиците на алатки се појавуваат само кога одговорот ги има.
| Настан | Содржина | Кога |
|---|---|---|
response.created | response | Секогаш прв. response.status е in_progress, а response.output е празен. |
response.in_progress | response | Секогаш втор, со истиот објект. |
response.output_item.added | output_index, item | Reasoning-от започнува: ставка reasoning со празен summary. |
response.reasoning_summary_text.delta | output_index, summary_index, delta | Парче од reasoning-от. |
response.reasoning_summary_text.done | output_index, summary_index, text | Reasoning-от е готов: неговиот цел text. |
response.output_item.done | output_index, item | Завршената ставка reasoning. |
response.output_item.added | output_index, item | Одговорот започнува: ставка message со статус in_progress и без содржина. |
response.content_part.added | output_index, content_index, part | Се отвора празен дел output_text. |
response.output_text.delta | output_index, content_index, delta | Парче од одговорот. |
response.output_text.done | output_index, content_index, text | Одговорот е готов: неговиот цел text. |
response.content_part.done | output_index, content_index, part | Завршениот дел output_text. |
response.output_item.done | output_index, item | Завршената ставка message, со статус completed. |
response.output_item.added | output_index, item | Започнува повик на алатка: ставка function_call со call_id, name и празни arguments. |
response.function_call_arguments.delta | output_index, delta | Аргументите на повикот, комплетни во една delta. |
response.function_call_arguments.done | output_index, arguments | Истите аргументи, како arguments. |
response.output_item.done | output_index, item | Завршената ставка function_call. |
response.completed | response | Секогаш последен при успех: целиот објект response со output и usage. |
event: response.created
data: {"type":"response.created","response":{"id":"resp_5f0c…","object":"response","status":"in_progress","output":[], …}}
event: response.in_progress
data: {"type":"response.in_progress","response":{"id":"resp_5f0c…","object":"response","status":"in_progress","output":[], …}}
event: response.output_item.added
data: {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_1c7b…","type":"message","role":"assistant","status":"in_progress","content":[]}}
event: response.content_part.added
data: {"type":"response.content_part.added","output_index":0,"content_index":0,"part":{"type":"output_text","text":""}}
event: response.output_text.delta
data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"Server-sent"}
event: response.output_text.delta
data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":" events let a server push text over one HTTP reply."}
event: response.output_text.done
data: {"type":"response.output_text.done","output_index":0,"content_index":0,"text":"Server-sent events let a server push text over one HTTP reply."}
event: response.content_part.done
data: {"type":"response.content_part.done","output_index":0,"content_index":0,"part":{"type":"output_text","text":"Server-sent events let a server push text over one HTTP reply."}}
event: response.output_item.done
data: {"type":"response.output_item.done","output_index":0,"item":{"id":"msg_1c7b…","type":"message","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Server-sent events let a server push text over one HTTP reply.","annotations":[]}]}}
event: response.completed
data: {"type":"response.completed","response":{"id":"resp_5f0c…","object":"response","status":"completed","output":[…],"usage":{"input_tokens":1190,"output_tokens":18,"total_tokens":1208}, …}} Streaming што не успева
На нивоата на Shannon неуспешниот одговор завршува со response.failed наместо response.completed. Неговиот response.status е failed, а response.error содржи code, rate_limit_exceeded или server_error, и message.
На хостираните open-weight модели неуспехот е настан error со code api_error и message. По него сепак следува response.completed.
Третирајте го streaming-от како неуспешен кога содржи response.failed или настан error, и испратете го барањето повторно.
Алатки
Алатката е функција што ја извршува вашиот код. Опишете ја во tools; кога моделот ја сака, одговорот содржи ставка function_call наместо пораката или покрај неа.
Дефиниција на алатка во tools:
[
{
"type": "function",
"name": "get_weather",
"description": "Current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
}
] output на одговор што ја повикува:
[
{
"id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"type": "function_call",
"name": "get_weather",
"call_id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"arguments": "{\"city\":\"Paris\"}"
}
] Извршете ја функцијата, па испратете го барањето повторно со додаден повик и неговиот резултат во input:
[
{
"role": "user",
"content": "What is the weather in Paris?"
},
{
"type": "function_call",
"call_id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
},
{
"type": "function_call_output",
"call_id": "call_3d9a7c1e5b2f4a60c8e1d7f09b24a6c5",
"output": "{\"temperature_c\": 18, \"sky\": \"cloudy\"}"
}
] Се читаат само алатки од тип function. На shannon-1.6-*, shannon-2-* и shannon-coder-1 schema на parameters се сведува на заедничките клучни зборови на JSON Schema: oneOf се чита како anyOf, а клучни зборови како $ref, additionalProperties, const, default и title не се проследуваат до моделот.
Вредностите на tool_choice required и именувана функција ги применуваат хостираните open-weight модели.
Јамката на алатки е опишана во целост на нејзина страница. Повик на функции
Структуриран излез
Овој формат го запишува структурираниот излез како text.format. Schema е директно во format, покрај name и strict, а не под член json_schema како на Chat Completions.
{"type": "json_object"}бара кој било JSON објект.{"type": "json_schema", "name", "schema", "strict"}бара JSON што ја следи вашата schema.strictеtrueкога го изоставите.
{
"model": "shannon-1.6-lite",
"input": "Extract the city and the date: 'The conference opens in Lisbon on 12 May 2027.'",
"text": {
"format": {
"type": "json_schema",
"name": "event",
"strict": true,
"schema": {
"type": "object",
"properties": {
"city": {
"type": "string"
},
"date": {
"type": "string",
"description": "ISO 8601 date"
}
},
"required": [
"city",
"date"
]
}
}
}
} JSON-от пристигнува како текст во делот output_text на пораката; парсирајте го сами. Хостиран open-weight модел без структуриран излез враќа 400.
{"city": "Lisbon", "date": "2027-05-12"} Кој модел која форма ја прима е наведено на нејзина страница. Структурирани излези
Reasoning
Модел што прави reasoning го враќа својот reasoning како излезна ставка од тип reasoning, пред пораката. Во streaming пристигнува како настани response.reasoning_summary_text.delta.
Хостираните open-weight модели го применуваат reasoning.effort: off, low, medium или high, со high кога не испраќате ништо. off не враќа ставка reasoning. Испратете го како објект; обичен стринг не се чита на овој ендпоинт.
Напорите се опишани на нивна страница. Напор на reasoning
Излезно ограничување
max_output_tokens е 4,096 кога не го испраќате. Тоа е бројот токени одвоени од вашето салдо кога барањето започнува; кога одговорот е готов, тој износ се заменува со она што барањето го искористило. Вредност што не собира во вашето преостанато салдо враќа 429 Quota exceeded.
Ја ограничува должината на одговорот на shannon-1.6-*, shannon-2-* и shannon-coder-1, и должината на текстот на одговорот на хостираните open-weight модели.
На овој ендпоинт shannon-coder-1 се наплатува во токени од вашето салдо, како секој друг модел.
Телото на барањето може да биде до 32 MiB. Ограничувања и салдо
Грешки
Грешките го користат телото на грешка на OpenAI: објект error со type и message; некои носат и code и param со вредност null. Табелата го наведува она што овој ендпоинт најчесто го враќа. Целосната листа, со тоа што да се повтори, има своја страница. Ракување со грешки
| Статус | Тип | Порака | Кога |
|---|---|---|---|
401 | authentication_error | Missing authenticationInvalid API key | Не е испратен API клуч, или клучот е непознат или отповикан. |
400 | invalid_request_error | unknown model: <id> | model недостасува или не е објавен ид. |
400 | invalid_request_error | No user message provided. | Нивоа на Shannon: input не содржи текст од корисник. |
400 | invalid_request_error | <id> does not accept image input | Слика е испратена до хостиран open-weight модел без влез на слики. |
400 | invalid_request_error | <id> does not accept response_format | text.format е испратен до хостиран open-weight модел без структуриран излез. |
400 | invalid_request_error | unknown reasoning effort '<value>'; expected off, low, medium or high | reasoning.effort содржи вредност надвор од листата. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | Телото е валиден JSON, но поле има погрешен тип. |
429 | rate_limit_error | Quota exceeded. Upgrade your plan at shannon-ai.com/plan | max_output_tokens е поголем од она што останало од вашето салдо. |
429 | rate_limit_error | Too many requests. Retry in <n>s. | Flood protection: повеќе од 120 барања во една минута на вашата сметка. |
500 | api_error | The model backend failed to answer. Please retry. | Моделот не создаде одговор. Испратете го барањето повторно. |
502 | api_error | The model backend failed to answer. Please retry. | Истото, на хостираните open-weight модели. |
504 | api_error | upstream timed out | Хостиран open-weight модел потрошил подолго од временското ограничување на одговор без streaming. Испратете го со stream поставен на true. |