pull/704/head
Kye Gomez 2 weeks ago
parent da3f12905d
commit df76859173

@ -2,7 +2,6 @@ import asyncio
import os import os
import secrets import secrets
import signal import signal
import sys
import traceback import traceback
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta from datetime import datetime, timedelta
@ -974,7 +973,7 @@ def run_server():
asyncio.run(server.startup()) asyncio.run(server.startup())
except Exception as e: except Exception as e:
logger.error(f"Failed to start API: {str(e)}") logger.error(f"Failed to start API: {str(e)}")
print(f"Error starting server: {str(e)}" print(f"Error starting server: {str(e)}")
if __name__ == "__main__": if __name__ == "__main__":

@ -1,7 +1,7 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, GroupChat, expertise_based from swarms import Agent, GroupChat
if __name__ == "__main__": if __name__ == "__main__":
@ -61,7 +61,6 @@ if __name__ == "__main__":
name="Investment Advisory", name="Investment Advisory",
description="Financial, tax, and stock analysis group", description="Financial, tax, and stock analysis group",
agents=agents, agents=agents,
speaker_fn=expertise_based,
) )
history = chat.run( history = chat.run(

@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry] [tool.poetry]
name = "swarms" name = "swarms"
version = "6.7.8" version = "6.7.9"
description = "Swarms - TGSC" description = "Swarms - TGSC"
license = "MIT" license = "MIT"
authors = ["Kye Gomez <kye@apac.ai>"] authors = ["Kye Gomez <kye@apac.ai>"]

@ -65,6 +65,40 @@ def random_selection(history: List[str], agent: Agent) -> bool:
return random.choice([True, False]) 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: def most_recent(history: List[str], agent: Agent) -> bool:
""" """
Most recent speaker function. Most recent speaker function.
@ -128,9 +162,14 @@ class GroupChat:
AgentResponse: The agent's response captured in a structured format. AgentResponse: The agent's response captured in a structured format.
""" """
try: try:
context = f"""You are {agent.name} with role: {agent.system_prompt}. # Provide the agent with information about the chat and other agents
Other agents: {[a.name for a in self.agents if a != agent]} chat_info = f"Chat Name: {self.name}\nChat Description: {self.description}\nAgents in Chat: {[a.agent_name for a in self.agents]}"
Previous messages: {[t.responses[-3:] for t in self.chat_history.turns[-3:]]}""" 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) message = agent.run(context + prompt)
return AgentResponse( return AgentResponse(
@ -150,6 +189,21 @@ class GroupChat:
preceding_context=[], 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]: def get_recent_messages(self, n: int = 3) -> List[str]:
""" """
Get the most recent messages in the chat. Get the most recent messages in the chat.

@ -2,6 +2,7 @@ import os
import subprocess import subprocess
from typing import List, Optional from typing import List, Optional
from loguru import logger
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from pydantic.v1 import validator from pydantic.v1 import validator
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
@ -13,7 +14,6 @@ from tenacity import (
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.swarm_router import SwarmRouter, SwarmType from swarms.structs.swarm_router import SwarmRouter, SwarmType
from loguru import logger
logger.add("swarm_builder.log", rotation="10 MB", backtrace=True) logger.add("swarm_builder.log", rotation="10 MB", backtrace=True)
@ -507,7 +507,10 @@ swarm = AutoSwarmBuilder(
swarm_type="ConcurrentWorkflow", swarm_type="ConcurrentWorkflow",
) )
try:
result = swarm.run( result = swarm.run(
"Design a new AI accelerator chip optimized for transformer model inference..." "Design a new AI accelerator chip optimized for transformer model inference..."
) )
print(result) print(result)
except Exception as e:
print(f"An error occurred: {e}")

Loading…
Cancel
Save