Tools
Let the model call functions in your code: tool definitions, calls and results in both API styles.
Describe functions your code can run. The model may answer with a call to one of them; you run it and send the result back in the next request.
Chat Completions API
Define tools with a JSON Schema for the parameters. tool_choice is auto (default), none, required, or a specific function.
{
"model": "kd-balanced",
"messages": [{"role": "user", "content": "What is the weather in Paris?"}],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
}
],
"tool_choice": "auto"
}A call comes back in message.tool_calls with finish_reason: "tool_calls". arguments is a JSON string.
{
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": null,
"tool_calls": [
{"id": "call_1", "type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}
]
},
"finish_reason": "tool_calls"
}
]
}Send the assistant message back with a tool message per call:
"messages": [
{"role": "user", "content": "What is the weather in Paris?"},
{"role": "assistant", "content": null, "tool_calls": [
{"id": "call_1", "type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}
]},
{"role": "tool", "tool_call_id": "call_1", "content": "{\"temp_c\": 18, \"sky\": \"clear\"}"}
]Messages API
Define tools with an input_schema. tool_choice is {"type": "auto"}, {"type": "any"}, {"type": "none"} or {"type": "tool", "name": "..."}.
{
"model": "kd-balanced",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "What is the weather in Paris?"}],
"tools": [
{
"name": "get_weather",
"description": "Current weather for a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
],
"tool_choice": {"type": "auto"}
}A call comes back as a tool_use block with stop_reason: "tool_use":
{
"role": "assistant",
"content": [
{"type": "tool_use", "id": "tool_1", "name": "get_weather", "input": {"city": "Paris"}}
],
"stop_reason": "tool_use"
}Send the assistant turn back, then a user turn with a tool_result block per call:
"messages": [
{"role": "user", "content": "What is the weather in Paris?"},
{"role": "assistant", "content": [
{"type": "tool_use", "id": "tool_1", "name": "get_weather", "input": {"city": "Paris"}}
]},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "tool_1", "content": "18 C, clear"}
]}
]Tips
- Write short, specific descriptions; the model chooses tools from them.
- Validate the arguments before you run anything: they come from the model.
- The model may call several tools in one answer. Answer every call.
- Tool definitions count as input tokens. Cache them in long sessions (prompt caching).