Responses API
НовоPOST /v1/responses приема инструкции и списък от входни елементи и връща обект на отговор, съставен от изходни елементи, във формата OpenAI Responses. Използвайте го с responses API на SDK на OpenAI и с инструменти, изградени върху него, като Codex CLI. Ендпоинтът не пази състояние: изпращайте целия разговор с всяка заявка.
POST https://api.shannon-ai.com/v1/responses
Най-малката заявка е id на модел и текст. Отговорът е без стрийминг, освен ако не го поискате.
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."
}' Отговорът е обект на отговор. Неговото output съдържа разсъжденията, когато моделът е разсъждавал, и съобщението:
{
"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 модели са дванадесетте id-та от списъка с модели; семейството Shannon 3 е shannon-3, shannon-3-pro, shannon-3.1 и shannon-3.1-pro. Модели и цени
| Поле | Тип | По подразбиране | Описание | Прилагано от |
|---|---|---|---|---|
model | string | Задължително. Id от списъка с модели. Съпоставянето не зависи от главни и малки букви. Липсващо или непубликувано id връща 400 unknown model. | Всички модели | |
input | string | array | Низ, който се чете като едно потребителско съобщение, или масив от входни елементи. Вижте Входни елементи по-долу. | Всички модели | |
instructions | string | Инструкции за модела, системният prompt на този формат. | Хоствани open-weight модели, shannon-1.6-*, shannon-2-*, shannon-coder-1 | |
stream | boolean | false | true изпраща отговора като server-sent events. Вижте Стрийминг по-долу. | Всички модели |
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 при отговори без стрийминг | |
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 модели според изброеното за всяко id |
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 е id на извикването, а output е резултатът като низ. | Всички модели |
Поставяйте инструкциите в полето instructions. При id от семейството Shannon 3 поставяйте инструкциите, които трябва да се спазват, в съобщението user.
Елементите на output на един отговор могат да се върнат в input такива, каквито са: елементите message и function_call се четат, елементите reasoning се пропускат.
Части на съдържанието
| Част | Описание | Налично на |
|---|---|---|
{"type": "input_text", "text": "…"} | Текст на потребителско съобщение. | Всички модели |
{"type": "output_text", "text": "…"} | Текст на съобщение на асистента. | Всички модели |
{"type": "input_image", "image_url": "…"} | Изображение, като URL data: със съдържание base64 или като URL http(s). | Семейството 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 съдържа URL data:, а file_url URL http(s). | Семейство Shannon 3 |
При нивата на Shannon изображенията и файловете се четат от последния елемент user на input. Размерите и ограниченията имат собствена страница. Изображения и файлове
Заявка с инструкции и опции
Тази заявка изпраща инструкции, разговор като входни елементи, ограничение на изхода, температура и усилия за разсъждения. Използва хостван 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 добавя токените, прочетени от кеша, и токените, изразходвани за разсъждения:
{
"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. При стрийм първо е in_progress, а в събитие response.failed е 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: изходните токени, изразходвани за разсъждения. | Хоствани open-weight модели |
model | string | Каноничното id на модела, който е отговорил. | Семейство 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": "…"}]} | Разсъжденията на модела като една част summary_text. Присъства само когато моделът е разсъждавал. |
{"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.
Стрийминг
Задайте stream на true за server-sent events. Всеки кадър има ред event: с името на събитието и ред data: с JSON обект; обектът повтаря името в type. Съпоставяйте делтите с техния елемент по 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
}' Събитията пристигат в този ред. Групите за разсъждения, съобщението и извикванията на инструменти се появяват само когато отговорът ги има.
| Събитие | Съдържание | Кога |
|---|---|---|
response.created | response | Винаги първо. response.status е in_progress, а response.output е празно. |
response.in_progress | response | Винаги второ, със същия обект. |
response.output_item.added | output_index, item | Разсъжденията започват: елемент reasoning с празно summary. |
response.reasoning_summary_text.delta | output_index, summary_index, delta | Парче от разсъжденията. |
response.reasoning_summary_text.done | output_index, summary_index, text | Разсъжденията са завършени: целият им 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 | Аргументите на извикването, пълни в една делта. |
response.function_call_arguments.done | output_index, arguments | Същите аргументи, като arguments. |
response.output_item.done | output_index, item | Завършеният елемент function_call. |
response.completed | 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}, …}} Стрийм, който се проваля
При нивата на 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.
Смятайте стрийма за неуспешен, когато съдържа събитие 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 схемата parameters се свежда до общите ключови думи на JSON Schema: oneOf се чете като anyOf, а ключови думи като $ref, additionalProperties, const, default и title не се предават на модела.
Стойностите на tool_choice required и именувана функция се прилагат от хостваните open-weight модели.
Цикълът на инструментите е описан изцяло на собствена страница. Извикване на функции
Структуриран изход
Този формат изписва структурирания изход като text.format. Схемата стои директно в format, до name и strict, а не под член json_schema, както при Chat Completions.
{"type": "json_object"}иска произволен JSON обект.{"type": "json_schema", "name", "schema", "strict"}иска JSON, който следва Вашата схема.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, преди съобщението. При стрийм те пристигат като събития response.reasoning_summary_text.delta.
Хостваните open-weight модели прилагат reasoning.effort: off, low, medium или high, като high, когато не изпратите нищо. off не връща елемент за разсъждения. Изпращайте го като обект; голям низ не се чете на този ендпоинт.
Усилията са описани на собствена страница. Усилие за разсъждение
Ограничение на изхода
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 липсва или не е публикувано id. |
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. | Защита от наводняване: повече от 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 модел е отнел повече от времевото ограничение за отговор без стрийминг. Изпратете заявката със stream, зададено на true. |