The Tool Execution Loop
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 Functions
To execute function calls, you first need actual TypeScript 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 uses TypeScript's type annotations to document what it expects (number) and returns. These are ordinary TypeScript functions that your application will call directly after the model requests them. They represent the actual capabilities your agent has — when the model decides to call add, your code will execute this function and return the result. Now you need to create tool schemas that tell the model these functions exist and how to use them.
Creating Tool Schemas for Your Functions
You'll create toolSchemas that match your TypeScript 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 TypeScript function — the parameter names (a and b) are identical, and the types correspond. This consistency matters because when the model calls add with arguments, you'll parse those arguments from JSON and pass them directly to your function using switch-based dispatch. With your functions and schemas defined, you're ready to build the conversation context.
