-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclaude_agent.py
More file actions
178 lines (155 loc) · 5.74 KB
/
claude_agent.py
File metadata and controls
178 lines (155 loc) · 5.74 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
"""ClaudeModel agent example with tool calling and streaming.
This example demonstrates using the ClaudeModel with both non-streaming and
streaming modes. ClaudeModel uses Anthropic's API (or DashScope compatible endpoint)
and supports tool calling.
Usage:
1. Set environment variables:
- LLM_API_KEY: Your API key
- LLM_BASE_URL: API endpoint (default: https://api.anthropic.com)
- LLM_MODEL: Model name (default: claude-3-5-haiku-latest)
2. Run: uv run python examples/claude_agent.py
Without API credentials, this example falls back to FakeModel for demonstration.
"""
from __future__ import annotations
import asyncio
import os
import sys
from typing import Any
from ecs_agent.components import (
ConversationComponent,
LLMComponent,
ToolRegistryComponent,
)
from ecs_agent.core import Runner, World
from ecs_agent.providers import FakeModel, Model
from ecs_agent.providers.config import ApiFormat
from ecs_agent.providers.protocol import LLMModel
from ecs_agent.types import CompletionResult, Message, ToolSchema
from ecs_agent.systems.error_handling import ErrorHandlingSystem
from ecs_agent.systems.memory import MemorySystem
from ecs_agent.systems.reasoning import ReasoningSystem
from ecs_agent.systems.tool_execution import ToolExecutionSystem
async def get_weather(city: str) -> str:
"""Simulate getting weather for a city."""
weather_db = {
"beijing": "Beijing: Sunny, 22°C, humidity 40%",
"shanghai": "Shanghai: Cloudy, 20°C, humidity 55%",
"shenzhen": "Shenzhen: Rainy, 24°C, humidity 75%",
}
return weather_db.get(city.lower(), f"Weather for {city} not available")
async def get_time(city: str) -> str:
"""Simulate getting current time in a city."""
time_db = {
"beijing": "14:30 (UTC+8)",
"shanghai": "14:30 (UTC+8)",
"newyork": "02:30 (UTC-5)",
}
return time_db.get(city.lower(), f"Time in {city} not available")
async def main() -> None:
"""Run ClaudeModel agent example."""
# Load config from environment
api_key = os.environ.get("LLM_API_KEY", "")
base_url = os.environ.get("LLM_BASE_URL", "https://api.anthropic.com")
model = os.environ.get("LLM_MODEL", "claude-3-5-haiku-latest")
# Decide which model to use
model: LLMModel
if api_key:
print(f"Using claude model: {model}")
model = Model(model, base_url=base_url, api_key=api_key, api_format=ApiFormat.ANTHROPIC_MESSAGES)
else:
print("Using FakeModel (no API key or ClaudeModel unavailable)")
model = FakeModel(
responses=[
CompletionResult(
message=Message(
role="assistant",
content="The weather in Beijing is sunny with a temperature of 22°C. The current time is 14:30.",
)
)
]
)
model = "fake"
# Create World
world = World()
agent_id = world.create_entity()
# Add components
world.add_component(
agent_id,
LLMComponent(model=model),
)
world.add_component(
agent_id,
ConversationComponent(
messages=[
Message(
role="user",
content="What's the weather like in Beijing? And what time is it there?",
)
]
),
)
# Register tools
world.add_component(
agent_id,
ToolRegistryComponent(
tools={
"get_weather": ToolSchema(
name="get_weather",
description="Get the current weather for a city",
parameters={
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name",
}
},
"required": ["city"],
},
),
"get_time": ToolSchema(
name="get_time",
description="Get the current time in a city",
parameters={
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name",
}
},
"required": ["city"],
},
),
},
handlers={"get_weather": get_weather, "get_time": get_time},
),
)
# Register systems
world.register_system(ReasoningSystem(priority=0), priority=0)
world.register_system(ToolExecutionSystem(priority=5), priority=5)
world.register_system(MemorySystem(), priority=10)
world.register_system(ErrorHandlingSystem(priority=99), priority=99)
# Run the agent
print("Running agent...\n")
runner = Runner()
await runner.run(world, max_ticks=5)
# Print conversation
conv = world.get_component(agent_id, ConversationComponent)
if conv:
print("\n" + "=" * 60)
print("CONVERSATION")
print("=" * 60)
for msg in conv.messages:
if msg.role == "user":
print(f"\n[User] {msg.content}")
elif msg.role == "assistant":
if msg.tool_calls:
for tc in msg.tool_calls:
print(f"\n[Tool Call] {tc.name}({tc.arguments})")
else:
print(f"\n[Assistant] {msg.content}")
elif msg.role == "tool":
print(f"[Tool Result] {msg.content}")
if __name__ == "__main__":
asyncio.run(main())