Spaces:
Sleeping
Sleeping
File size: 10,598 Bytes
d8d14f1 |
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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
import concurrent.futures
from datetime import datetime
from typing import Callable, List
from loguru import logger
from pydantic import BaseModel, Field
from swarms.structs.agent import Agent
class AgentResponse(BaseModel):
agent_name: str
role: str
message: str
timestamp: datetime = Field(default_factory=datetime.now)
turn_number: int
preceding_context: List[str] = Field(default_factory=list)
class ChatTurn(BaseModel):
turn_number: int
responses: List[AgentResponse]
task: str
timestamp: datetime = Field(default_factory=datetime.now)
class ChatHistory(BaseModel):
turns: List[ChatTurn]
total_messages: int
name: str
description: str
start_time: datetime = Field(default_factory=datetime.now)
SpeakerFunction = Callable[[List[str], "Agent"], bool]
def round_robin(history: List[str], agent: Agent) -> bool:
"""
Round robin speaker function.
Each agent speaks in turn, in a circular order.
"""
return True
def expertise_based(history: List[str], agent: Agent) -> bool:
"""
Expertise based speaker function.
An agent speaks if their system prompt is in the last message.
"""
return (
agent.system_prompt.lower() in history[-1].lower()
if history
else True
)
def random_selection(history: List[str], agent: Agent) -> bool:
"""
Random selection speaker function.
An agent speaks randomly.
"""
import random
return random.choice([True, False])
def custom_speaker(history: List[str], agent: Agent) -> bool:
"""
Custom speaker function with complex logic.
Args:
history: Previous conversation messages
agent: Current agent being evaluated
Returns:
bool: Whether agent should speak
"""
# No history - let everyone speak
if not history:
return True
last_message = history[-1].lower()
# Check for agent expertise keywords
expertise_relevant = any(
keyword in last_message
for keyword in agent.description.lower().split()
)
# Check for direct mentions
mentioned = agent.agent_name.lower() in last_message
# Check if agent hasn't spoken recently
not_recent_speaker = not any(
agent.agent_name in msg for msg in history[-3:]
)
return expertise_relevant or mentioned or not_recent_speaker
def most_recent(history: List[str], agent: Agent) -> bool:
"""
Most recent speaker function.
An agent speaks if they are the last speaker.
"""
return (
agent.agent_name == history[-1].split(":")[0].strip()
if history
else True
)
class GroupChat:
"""
GroupChat class to enable multiple agents to communicate in a synchronous group chat.
Each agent is aware of all other agents, every message exchanged, and the social context.
"""
def __init__(
self,
name: str = "GroupChat",
description: str = "A group chat for multiple agents",
agents: List[Agent] = [],
speaker_fn: SpeakerFunction = round_robin,
max_turns: int = 10,
):
"""
Initialize the GroupChat.
Args:
name (str): Name of the group chat.
description (str): Description of the purpose of the group chat.
agents (List[Agent]): A list of agents participating in the chat.
speaker_fn (SpeakerFunction): The function to determine which agent should speak next.
max_turns (int): Maximum number of turns in the chat.
"""
self.name = name
self.description = description
self.agents = agents
self.speaker_fn = speaker_fn
self.max_turns = max_turns
self.chat_history = ChatHistory(
turns=[],
total_messages=0,
name=name,
description=description,
)
def _get_response_sync(
self, agent: Agent, prompt: str, turn_number: int
) -> AgentResponse:
"""
Get the response from an agent synchronously.
Args:
agent (Agent): The agent responding.
prompt (str): The message triggering the response.
turn_number (int): The current turn number.
Returns:
AgentResponse: The agent's response captured in a structured format.
"""
try:
# Provide the agent with information about the chat and other agents
chat_info = f"Chat Name: {self.name}\nChat Description: {self.description}\nAgents in Chat: {[a.agent_name for a in self.agents]}"
context = f"""You are {agent.agent_name}
Conversation History:
\n{chat_info}
Other agents: {[a.agent_name for a in self.agents if a != agent]}
Previous messages: {self.get_full_chat_history()}
""" # Updated line
message = agent.run(context + prompt)
return AgentResponse(
agent_name=agent.name,
role=agent.system_prompt,
message=message,
turn_number=turn_number,
preceding_context=self.get_recent_messages(3),
)
except Exception as e:
logger.error(f"Error from {agent.name}: {e}")
return AgentResponse(
agent_name=agent.name,
role=agent.system_prompt,
message=f"Error generating response: {str(e)}",
turn_number=turn_number,
preceding_context=[],
)
def get_full_chat_history(self) -> str:
"""
Get the full chat history formatted for agent context.
Returns:
str: The full chat history with sender names.
"""
messages = []
for turn in self.chat_history.turns:
for response in turn.responses:
messages.append(
f"{response.agent_name}: {response.message}"
)
return "\n".join(messages)
def get_recent_messages(self, n: int = 3) -> List[str]:
"""
Get the most recent messages in the chat.
Args:
n (int): The number of recent messages to retrieve.
Returns:
List[str]: The most recent messages in the chat.
"""
messages = []
for turn in self.chat_history.turns[-n:]:
for response in turn.responses:
messages.append(
f"{response.agent_name}: {response.message}"
)
return messages
def run(self, task: str) -> ChatHistory:
"""
Run the group chat.
Args:
task (str): The initial message to start the chat.
Returns:
ChatHistory: The history of the chat.
"""
try:
logger.info(
f"Starting chat '{self.name}' with task: {task}"
)
for turn in range(self.max_turns):
current_turn = ChatTurn(
turn_number=turn, responses=[], task=task
)
for agent in self.agents:
if self.speaker_fn(
self.get_recent_messages(), agent
):
response = self._get_response_sync(
agent, task, turn
)
current_turn.responses.append(response)
self.chat_history.total_messages += 1
logger.debug(
f"Turn {turn}, {agent.name} responded"
)
self.chat_history.turns.append(current_turn)
return self.chat_history
except Exception as e:
logger.error(f"Error in chat: {e}")
raise e
def batched_run(self, tasks: List[str], *args, **kwargs):
"""
Run the group chat with a batch of tasks.
Args:
tasks (List[str]): The list of tasks to run in the chat.
Returns:
List[ChatHistory]: The history of each chat.
"""
return [self.run(task, *args, **kwargs) for task in tasks]
def concurrent_run(self, tasks: List[str], *args, **kwargs):
"""
Run the group chat with a batch of tasks concurrently using a thread pool.
Args:
tasks (List[str]): The list of tasks to run in the chat.
Returns:
List[ChatHistory]: The history of each chat.
"""
with concurrent.futures.ThreadPoolExecutor() as executor:
return list(
executor.map(
lambda task: self.run(task, *args, **kwargs),
tasks,
)
)
# if __name__ == "__main__":
# load_dotenv()
# # Get the OpenAI API key from the environment variable
# api_key = os.getenv("OPENAI_API_KEY")
# # Create an instance of the OpenAIChat class
# model = OpenAIChat(
# openai_api_key=api_key,
# model_name="gpt-4o-mini",
# temperature=0.1,
# )
# # Example agents
# agent1 = Agent(
# agent_name="Financial-Analysis-Agent",
# system_prompt="You are a financial analyst specializing in investment strategies.",
# llm=model,
# max_loops=1,
# autosave=False,
# dashboard=False,
# verbose=True,
# dynamic_temperature_enabled=True,
# user_name="swarms_corp",
# retry_attempts=1,
# context_length=200000,
# output_type="string",
# streaming_on=False,
# )
# agent2 = Agent(
# agent_name="Tax-Adviser-Agent",
# system_prompt="You are a tax adviser who provides clear and concise guidance on tax-related queries.",
# llm=model,
# max_loops=1,
# autosave=False,
# dashboard=False,
# verbose=True,
# dynamic_temperature_enabled=True,
# user_name="swarms_corp",
# retry_attempts=1,
# context_length=200000,
# output_type="string",
# streaming_on=False,
# )
# agents = [agent1, agent2]
# chat = GroupChat(
# name="Investment Advisory",
# description="Financial and tax analysis group",
# agents=agents,
# speaker_fn=expertise_based,
# )
# history = chat.run(
# "How to optimize tax strategy for investments?"
# )
# print(history.model_dump_json(indent=2))
|