Call LLM with tool definitions
Call an LLM with tool definitions by sending a tool schema, reading the tool_use block in the reply, and returning the result in a follow-up message.
A model can ask your code to run a function. You describe the function with a JSON Schema, the model replies with the arguments, and you send the result back.
const tools = [
{
name: 'get_weather',
description: 'Get the current temperature for a city',
input_schema: {
type: 'object',
properties: { city: { type: 'string' } },
required: ['city'],
},
},
];
async function call(messages) {
const res = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-api-key': process.env.ANTHROPIC_API_KEY,
'anthropic-version': '2023-06-01',
},
body: JSON.stringify({ model: 'claude-sonnet-5-5', max_tokens: 512, tools, messages }),
});
return res.json();
}
const messages = [{ role: 'user', content: 'Is it warm in Lisbon?' }];
const reply = await call(messages);
const toolUse = reply.content.find((block) => block.type === 'tool_use');
if (toolUse) {
messages.push({ role: 'assistant', content: reply.content });
messages.push({
role: 'user',
content: [{ type: 'tool_result', tool_use_id: toolUse.id, content: '24 degrees C' }],
});
const final = await call(messages);
console.log(final.content[0].text);
}The reply has stop_reason: "tool_use" and a content block like { "type": "tool_use", "id": "toolu_...", "name": "get_weather", "input": { "city": "Lisbon" } }. The id is generated per call, so copy it into the matching tool_result rather than writing it by hand.
The model only asks; your code decides whether to run the function, so validate the input as you would any user input. Real agents loop until stop_reason is no longer tool_use. The request format is in the tool use guide.