Tool and Function Calling

Let the model request actions (search, database queries, API calls) that your code executes, the foundation of every agent.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Structured Outputs and JSON Schema

Tool calling (function calling) lets a model say "call get_weather with {city: "Pune"}" instead of guessing an answer. Your code runs the function and sends the result back. The model never executes anything itself.

The round trip

  1. You send the conversation plus a list of tool definitions: name, description, and a JSON Schema for the arguments.
  2. The model responds with a tool call (stop reason indicates tool use) and arguments.
  3. Your code validates the arguments, executes the tool and appends a tool result message.
  4. You call the model again; it uses the result to answer or calls another tool.

Writing good tool definitions

  • Descriptions are prompts. Explain when to use the tool, not just what it does.
  • Use clear parameter names, enums and required fields.
  • Return concise, structured results. Huge raw payloads waste context and confuse the model.
  • Return helpful error messages as results ("city not found, try a larger city nearby") so the model can recover.

Control and safety

  • tool_choice lets you force a specific tool, require any tool, or disable tools.
  • Models may request several tools in parallel; handle all of them.
  • Treat arguments as untrusted input. Validate, authorize and rate-limit, especially for tools that write data, spend money or send messages.

Good enough to move on

You can implement a manual tool loop with two or three tools, handle parallel calls and errors, and stop the loop safely.

Key concepts

  • Tool definitions and schemas
  • The tool call / result round trip
  • tool_choice and forcing tools
  • Parallel tool calls
  • Error results the model can use
  • Validating and authorizing arguments
  • Provider built-in tools (web search, code)

Mini project

Build a small assistant with three tools (current time, a calculator and a lookup against a local SQLite table) using a hand-written tool loop, and log every call and result.

Check yourself

The model calls your delete_record tool with an ID belonging to another user. Where in your system should this be stopped, and why not in the prompt?

Free resources