-
Notifications
You must be signed in to change notification settings - Fork 895
/
Copy pathrouting.py
70 lines (55 loc) · 2.2 KB
/
routing.py
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
import asyncio
import uuid
from openai.types.responses import ResponseContentPartDoneEvent, ResponseTextDeltaEvent
from agents import Agent, RawResponsesStreamEvent, Runner, TResponseInputItem, trace
"""
This example shows the handoffs/routing pattern. The triage agent receives the first message, and
then hands off to the appropriate agent based on the language of the request. Responses are
streamed to the user.
"""
french_agent = Agent(
name="french_agent",
instructions="You only speak French",
)
spanish_agent = Agent(
name="spanish_agent",
instructions="You only speak Spanish",
)
english_agent = Agent(
name="english_agent",
instructions="You only speak English",
)
triage_agent = Agent(
name="triage_agent",
instructions="Handoff to the appropriate agent based on the language of the request.",
handoffs=[french_agent, spanish_agent, english_agent],
)
async def main():
# We'll create an ID for this conversation, so we can link each trace
conversation_id = str(uuid.uuid4().hex[:16])
msg = input("Hi! We speak French, Spanish and English. How can I help? ")
agent = triage_agent
inputs: list[TResponseInputItem] = [{"content": msg, "role": "user"}]
while True:
# Each conversation turn is a single trace. Normally, each input from the user would be an
# API request to your app, and you can wrap the request in a trace()
with trace("Routing example", group_id=conversation_id):
result = Runner.run_streamed(
agent,
input=inputs,
)
async for event in result.stream_events():
if not isinstance(event, RawResponsesStreamEvent):
continue
data = event.data
if isinstance(data, ResponseTextDeltaEvent):
print(data.delta, end="", flush=True)
elif isinstance(data, ResponseContentPartDoneEvent):
print("\n")
inputs = result.to_input_list()
print("\n")
user_msg = input("Enter a message: ")
inputs.append({"content": user_msg, "role": "user"})
agent = result.current_agent
if __name__ == "__main__":
asyncio.run(main())