-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun_agent.py
More file actions
283 lines (223 loc) · 9.81 KB
/
run_agent.py
File metadata and controls
283 lines (223 loc) · 9.81 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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/usr/bin/env python3
# Tencent is pleased to support the open source community by making tRPC-Agent-Python available.
#
# Copyright (C) 2026 Tencent. All rights reserved.
#
# tRPC-Agent-Python is licensed under Apache-2.0.
"""Tools demo"""
import asyncio
import uuid
from dotenv import load_dotenv
from trpc_agent_sdk.runners import Runner
from trpc_agent_sdk.sessions import InMemorySessionService
from trpc_agent_sdk.types import Content
from trpc_agent_sdk.types import Part
load_dotenv()
async def run_agent_tool_demo():
"""Run the AgentTool demo agent"""
app_name = "agent_tool_demo"
from agent.agent import create_agent_tool_agent
session_service = InMemorySessionService()
runner = Runner(app_name=app_name, agent=create_agent_tool_agent(), session_service=session_service)
user_id = "demo_user"
demo_queries = [
"Please translate this to Chinese: Artificial intelligence is changing our world.",
]
main_agent = create_agent_tool_agent()
session_service = InMemorySessionService()
runner = Runner(app_name="agent_tool_demo", agent=main_agent, session_service=session_service)
user_id = "demo_user"
session_id = str(uuid.uuid4())
# 测试场景
test_scenarios = [
"请将这段中文翻译成英文:人工智能正在改变我们的世界。",
"Please translate this to Chinese: Hello, how are you today?",
]
for i, query in enumerate(test_scenarios, 1):
print(f"\n Test {i}: {query}")
print("🤖 Assistant: ", end="", flush=True)
user_content = Content(parts=[Part.from_text(text=query)])
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=user_content):
if event.content and event.content.parts and event.author != "user":
if event.partial:
# Streaming output
for part in event.content.parts:
if part.text:
print(part.text, end="", flush=True)
else:
# Tool call and result
for part in event.content.parts:
if part.function_call:
print(f"\n🔧 [Tool call: {part.function_call.name}]")
elif part.function_response:
print(f"📊 [Tool result: {part.function_response.response}]")
print("\n" + "-" * 50)
await runner.close()
print("\n✅ AgentTool demo completed!")
async def run_function_tool_demo():
"""Run the Function Tool demo agent"""
from agent.agent import create_function_tool_agent
print("🔧 Function Tool demo")
print("=" * 60)
print("This demo shows the two usages of Function Tool:")
print("• Directly package asynchronous functions to create tools (get_weather)")
print("• Decorator register asynchronous tools (get_session_info)")
print("=" * 60)
agent = create_function_tool_agent()
session_service = InMemorySessionService()
runner = Runner(app_name="function_tool_demo", agent=agent, session_service=session_service)
user_id = "demo_user"
session_id = str(uuid.uuid4())
# Test queries
test_queries = [
"Please get the weather in Beijing",
"Please get the postal code in Guangdong Shenzhen",
"Please get the session information",
"Now calculate 15 * 3.5",
]
for i, query in enumerate(test_queries, 1):
print(f"\n Test {i}: {query}")
print("🤖 Assistant: ", end="", flush=True)
user_content = Content(parts=[Part.from_text(text=query)])
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=user_content):
if event.content and event.content.parts and event.author != "user":
if event.partial:
# Streaming output
for part in event.content.parts:
if part.text:
print(part.text, end="", flush=True)
else:
# Full event
for part in event.content.parts:
if part.function_call:
print(f"\n🔧 [Tool call: {part.function_call.name}]")
print(f" Args: {part.function_call.args}")
elif part.function_response:
print(f"📊 [Tool result: {part.function_response.response}]")
print("\n" + "-" * 50)
await runner.close()
print("\n✅ Function Tool demo completed!")
async def run_langchain_tool_demo():
"""Run the LangChain Tool demo agent"""
print("🔎 LangChain Tool demo")
print("=" * 60)
print("This demo shows how to use LangChain tool to search the internet")
print("Environment requirements: TAVILY_API_KEY must be set in environment variables")
print("=" * 60)
# Create Agent and Runner
from agent.agent import create_langchain_tool_agent
agent = create_langchain_tool_agent()
session_service = InMemorySessionService()
runner = Runner(app_name="langchain_tool_demo", agent=agent, session_service=session_service)
user_id = "demo_user"
session_id = str(uuid.uuid4())
# Test queries
test_queries = [
"Please search for the latest news in the AI field",
]
for i, query in enumerate(test_queries, 1):
print(f"\n📝 Test {i}: {query}")
print("🤖 Assistant: ", end="", flush=True)
user_content = Content(parts=[Part.from_text(text=query)])
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=user_content):
if event.content and event.content.parts and event.author != "user":
if event.partial:
# Streaming output
for part in event.content.parts:
if part.text:
print(part.text, end="", flush=True)
else:
# Full event
for part in event.content.parts:
if part.function_call:
print(f"\n🔧 [Tool call: {part.function_call.name}]")
print(f" Args: {part.function_call.args}")
elif part.function_response:
print(f"📊 [Tool result: {part.function_response.response}]")
print("\n" + "-" * 50)
await runner.close()
print("\n✅ LangChain Tool demo completed!")
async def run_toolset_demo():
"""Run the ToolSet demo agent"""
print("=" * 60)
print("🔧 ToolSet demo")
print("=" * 60)
# Create Agent and Runner
from agent.agent import create_toolset_agent
agent = create_toolset_agent()
session_service = InMemorySessionService()
runner = Runner(app_name="weather_toolset_demo", agent=agent, session_service=session_service)
# Test different types of users
test_scenarios = [
{
"user_id":
"basic_user",
"user_type":
"basic",
"queries": [
"Please get the current weather in Beijing",
"Please get the weather forecast for Beijing for the next 5 days",
],
},
{
"user_id": "vip_user",
"user_type": "vip",
"queries": [
"Please get the weather forecast for Beijing for the next 5 days",
],
},
]
for scenario in test_scenarios:
user_id = scenario["user_id"]
user_type = scenario["user_type"]
session_id = str(uuid.uuid4())
print(f"\n👤 User type: {user_type.upper()}")
print("=" * 40)
# Create Session and set user state
await session_service.create_session(
app_name="weather_toolset_demo",
user_id=user_id,
session_id=session_id,
state={"user_type": user_type},
)
# Execute test queries
for i, query in enumerate(scenario["queries"], 1):
print(f"\n📝 Test {i}: {query}")
print("🤖 Assistant: ", end="", flush=True)
user_content = Content(parts=[Part.from_text(text=query)])
async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=user_content):
if event.content and event.content.parts and event.author != "user":
if event.partial:
# Streaming output
for part in event.content.parts:
if part.text:
print(part.text, end="", flush=True)
else:
# Full event
for part in event.content.parts:
if part.function_call:
print(f"\n🔧 [Tool call: {part.function_call.name}]")
print(f" Args: {part.function_call.args}")
elif part.function_response:
print(f"📊 [Tool result: {part.function_response.response}]")
print("\n" + "-" * 30)
# Need to close manually
await runner.close()
print("\n✅ ToolSet demo completed!")
# =============================================================================
# Main function
# =============================================================================
async def main():
"""Main function"""
try:
await run_agent_tool_demo()
await run_function_tool_demo()
await run_langchain_tool_demo()
await run_toolset_demo()
except KeyboardInterrupt:
print("\n\n👋 Demo interrupted")
except Exception as e:
print(f"\n❌ Error during demo: {e}")
raise
if __name__ == "__main__":
asyncio.run(main())