forked from openai/openai-agents-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagents_as_tools_conditional.py
More file actions
143 lines (114 loc) · 5.08 KB
/
agents_as_tools_conditional.py
File metadata and controls
143 lines (114 loc) · 5.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import asyncio
from pydantic import BaseModel
from agents import Agent, AgentBase, ModelSettings, RunContextWrapper, Runner, trace
from agents.tool import function_tool
from examples.auto_mode import confirm_with_fallback, input_with_fallback
"""
This example demonstrates the agents-as-tools pattern with conditional tool enabling.
Agent tools are dynamically enabled/disabled based on user access levels using the
is_enabled parameter.
"""
class AppContext(BaseModel):
language_preference: str = "spanish_only" # "spanish_only", "french_spanish", "european"
def french_spanish_enabled(ctx: RunContextWrapper[AppContext], agent: AgentBase) -> bool:
"""Enable for French+Spanish and European preferences."""
return ctx.context.language_preference in ["french_spanish", "european"]
def european_enabled(ctx: RunContextWrapper[AppContext], agent: AgentBase) -> bool:
"""Only enable for European preference."""
return ctx.context.language_preference == "european"
@function_tool(needs_approval=True)
async def get_user_name() -> str:
print("Getting the user's name...")
return "Kaz"
# Create specialized agents
spanish_agent = Agent(
name="spanish_agent",
instructions="You respond in Spanish. Always reply to the user's question in Spanish. You must call all the tools to best answer the user's question.",
model_settings=ModelSettings(tool_choice="required"),
tools=[get_user_name],
)
french_agent = Agent(
name="french_agent",
instructions="You respond in French. Always reply to the user's question in French.",
)
italian_agent = Agent(
name="italian_agent",
instructions="You respond in Italian. Always reply to the user's question in Italian.",
)
# Create orchestrator with conditional tools
orchestrator = Agent(
name="orchestrator",
instructions=(
"You are a multilingual assistant. You use the tools given to you to respond to users. "
"You must call ALL available tools to provide responses in different languages. "
"You never respond in languages yourself, you always use the provided tools."
),
tools=[
spanish_agent.as_tool(
tool_name="respond_spanish",
tool_description="Respond to the user's question in Spanish",
is_enabled=True, # Always enabled
needs_approval=True, # HITL
),
french_agent.as_tool(
tool_name="respond_french",
tool_description="Respond to the user's question in French",
is_enabled=french_spanish_enabled,
),
italian_agent.as_tool(
tool_name="respond_italian",
tool_description="Respond to the user's question in Italian",
is_enabled=european_enabled,
),
],
)
async def main():
"""Interactive demo with LLM interaction."""
print("Agents-as-Tools with Conditional Enabling\n")
print(
"This demonstrates how language response tools are dynamically enabled based on user preferences.\n"
)
print("Choose language preference:")
print("1. Spanish only (1 tool)")
print("2. French and Spanish (2 tools)")
print("3. European languages (3 tools)")
choice = input_with_fallback("\nSelect option (1-3): ", "2").strip()
preference_map = {"1": "spanish_only", "2": "french_spanish", "3": "european"}
language_preference = preference_map.get(choice, "spanish_only")
# Create context and show available tools
context = RunContextWrapper(AppContext(language_preference=language_preference))
available_tools = await orchestrator.get_all_tools(context)
tool_names = [tool.name for tool in available_tools]
print(f"\nLanguage preference: {language_preference}")
print(f"Available tools: {', '.join(tool_names)}")
print(f"The LLM will only see and can use these {len(available_tools)} tools\n")
# Get user request
user_request = input_with_fallback(
"Ask a question and see responses in available languages:\n",
"How do you say good morning?",
)
# Run with LLM interaction
print("\nProcessing request...")
with trace("Conditional tool access"):
result = await Runner.run(
starting_agent=orchestrator,
input=user_request,
context=context.context,
)
while result.interruptions:
async def confirm(question: str) -> bool:
return confirm_with_fallback(f"{question} (y/n): ", default=True)
state = result.to_state()
for interruption in result.interruptions:
prompt = f"\nDo you approve this tool call: {interruption.name} with arguments {interruption.arguments}?"
confirmed = await confirm(prompt)
if confirmed:
state.approve(interruption)
print(f"✓ Approved: {interruption.name}")
else:
state.reject(interruption)
print(f"✗ Rejected: {interruption.name}")
result = await Runner.run(orchestrator, state)
print(f"\nResponse:\n{result.final_output}")
if __name__ == "__main__":
asyncio.run(main())