OpenAI Agents SDK: Give Your Agent Tools
When you need the AI to actually do something
In the previous post, we created a simple agent that responded in haikus. But the real strength of AI agents emerges when they interact with external tools, making them powerful assistants in dynamic scenarios such as gameplay.
Why Use Tools?
Tools enable your agent to:
Access dynamic or real-time data
Execute specific tasks and computations
Extend their capabilities beyond pre-trained knowledge
Here's how to add a dice-rolling tool to your AI agent for game scenarios like Dungeons & Dragons:
Set up your Python environment:
python -m venv env
source env/bin/activatepip install openai-agents
pip install python-dotenvExample: Dice Rolling Tool
We'll implement a Dice Roll tool that simulates dice rolls for games:
from agents import Agent, Runner, function_tool
import asyncio
import random
from dotenv import load_dotenv
from agents import set_tracing_disabled
from termcolor import colored
load_dotenv()
set_tracing_disabled(True)
@function_tool
def roll_dice(num_dice: int, sides: int) -> str:
if sides < 2:
return "A die must have at least 2 sides."
if num_dice < 1:
return "You must roll at least one die."
results = [random.randint(1, sides) for _ in range(num_dice)]
total = sum(results)
return f"You rolled {results} on {num_dice} {sides}-sided dice, for a total of {total}."
agent = Agent(
name="Dice Roller",
instructions="You're an assistant that helps users roll dice for games.",
tools=[roll_dice]
)
async def main():
print(colored(f"=== Running {agent.name} ===", "cyan"))
user_input = input(colored("Enter your dice roll request: ", "magenta"))
print(colored(f"You: {user_input}", "magenta"))
output = await Runner.run(agent, user_input)
# Use termcolor to colorize the output
colored_output = colored(output.final_output, "green", attrs=["bold"])
print(colored_output)
if __name__ == "__main__":
asyncio.run(main())Running Your Agent
Save the script as dice_roller.py and execute:
python dice_roller.pyNext Steps
Continue your journey by exploring:
OpenAI Agents SDK: Guardrails
OpenAI Agents SDK: Multi-agent Orchestration
Keep your agents versatile and powerful with OpenAI's Agents SDK!






