Forcing Tool Use
Description: Learn how to force agents to use tools with different behaviors: default, first tool result, or custom logic
Difficulty: advanced
Category: tools
Python Code Example
from __future__ import annotations
import asyncio
from typing import Any, Literal
from pydantic import BaseModel
from agents import (
Agent,
FunctionToolResult,
ModelSettings,
RunContextWrapper,
Runner,
ToolsToFinalOutputFunction,
ToolsToFinalOutputResult,
function_tool,
)
"""
This example shows how to force the agent to use a tool. It uses ModelSettings(tool_choice="required")
to force the agent to use any tool.
You can modify the tool_use_behavior variable to test different behaviors:
1. "default": The default behavior, which sends the tool output to the LLM
2. "first_tool": The first tool result is used as the final output
3. "custom": A custom tool use behavior function is used
"""
class Weather(BaseModel):
city: str
temperature_range: str
conditions: str
@function_tool
def get_weather(city: str) -> Weather:
print("[debug] get_weather called")
return Weather(city=city, temperature_range="14-20C", conditions="Sunny with wind")
async def custom_tool_use_behavior(
context: RunContextWrapper[Any], results: list[FunctionToolResult]
) -> ToolsToFinalOutputResult:
weather: Weather = results[0].output
return ToolsToFinalOutputResult(
is_final_output=True, final_output=f"{weather.city} is {weather.conditions}."
)
async def main(tool_use_behavior: Literal["default", "first_tool", "custom"] = "first_tool"):
if tool_use_behavior == "default":
behavior: Literal["run_llm_again", "stop_on_first_tool"] | ToolsToFinalOutputFunction = (
"run_llm_again"
)
elif tool_use_behavior == "first_tool":
behavior = "stop_on_first_tool"
elif tool_use_behavior == "custom":
behavior = custom_tool_use_behavior
agent = Agent(
name="Weather agent",
instructions="You are a helpful agent.",
tools=[get_weather],
tool_use_behavior=behavior,
model_settings=ModelSettings(
tool_choice="required" if tool_use_behavior != "default" else None
),
)
print(f"\n=== Testing tool_use_behavior: {tool_use_behavior} ===")
result = await Runner.run(agent, input="What's the weather in Tokyo?")
print(f"\nFinal output: {result.final_output}")
if __name__ == "__main__":
asyncio.run(main())
Expected Output: Weather information with different tool use behaviors
About This Example
This is an interactive Python tutorial for the OpenAI Agents SDK. The code runs directly in your browser using PyOdide (Python in WebAssembly).
Key Features:
- No installation required - runs entirely in your browser
- Interactive code editor with syntax highlighting
- Real-time execution using PyOdide
- Complete OpenAI Agents SDK functionality
- Connect with GitHub Models for AI capabilities
Related Examples:
- Agents as Tools - Create a multi-agent system where agents use other agents as tools for translation
- Usage Tracking with Tools - Track API usage metrics including token counts and request statistics when using tools
← Back to all examples
JavaScript is required to run the interactive code editor. Please enable JavaScript in your browser for the full experience.