Chamadas a funcións
Describe as túas funcións na solicitude e o modelo responde coas chamadas que quere que se fagan. O teu código execútaas e devolve os resultados: a API devolve chamadas a ferramentas e non executa ela mesma ningunha ferramenta.
POST https://api.shannon-ai.com/v1/chat/completions
Os exemplos desta páxina usan /v1/chat/completions. O mesmo bucle funciona en /v1/responses e /v1/messages; onde un formato escribe algo de forma distinta, as seccións seguintes mostran os tres.
import json
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY", base_url="https://api.shannon-ai.com/v1")
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Paris"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
},
},
}]
def get_weather(city, unit="celsius"):
# Your code: ask a weather service here.
return {"city": city, "temperature": 18, "unit": unit, "conditions": "cloudy"}
messages = [{"role": "user", "content": "What is the weather in Paris right now?"}]
answer = None
for _ in range(5): # the API sets no limit on rounds: set your own
response = client.chat.completions.create(
model="Kimi-K3-3BIT-REAP",
messages=messages,
tools=tools,
)
choice = response.choices[0]
if choice.finish_reason != "tool_calls":
answer = choice.message.content
break
messages.append(choice.message) # the assistant turn with its tool_calls
for call in choice.message.tool_calls:
args = json.loads(call.function.arguments) # arguments is a JSON string
result = get_weather(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
print(answer) import OpenAI from "openai";
const client = new OpenAI({ apiKey: "YOUR_API_KEY", baseURL: "https://api.shannon-ai.com/v1" });
const tools = [{
type: "function",
function: {
name: "get_weather",
description: "Get the current weather for a city.",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "City name, for example Paris" },
unit: { type: "string", enum: ["celsius", "fahrenheit"] },
},
required: ["city"],
},
},
}];
// Your code: ask a weather service here.
function getWeather({ city, unit = "celsius" }) {
return { city, temperature: 18, unit, conditions: "cloudy" };
}
const messages = [{ role: "user", content: "What is the weather in Paris right now?" }];
let answer = null;
// The API sets no limit on rounds: set your own.
for (let round = 0; round < 5; round++) {
const response = await client.chat.completions.create({
model: "Kimi-K3-3BIT-REAP",
messages,
tools,
});
const choice = response.choices[0];
if (choice.finish_reason !== "tool_calls") {
answer = choice.message.content;
break;
}
messages.push(choice.message); // the assistant turn with its tool_calls
for (const call of choice.message.tool_calls) {
const args = JSON.parse(call.function.arguments); // arguments is a JSON string
messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(getWeather(args)),
});
}
}
console.log(answer); # 1. Send the conversation with the tools.
curl https://api.shannon-ai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "Kimi-K3-3BIT-REAP",
"messages": [
{"role": "user", "content": "What is the weather in Paris right now?"}
],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Paris"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}]
}'
# 2. Run the function yourself, then send the assistant turn and the result.
# Use the id of the call you received.
curl https://api.shannon-ai.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "Kimi-K3-3BIT-REAP",
"messages": [
{"role": "user", "content": "What is the weather in Paris right now?"},
{"role": "assistant", "content": null, "tool_calls": [{
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\":\"Paris\"}"}
}]},
{"role": "tool", "tool_call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"content": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"}
],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, for example Paris"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}]
}' A primeira resposta non contesta a pregunta. Pide unha chamada:
{
"id": "chatcmpl-5b0c1d8e7f6a4b3c9d2e1f0a8b7c6d5e",
"object": "chat.completion",
"created": 1791590400,
"model": "Kimi-K3-3BIT-REAP",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": null,
"reasoning_content": "The user asks for the current weather in Paris. I should call get_weather.",
"tool_calls": [
{
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 312,
"completion_tokens": 58,
"total_tokens": 370,
"prompt_tokens_details": {"cached_tokens": 0},
"completion_tokens_details": {"reasoning_tokens": 31}
}
} Despois de enviar o resultado, a seguinte resposta é unha resposta normal: message.content contén o texto e finish_reason é stop.
O bucle, paso a paso
| Paso | Quen | Que pasa |
|---|---|---|
| 1 | Ti | Envía messages xunto con tools, a lista de funcións que o modelo pode pedir. |
| 2 | Modelo | A resposta leva tool_calls e finish_reason: "tool_calls". Cada chamada nomea unha función e dá os seus argumentos. |
| 3 | Ti | Analiza os arguments de cada chamada e executa a túa función. |
| 4 | Ti | Engade a mensaxe do asistente e unha mensaxe tool por chamada a messages e envía a solicitude de novo cos mesmos tools. |
| 5 | Modelo | O modelo responde en texto con finish_reason: "stop", ou pide máis chamadas. Nese caso, volve ao paso 3. |
Unha solicitude é un turno do modelo. A API non garda ningunha conversa entre solicitudes e non fixa un número de roldas: o teu código garda messages e decide cando parar.
Definir ferramentas
tools é unha matriz cunha entrada por función. Todos os modelos do catálogo a aceptan; GET /v1/models informa capabilities.tools: true para todos os ids.
| Campo | Tipo | Descrición |
|---|---|---|
type | string | Sempre function. |
function.name | string | O nome que usa o modelo cando pide esta función. Obrigatorio. |
function.description | string | O que fai a función, en linguaxe sinxela. |
function.parameters | object | Os argumentos como JSON Schema con type: "object" na parte superior. Consulta Palabras clave do esquema máis abaixo. |
Cada endpoint ten a súa propia forma de escribir unha ferramenta. Envía a que corresponde ao endpoint ao que chamas:
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, for example Paris"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
} {
"type": "function",
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, for example Paris"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
} {
"name": "get_weather",
"description": "Get the current weather for a city.",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, for example Paris"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
} tool_choice
tool_choice indica se o modelo pode, ou debe, chamar a unha ferramenta. Só se le xunto con tools.
| Valor | Descrición | Aplicado por |
|---|---|---|
"auto" | O modelo decide se responde en texto ou chama a unha ferramenta. Este é o valor predeterminado. | Todos os modelos |
"required" | A resposta chama a polo menos unha ferramenta. | Modelos open-weight alojados |
{"type": "function", "function": {"name": "get_weather"}} | A resposta chama a esta función. O nome debe ser o dunha das funcións de tools. As chamadas a outras funcións quedan fóra da resposta. | Modelos open-weight alojados |
Os modelos Shannon (shannon-*) deciden en cada solicitude, como con auto.
Con required ou unha función nomeada, le finish_reason antes de ler tool_calls. Cando o modelo non produce ningunha chamada, a resposta é unha resposta de texto con finish_reason: "stop".
| Significado | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| O modelo decide | "auto" | "auto" | {"type": "auto"} |
| Chamar a polo menos unha ferramenta | "required" | "required" | {"type": "any"} |
| Chamar a unha función nomeada | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Aceptados por compatibilidade: tool_choice: "none" e parallel_tool_calls. Para un turno sen chamadas a ferramentas, envía a solicitude sen tools.
Chamadas a ferramentas na resposta
| Campo | Tipo | Descrición |
|---|---|---|
finish_reason | string | tool_calls cando a resposta leva polo menos unha chamada. |
message.tool_calls | array | Unha entrada por chamada. O campo só está presente cando o modelo pediu unha chamada. |
tool_calls[].id | string | call_ seguido de 32 caracteres hexadecimais. Devólveo como tool_call_id co resultado. |
tool_calls[].type | string | Sempre function. |
tool_calls[].function.name | string | A función que se vai executar. |
tool_calls[].function.arguments | string | Os argumentos como cadea JSON, "{}" cando non hai ningún. Analízaa antes de usala. |
message.content | string | null | null cando a resposta contén só chamadas. Os modelos open-weight alojados poden devolver texto xunto coas chamadas; os modelos Shannon devolven null. |
A mesma chamada en cada formato. En /v1/responses é un elemento function_call de output, con arguments como cadea JSON. En /v1/messages é un bloque de contido tool_use cuxo input é un obxecto JSON, o seu id comeza por toolu_ e stop_reason é tool_use.
{
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
}
} {
"output": [
{
"id": "fc_3d2c1b0a9f8e4d7c6b5a4f3e2d1c0b9a",
"type": "function_call",
"call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}",
"status": "completed"
}
]
} {
"stop_reason": "tool_use",
"content": [
{
"type": "tool_use",
"id": "toolu_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"name": "get_weather",
"input": {"city": "Paris"}
}
]
} Varias chamadas nun turno
Unha resposta pode levar varias chamadas. Executa todas e envía un resultado por chamada, cada un co seu propio tool_call_id, na seguinte solicitude.
Os modelos open-weight alojados devolven cada chamada distinta unha soa vez: dúas chamadas co mesmo nome e os mesmos argumentos chegan como unha.
Chamadas a ferramentas con stream
Con stream: true, unha chamada chega dunha soa peza: o chunk contén a cadea arguments completa, así que non hai fragmentos que unir. index conta as chamadas do turno desde 0.
{
"id": "chatcmpl-5b0c1d8e7f6a4b3c9d2e1f0a8b7c6d5e",
"object": "chat.completion.chunk",
"created": 1791590400,
"model": "Kimi-K3-3BIT-REAP",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"index": 0,
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
},
"finish_reason": null
}
]
} | Endpoint | Que chega |
|---|---|
/v1/chat/completions | Un chat.completion.chunk por chamada, coa chamada en delta.tool_calls[0]. O último chunk ten finish_reason: "tool_calls" e usage. |
/v1/responses | Por chamada: response.output_item.added (un elemento function_call con arguments baleiro), response.function_call_arguments.delta (a cadea completa), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Por chamada: content_block_start (un bloque tool_use con input baleiro), un content_block_delta cuxo input_json_delta.partial_json é o texto completo dos argumentos, content_block_stop. Despois message_delta leva stop_reason: "tool_use". |
En shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro e shannon-coder-1, unha solicitude con stream que leva tools entrega o texto da súa resposta nun só delta de content ao final do turno. Streaming
Devolver os resultados
A segunda solicitude repite a conversa e engade dúas cousas: o turno do asistente que pediu as chamadas e un resultado por chamada.
{
"messages": [
{"role": "user", "content": "What is the weather in Paris right now?"},
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"content": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"
}
]
} {
"input": [
{"role": "user", "content": "What is the weather in Paris right now?"},
{
"type": "function_call",
"call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"name": "get_weather",
"arguments": "{\"city\":\"Paris\"}"
},
{
"type": "function_call_output",
"call_id": "call_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"output": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"
}
]
} {
"messages": [
{"role": "user", "content": "What is the weather in Paris right now?"},
{
"role": "assistant",
"content": [
{
"type": "tool_use",
"id": "toolu_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"name": "get_weather",
"input": {"city": "Paris"}
}
]
},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_9f1c2ab34d5e4f60a7b8c9d0e1f2a3b4",
"content": "{\"city\":\"Paris\",\"temperature\":18,\"unit\":\"celsius\",\"conditions\":\"cloudy\"}"
}
]
}
]
} - Devolve o turno do asistente tal como o recibiches, antes dos resultados. Cada resultado asóciase á súa chamada polo id:
tool_call_iden/v1/chat/completions,call_iden/v1/responses,tool_use_iden/v1/messages. - Un resultado é texto. Serializa un obxecto a unha cadea JSON para
content(outputen/v1/responses). En/v1/messages, ocontentdun bloquetool_resulté unha cadea ou unha lista de bloques de texto. - No turno do asistente,
function.argumentssegue sendo unha cadea JSON, exactamente como chegou. - A conversa pode rematar cun resultado de ferramenta. Non fai falta ningunha mensaxe nova de usuario: o modelo continúa desde o resultado.
- Cando a túa función falla, envía o fallo como texto do resultado. O modelo pode entón informar del ou pedir outra chamada.
Palabras clave do esquema
parameters (input_schema en /v1/messages) é un JSON Schema. A familia Shannon 3 (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) e os modelos open-weight alojados recíbeno tal como o envías.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro e shannon-coder-1 reciben este subconxunto, nos tres endpoints:
| Tratamento | Palabras clave |
|---|---|
| Lido tal como se envía | Todas as palabras clave que non se nomean nas filas seguintes, por exemplo type, properties, required, items, enum, description, minimum, maximum, anyOf e allOf, en todos os niveis do esquema. |
format | Lese para os valores int32, int64, float, double, byte, date, date-time e enum. |
oneOf | Lese como anyOf. |
| Non forma parte do esquema que reciben estes modelos | $schema, $id, $ref, $defs, $comment, definitions, additionalProperties, unevaluatedProperties, patternProperties, propertyNames, examples, default, title, const, not, if, then, else, contains, minContains, maxContains, dependentRequired, dependentSchemas, dependencies, readOnly, writeOnly, deprecated, contentEncoding, contentMediaType, contentSchema, multipleOf, uniqueItems; exclusiveMinimum e exclusiveMaximum cando son números; outros valores de format. |
Comportamento e límites
- A API non fixa un número máximo de ferramentas nin un número máximo de roldas.
- O corpo dunha solicitude pode ser de ata 32 MiB, e a conversa cos seus resultados ten que caber na ventá de contexto do modelo.
- Cando unha solicitude leva
tools,shannon-1.6-lite,shannon-1.6-pro,shannon-2-liteeshannon-2-prousan unhatemperaturepredeterminada de 0.2. Envíatemperaturepara definir outro valor. - Cada ronda é unha solicitude propia: gasta do teu saldo e conta para a protección contra inundación como calquera outra solicitude. Límites e saldo
Erros
Unha chamada a unha ferramenta é unha resposta normal co estado 200. Estes erros refírense á propia solicitude:
| Estado | Tipo | Mensaxe | Cando |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model non é un id da lista publicada. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools non é unha matriz, ou outro campo ten o tipo JSON incorrecto. |
413 | invalid_request_error | Failed to buffer the request body: … | O corpo da solicitude é maior de 32 MiB. O erro leva code: "request_too_large". |
O modelo escribe os argumentos. Compróbaos co teu esquema antes de executar a función, como farías con calquera entrada externa.
Os erros de autenticación, saldo e servidor son os mesmos que para calquera solicitude. Xestión de erros