-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathautonomous_agent.py
More file actions
83 lines (71 loc) · 2.35 KB
/
autonomous_agent.py
File metadata and controls
83 lines (71 loc) · 2.35 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
import asyncio
import os
from coagent.agents import Model
from coagent.agents.react_agent import (
ReActAgent,
InputMessage,
InputHistory,
RunContext,
OutputMessage,
MessageOutputItem,
ToolCallItem,
ToolCallOutputItem,
ToolCallProgressItem,
)
from coagent.core import AgentSpec, new, init_logger
from coagent.runtimes import LocalRuntime
async def get_current_city(ctx: RunContext) -> str:
"""Get the current city."""
ctx.report_progress(message="Getting the current city...")
return "Beijing"
async def query_weather(ctx: RunContext, city: str) -> str:
"""Query the weather in the given city."""
ctx.report_progress(message=f"Querying the weather in {city}...")
return f"The weather in {city} is sunny."
reporter = AgentSpec(
"reporter",
new(
ReActAgent,
name="reporter",
system="You are a helpful weather reporter",
model=Model(
id=os.getenv("MODEL_ID"),
base_url=os.getenv("MODEL_BASE_URL"),
api_key=os.getenv("MODEL_API_KEY"),
),
tools=[get_current_city, query_weather],
),
)
async def main():
async with LocalRuntime() as runtime:
await runtime.register(reporter)
result = await reporter.run(
InputHistory(
messages=[InputMessage(role="user", content="What's the weather like?")]
).encode(),
stream=True,
)
async for chunk in result:
msg = OutputMessage.decode(chunk)
i = msg.item
match i:
case MessageOutputItem():
print(i.raw_item.content[0].text, end="", flush=True)
case ToolCallItem():
print(
f"\n[tool#{i.raw_item.call_id} call: {i.raw_item.name}]",
flush=True,
)
case ToolCallProgressItem():
print(
f"\n[tool#{i.raw_item.call_id} progress: {i.raw_item.message}]",
flush=True,
)
case ToolCallOutputItem():
print(
f"\n[tool#{i.raw_item.call_id} output: {i.raw_item.output}]",
flush=True,
)
if __name__ == "__main__":
init_logger()
asyncio.run(main())