Executing Tool Calls and Managing Context
Introduction: The Tool Execution Loop
You've learned how to define tool schemas and parse function calls from model responses. Now you're ready to close the loop by actually executing those function calls and feeding their results back to the model. This lesson introduces Factor 3 (Own your context window) by showing you how to explicitly control what information flows through your agent's conversation history. By the end of this lesson, you'll build agents that can perform multi-step reasoning, where the model calls a tool, your code executes it, and the model sees the result before deciding what to do next.
Defining Executable Python Functions
To execute function calls, you first need actual Python functions that perform real work. These functions should be simple and focused, with clear inputs and outputs. For this lesson, you'll define two basic mathematical operations that your agent can use.
Each function has type hints that document what it expects (float) and returns. The docstrings describe what the function does in plain language. These functions represent the actual capabilities your agent has — when the model decides to call add, your code will execute this Python function and return the result. Now you need to create tool schemas that tell the model that these functions exist and how to use them.
Creating Tool Schemas for Your Functions
You'll create tool_schemas that match your Python functions, plus a final_answer tool that signals when the agent has finished its work. The schemas tell the model what tools are available and exactly how to use them.
Notice how the schema for add matches the signature of your Python function — the parameter names (a and b) are identical, and the types correspond to Python's type hints. This consistency is critical because when the model calls add with arguments, you'll parse those arguments and pass them directly to your Python function using keyword argument unpacking. With your functions and schemas defined, you're ready to build the conversation context.
