-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrun.py
74 lines (57 loc) · 2.18 KB
/
run.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
71
72
73
74
# Copyright 2025 GlyphyAI
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
import asyncio
import json
from pydantic import TypeAdapter
from liteswarm import LLM, Agent, AgentContext, ChatMessage, SwarmChat, ToolResult, tool
ChatMessageList = TypeAdapter(list[ChatMessage])
@tool
def fetch_weather(context: AgentContext, location: str) -> ToolResult:
return ToolResult(content="The weather in New York is sunny.")
async def run() -> None:
# Create a simple agent
agent = Agent(
id="assistant",
instructions="You are a helpful assistant that provides clear and concise responses.",
llm=LLM(model="gpt-4o"),
)
weather_agent = Agent(
id="weather",
instructions="You are a weather agent that provides weather information.",
llm=LLM(model="gpt-4o"),
tools=[fetch_weather],
)
@tool(agent=agent)
def switch_to_weather_agent(context: AgentContext) -> ToolResult:
return ToolResult.switch_to(
content="Switched to weather agent",
agent=weather_agent,
params=context.params,
)
# Initialize chat
chat = SwarmChat()
# Send messages and stream responses
user_messages = [
"Hello! My name is John. What can you help me with?",
"What is my name?",
"What is the weather in New York?",
]
for message in user_messages:
print(f"\nUser: {message}")
print("Assistant: ", end="", flush=True)
async for event in chat.send_message(message, agent=agent):
if event.type == "agent_response_chunk":
completion = event.chunk.completion
if completion.delta.content:
print(completion.delta.content, end="", flush=True)
if completion.finish_reason == "stop":
print()
# Get conversation history
chat_messages = await chat.get_messages()
history = ChatMessageList.dump_python(chat_messages, exclude_none=True)
print(f"\nConversation history:\n{json.dumps(history, indent=2)}")
if __name__ == "__main__":
asyncio.run(run())