Skip to main content
Time to put this into practice. In this hands-on lesson you’ll build a small Python application where the language model decides when to call tools on your behalf. You’ll:
  • Define tool schemas the model can inspect
  • Implement local handler functions that perform the requested work
  • Wire a tool-call loop that executes model-suggested tool calls and returns results for the model to finalize a reply
This same pattern—model suggests a tool call, your app runs the tool, and the model composes the final answer—powers many AI agents.
A retro-style poster with large yellow pixel text reading "BUILD A TOOL-CALLING APP" and a small teal label "HANDS-ON LAB" with a key icon. It also shows the lines "Define tools · Write handlers · Wire the loop," a green "TOOL-CALL LOOP" button, and the tagline "The same pattern that powers every AI agent" on a dark grid background.
Prerequisites
  • Python 3.11 (virtual environment recommended)
  • OpenAI SDK installed in the environment
  • Working directory: /root/code
Step 1 — Create the app file Create a file named tool_app.py in /root/code:
Step 2 — Full example: tool-call loop Below is a concise, complete script that demonstrates the pattern end-to-end: define tool schemas (JSON-schema style), implement local handler functions, dispatch tool calls from the model response, and provide tool outputs back to the model for a final answer.
Step 3 — Set environment variables Before running the script, ensure your API key (and optional base URL) are exported:
Step 4 — Run the script
Example output
Why this works — quick summary
  • You supply the model with a tools list. Each tool includes:
    • name — unique tool identifier
    • description — natural-language description of the tool’s purpose
    • parameters — a JSON Schema-like object describing expected arguments
  • The model may respond with a message whose finish reason is tool_calls. That response can include one or more tool call objects.
  • Your app:
    1. Extracts the tool name and arguments from the model’s tool call
    2. Executes the corresponding local function
    3. Appends a role: "tool" message containing the tool output (and tool_call_id for correlation)
    4. Calls the model again so it can compose a natural-language final answer using the tool output
Reference table — message roles and purpose Links and further reading
Make sure your tool outputs are in a format the model can parse (for example, JSON strings or clear natural language). Also ensure OPENAI_API_KEY is set in your environment before running the script.

Watch Video