Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Function Execution
Function execution is what happens when the agent calls a tool. The tool runner validates the arguments, calls the function, captures the result, and returns it as an observation.
8 min•By Priygop Team•Updated 2026
The Execution Flow
When the agent decides to call a tool, the following happens:
- 1The agent outputs a tool call with a name and arguments
- 2The tool runner validates: does the tool exist? Are the arguments valid?
- 3The tool function is executed
- 4The return value is captured
- 5The return value is passed back to the agent as an observation
- 6The observation is added to the agent state
- 7The agent reads the observation and decides the next step
If step 2 or 3 fails, an error observation is returned instead of a result. The agent must handle this error.
Tool Runner Implementation
Tool Runner Implementation
# A basic tool runner that handles validation and execution
class ToolRunner:
def __init__(self, tools: dict):
"""
tools: dict of tool_name -> callable
"""
self.tools = tools
def execute(self, tool_name: str, arguments: dict) -> dict:
"""Execute a tool call and return a structured result."""
# Check tool exists
if tool_name not in self.tools:
return {
"status": "error",
"error": f"Tool '{tool_name}' not found",
"result": None
}
try:
# Execute the tool
tool_fn = self.tools[tool_name]
result = tool_fn(**arguments)
return {
"status": "success",
"tool": tool_name,
"result": result
}
except TypeError as e:
# Wrong arguments
return {
"status": "error",
"error": f"Invalid arguments for '{tool_name}': {str(e)}",
"result": None
}
except Exception as e:
# Tool execution failed
return {
"status": "error",
"error": f"Tool '{tool_name}' failed: {str(e)}",
"result": None
}
# Register tools and run
def calculate(expression: str) -> float:
return eval(expression, {"__builtins__": {}})
runner = ToolRunner(tools={"calculate": calculate})
result = runner.execute("calculate", {"expression": "2 + 2"})
print(result) # {'status': 'success', 'tool': 'calculate', 'result': 4}