Chamada de funções
Descreva suas funções na requisição e o modelo responde com as chamadas que quer que sejam feitas. Seu código as executa e envia os resultados de volta: a API retorna chamadas de ferramenta e não executa nenhuma ferramenta por conta própria.
POST https://api.shannon-ai.com/v1/chat/completions
Os exemplos desta página usam /v1/chat/completions. O mesmo loop funciona em /v1/responses e /v1/messages; onde um formato escreve algo de forma diferente, as seções abaixo mostram os três.
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 não responde à pergunta. Ela pede uma 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}
}
} Depois que você envia o resultado, a resposta seguinte é uma resposta comum: message.content contém o texto e finish_reason é stop.
O loop, passo a passo
| Passo | Quem | O que acontece |
|---|---|---|
| 1 | Você | Envie messages junto com tools, a lista de funções que o modelo pode pedir. |
| 2 | Modelo | A resposta traz tool_calls e finish_reason: "tool_calls". Cada chamada nomeia uma função e informa seus argumentos. |
| 3 | Você | Faça o parse dos arguments de cada chamada e execute sua função. |
| 4 | Você | Acrescente a mensagem do assistente e uma mensagem tool por chamada a messages e envie a requisição de novo com os mesmos tools. |
| 5 | Modelo | O modelo responde em texto com finish_reason: "stop", ou pede mais chamadas. Nesse caso, volte ao passo 3. |
Uma requisição é um turno do modelo. A API não guarda a conversa entre requisições e não define um número de rodadas: seu código mantém messages e decide quando parar.
Definindo ferramentas
tools é um array com uma entrada por função. Todos os modelos do catálogo o aceitam; GET /v1/models informa capabilities.tools: true para todos os ids.
| Campo | Tipo | Descrição |
|---|---|---|
type | string | Sempre function. |
function.name | string | O nome que o modelo usa quando pede esta função. Obrigatório. |
function.description | string | O que a função faz, em linguagem simples. |
function.parameters | object | Os argumentos como um JSON Schema com type: "object" no topo. Veja Palavras-chave do schema abaixo. |
Cada endpoint tem a sua própria grafia de uma ferramenta. Envie a que pertence ao endpoint que você chama:
{
"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 diz se o modelo pode ou deve chamar uma ferramenta. É lido somente junto com tools.
| Valor | Descrição | Aplicado por |
|---|---|---|
"auto" | O modelo decide se responde em texto ou chama uma ferramenta. Este é o padrão. | Todos os modelos |
"required" | A resposta chama pelo menos uma ferramenta. | Modelos open-weight hospedados |
{"type": "function", "function": {"name": "get_weather"}} | A resposta chama esta função. O nome deve ser o de uma das funções em tools. Chamadas a outras funções são omitidas da resposta. | Modelos open-weight hospedados |
Os modelos Shannon (shannon-*) decidem em cada requisição, como com auto.
Com required ou uma função nomeada, leia finish_reason antes de ler tool_calls. Quando o modelo não produz nenhuma chamada, a resposta é um texto com finish_reason: "stop".
| Significado | /v1/chat/completions | /v1/responses | /v1/messages |
|---|---|---|---|
| O modelo decide | "auto" | "auto" | {"type": "auto"} |
| Chamar pelo menos uma ferramenta | "required" | "required" | {"type": "any"} |
| Chamar uma função nomeada | {"type": "function", "function": {"name": "get_weather"}} | {"type": "function", "name": "get_weather"} | {"type": "tool", "name": "get_weather"} |
Aceitos por compatibilidade: tool_choice: "none" e parallel_tool_calls. Para um turno sem chamadas de ferramenta, envie a requisição sem tools.
Chamadas de ferramenta na resposta
| Campo | Tipo | Descrição |
|---|---|---|
finish_reason | string | tool_calls quando a resposta traz pelo menos uma chamada. |
message.tool_calls | array | Uma entrada por chamada. O campo só está presente quando o modelo pediu uma chamada. |
tool_calls[].id | string | call_ seguido de 32 caracteres hexadecimais. Envie-o de volta como tool_call_id com o resultado. |
tool_calls[].type | string | Sempre function. |
tool_calls[].function.name | string | A função a executar. |
tool_calls[].function.arguments | string | Os argumentos como uma string JSON, "{}" quando não há nenhum. Faça o parse antes de usar. |
message.content | string | null | null quando a resposta contém apenas chamadas. Os modelos open-weight hospedados podem retornar texto junto das chamadas; os modelos Shannon retornam null. |
A mesma chamada em cada formato. Em /v1/responses, é um item function_call de output, com arguments como string JSON. Em /v1/messages, é um bloco de conteúdo tool_use cujo input é um objeto JSON, seu id começa com 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"}
}
]
} Várias chamadas em um turno
Uma resposta pode trazer várias chamadas. Execute todas e envie, na próxima requisição, um resultado por chamada, cada um com o seu próprio tool_call_id.
Os modelos open-weight hospedados retornam cada chamada distinta uma única vez: duas chamadas com o mesmo nome e os mesmos argumentos chegam como uma só.
Chamadas de ferramenta em streaming
Com stream: true, uma chamada chega de uma só vez: o chunk contém a string arguments completa, então não há fragmentos para juntar. index conta as chamadas do turno a partir de 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 | O que chega |
|---|---|
/v1/chat/completions | Um chat.completion.chunk por chamada, com a chamada em delta.tool_calls[0]. O último chunk tem finish_reason: "tool_calls" e usage. |
/v1/responses | Por chamada: response.output_item.added (um item function_call com arguments vazio), response.function_call_arguments.delta (a string inteira), response.function_call_arguments.done, response.output_item.done. |
/v1/messages | Por chamada: content_block_start (um bloco tool_use com input vazio), um content_block_delta cujo input_json_delta.partial_json é o texto completo dos argumentos, content_block_stop. message_delta então traz stop_reason: "tool_use". |
Em shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro e shannon-coder-1, uma requisição com streaming que traz tools entrega o texto da resposta em um único delta de content no fim do turno. Streaming
Enviando os resultados de volta
A segunda requisição repete a conversa e acrescenta duas coisas: o turno do assistente que pediu as chamadas e um 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\"}"
}
]
}
]
} - Envie o turno do assistente de volta como você o recebeu, antes dos resultados. Cada resultado é associado à sua chamada pelo id:
tool_call_idem/v1/chat/completions,call_idem/v1/responses,tool_use_idem/v1/messages. - Um resultado é texto. Serialize um objeto em uma string JSON para
content(outputem/v1/responses). Em/v1/messages, ocontentde um blocotool_resulté uma string ou uma lista de blocos de texto. - No turno do assistente,
function.argumentscontinua sendo uma string JSON, exatamente como chegou. - A conversa pode terminar com um resultado de ferramenta. Não é preciso uma nova mensagem de usuário: o modelo continua a partir do resultado.
- Quando sua função falha, envie a falha como o texto do resultado. O modelo pode então relatá-la ou pedir outra chamada.
Palavras-chave do schema
parameters (input_schema em /v1/messages) é um JSON Schema. A família Shannon 3 (shannon-3, shannon-3-pro, shannon-3.1, shannon-3.1-pro) e os modelos open-weight hospedados o recebem como você o envia.
shannon-1.6-lite, shannon-1.6-pro, shannon-2-lite, shannon-2-pro e shannon-coder-1 recebem este subconjunto, nos três endpoints:
| Tratamento | Palavras-chave |
|---|---|
| Lidas como enviadas | Toda palavra-chave que não é citada nas linhas abaixo, por exemplo type, properties, required, items, enum, description, minimum, maximum, anyOf e allOf, em todos os níveis do schema. |
format | Lido para os valores int32, int64, float, double, byte, date, date-time e enum. |
oneOf | Lido como anyOf. |
| Não fazem parte do schema que esses modelos recebem | $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 quando são números; outros valores de format. |
Comportamento e limites
- A API não define um número máximo de ferramentas nem um número máximo de rodadas.
- O corpo de uma requisição pode ter até 32 MiB, e a conversa com seus resultados precisa caber na janela de contexto do modelo.
- Quando uma requisição traz
tools,shannon-1.6-lite,shannon-1.6-pro,shannon-2-liteeshannon-2-prousam umatemperaturepadrão de 0.2. Envietemperaturepara definir outro valor. - Cada rodada é uma requisição própria: consome o seu saldo e conta para a proteção contra flood como qualquer outra requisição. Limites e saldo
Erros
Uma chamada de ferramenta é uma resposta normal com status 200. Estes erros dizem respeito à própria requisição:
| Status | Tipo | Mensagem | Quando |
|---|---|---|---|
400 | invalid_request_error | unknown model: <id> | model não é um id da lista publicada. |
422 | invalid_request_error | Failed to deserialize the JSON body into the target type: … | tools não é um array, ou outro campo tem o tipo JSON errado. |
413 | invalid_request_error | Failed to buffer the request body: … | O corpo da requisição é maior que 32 MiB. O erro traz code: "request_too_large". |
O modelo escreve os argumentos. Verifique-os com o seu schema antes de executar a função, como faria com qualquer entrada externa.
Erros de autenticação, de saldo e de servidor são os mesmos de qualquer requisição. Tratamento de erros