Skip to content
jshacks.dev
APIs

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.

2 min read
Summarize in AI

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.

tools.jsJavaScript
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.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.