mirror of
https://github.com/rowboatlabs/rowboat.git
synced 2026-05-05 21:32:46 +02:00
Clean up old swarm code
This commit is contained in:
parent
6ea2d6b568
commit
1fa5c39716
15 changed files with 245 additions and 790 deletions
|
|
@ -1,30 +1,31 @@
|
|||
from src.swarm.types import Agent as SwarmAgent, Response as SwarmResponse
|
||||
import logging
|
||||
import json
|
||||
|
||||
# Import helper functions needed for get_agents
|
||||
from .helpers.access import (
|
||||
get_agent_data_by_name, get_agent_by_name, get_tool_config_by_name,
|
||||
get_tool_config_by_name,
|
||||
get_tool_config_by_type
|
||||
)
|
||||
from .helpers.transfer import create_transfer_function_to_agent, create_transfer_function_to_parent_agent
|
||||
from .helpers.instructions import (
|
||||
add_transfer_instructions_to_child_agents, add_transfer_instructions_to_parent_agents,
|
||||
add_rag_instructions_to_agent, add_universal_system_message_to_agent
|
||||
add_rag_instructions_to_agent
|
||||
)
|
||||
|
||||
from agents import Agent as NewAgent, Runner, FunctionTool, function_tool, RunContextWrapper
|
||||
from agents import Agent as NewAgent, Runner, FunctionTool, RunContextWrapper
|
||||
# Add import for OpenAI functionality
|
||||
from src.utils.common import generate_openai_output
|
||||
from src.utils.common import common_logger as logger, generate_openai_output
|
||||
from typing import Any
|
||||
# Create a dedicated logger for swarm wrapper
|
||||
logger = logging.getLogger("swarm_wrapper")
|
||||
logger.setLevel(logging.INFO)
|
||||
#logger = logging.getLogger("swarm_wrapper")
|
||||
#logger.setLevel(logging.INFO)
|
||||
|
||||
# Re-export the types from src.swarm.types
|
||||
Agent = SwarmAgent
|
||||
Response = SwarmResponse
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional, Dict
|
||||
|
||||
class NewResponse(BaseModel):
|
||||
messages: List[Dict]
|
||||
agent: Optional[Any] = None
|
||||
tokens_used: Optional[dict] = {}
|
||||
error_msg: Optional[str] = ""
|
||||
|
||||
async def catch_all(ctx: RunContextWrapper[Any], args: str, tool_name: str, tool_config: dict) -> str:
|
||||
print(f"Catch all called for tool: {tool_name}")
|
||||
|
|
@ -43,25 +44,22 @@ async def catch_all(ctx: RunContextWrapper[Any], args: str, tool_name: str, tool
|
|||
print(response_content)
|
||||
return(response_content)
|
||||
|
||||
def get_agents(agent_configs, tool_configs, localize_history, available_tool_mappings,
|
||||
agent_data, start_turn_with_start_agent, children_aware_of_parent, universal_sys_msg):
|
||||
def get_agents(agent_configs, tool_configs):
|
||||
"""
|
||||
Creates and initializes Agent objects based on their configurations and connections.
|
||||
This function also sets up parent-child relationships, transfer instructions, and
|
||||
universal system messages.
|
||||
"""
|
||||
if not isinstance(agent_configs, list):
|
||||
raise ValueError("Agents config is not a list in get_agents")
|
||||
if not isinstance(tool_configs, list):
|
||||
raise ValueError("Tools config is not a list in get_agents")
|
||||
|
||||
agents = []
|
||||
new_agents = []
|
||||
new_agent_to_children = {}
|
||||
new_agent_name_to_index = {}
|
||||
# Create Agent objects from config
|
||||
for agent_config in agent_configs:
|
||||
logger.debug(f"Processing config for agent: {agent_config['name']}")
|
||||
print(f"Processing config for agent: {agent_config['name']}")
|
||||
|
||||
# If hasRagSources, append the RAG tool to the agent's tools
|
||||
if agent_config.get("hasRagSources", False):
|
||||
|
|
@ -71,11 +69,9 @@ def get_agents(agent_configs, tool_configs, localize_history, available_tool_map
|
|||
|
||||
# Prepare tool lists for this agent
|
||||
external_tools = []
|
||||
candidate_parent_functions = {}
|
||||
child_functions = {}
|
||||
|
||||
logger.debug(f"Agent {agent_config['name']} has {len(agent_config['tools'])} configured tools")
|
||||
print(tool_configs)
|
||||
print(f"Agent {agent_config['name']} has {len(agent_config['tools'])} configured tools")
|
||||
|
||||
new_tools = []
|
||||
for tool_name in agent_config["tools"]:
|
||||
|
|
@ -97,33 +93,15 @@ def get_agents(agent_configs, tool_configs, localize_history, available_tool_map
|
|||
)
|
||||
new_tools.append(tool)
|
||||
logger.debug(f"Added tool {tool_name} to agent {agent_config['name']}")
|
||||
print(f"Added tool {tool_name} to agent {agent_config['name']}")
|
||||
else:
|
||||
logger.warning(f"Tool {tool_name} not found in tool_configs")
|
||||
|
||||
# Localize history (if applicable)
|
||||
history = []
|
||||
this_agent_data = get_agent_data_by_name(agent_config["name"], agent_data)
|
||||
if this_agent_data and localize_history:
|
||||
history = this_agent_data.get("history", [])
|
||||
print(f"WARNING: Tool {tool_name} not found in tool_configs")
|
||||
|
||||
# Create the agent object
|
||||
logger.debug(f"Creating Agent object for {agent_config['name']}")
|
||||
print(f"Creating Agent object for {agent_config['name']}")
|
||||
try:
|
||||
agent = Agent(
|
||||
name=agent_config["name"],
|
||||
type=agent_config.get("type", "default"),
|
||||
instructions=agent_config["instructions"],
|
||||
description=agent_config.get("description", ""),
|
||||
internal_tools=[],
|
||||
external_tools=external_tools,
|
||||
candidate_parent_functions=candidate_parent_functions,
|
||||
child_functions=child_functions,
|
||||
model=agent_config["model"],
|
||||
respond_to_user=agent_config.get("respond_to_user", False),
|
||||
history=history,
|
||||
children_names=agent_config.get("connectedAgents", []),
|
||||
most_recent_parent=None
|
||||
)
|
||||
new_agent = NewAgent(
|
||||
name=agent_config["name"],
|
||||
instructions=agent_config["instructions"],
|
||||
|
|
@ -134,54 +112,13 @@ def get_agents(agent_configs, tool_configs, localize_history, available_tool_map
|
|||
new_agent_to_children[agent_config["name"]] = agent_config.get("connectedAgents", [])
|
||||
new_agent_name_to_index[agent_config["name"]] = len(new_agents)
|
||||
new_agents.append(new_agent)
|
||||
agents.append(agent)
|
||||
logger.debug(f"Successfully created agent: {agent_config['name']}")
|
||||
print(f"Successfully created agent: {agent_config['name']}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create agent {agent_config['name']}: {str(e)}")
|
||||
print(f"ERROR: Failed to create agent {agent_config['name']}: {str(e)}")
|
||||
raise
|
||||
|
||||
# Reattach most_recent_parent if it exists
|
||||
for agent in agents:
|
||||
this_agent_data = get_agent_data_by_name(agent.name, agent_data)
|
||||
if this_agent_data:
|
||||
most_recent_parent_name = this_agent_data.get("most_recent_parent_name", "")
|
||||
if most_recent_parent_name:
|
||||
parent_agent = get_agent_by_name(most_recent_parent_name, agents)
|
||||
if parent_agent:
|
||||
agent.most_recent_parent = parent_agent
|
||||
|
||||
# Attach children
|
||||
logger.info("Adding children agents to parent agents")
|
||||
for agent in agents:
|
||||
agent.children = {
|
||||
potential_child.name: potential_child
|
||||
for potential_child in agents
|
||||
if potential_child.name in agent.children_names
|
||||
}
|
||||
|
||||
# Generate transfer functions for child agents
|
||||
logger.info("Generating transfer functions for transferring to children agents")
|
||||
transfer_functions = {
|
||||
agent.name: create_transfer_function_to_agent(agent)
|
||||
for agent in agents
|
||||
}
|
||||
|
||||
# Add transfer functions to parent agents for each child
|
||||
logger.info("Adding transfer functions for parents to transfer to children")
|
||||
for agent in agents:
|
||||
for child in agent.children.values():
|
||||
agent.child_functions[child.name] = transfer_functions[child.name]
|
||||
|
||||
# Add parent-related instructions
|
||||
logger.info("Adding child transfer-related instructions to parent agents")
|
||||
for agent in agents:
|
||||
if agent.children:
|
||||
add_transfer_instructions_to_parent_agents(agent, agent.children, transfer_functions)
|
||||
|
||||
# Finally add a universal system message to all agents
|
||||
for agent in agents:
|
||||
add_universal_system_message_to_agent(agent, universal_sys_msg)
|
||||
|
||||
for new_agent in new_agents:
|
||||
# Initialize the handoffs attribute if it doesn't exist
|
||||
if not hasattr(new_agent, 'handoffs'):
|
||||
|
|
@ -189,7 +126,7 @@ def get_agents(agent_configs, tool_configs, localize_history, available_tool_map
|
|||
# Look up the agent's children from the old agent and create a list called handoffs in new_agent with pointers to the children in new_agents
|
||||
new_agent.handoffs = [new_agents[new_agent_name_to_index[child]] for child in new_agent_to_children[new_agent.name]]
|
||||
|
||||
return agents, new_agents
|
||||
return new_agents
|
||||
|
||||
|
||||
def create_response(messages=None, tokens_used=None, agent=None, error_msg=''):
|
||||
|
|
@ -210,10 +147,10 @@ def create_response(messages=None, tokens_used=None, agent=None, error_msg=''):
|
|||
if tokens_used is None:
|
||||
tokens_used = {}
|
||||
|
||||
return Response(
|
||||
return NewResponse(
|
||||
messages=messages,
|
||||
tokens_used=tokens_used,
|
||||
agent=agent,
|
||||
tokens_used=tokens_used,
|
||||
error_msg=error_msg
|
||||
)
|
||||
|
||||
|
|
@ -221,11 +158,7 @@ def create_response(messages=None, tokens_used=None, agent=None, error_msg=''):
|
|||
def run(
|
||||
agent,
|
||||
messages,
|
||||
execute_tools=True,
|
||||
external_tools=None,
|
||||
localize_history=True,
|
||||
parent_has_child_history=True,
|
||||
max_messages_per_turn=10,
|
||||
tokens_used=None
|
||||
):
|
||||
"""
|
||||
|
|
@ -245,6 +178,7 @@ def run(
|
|||
Response object from the Swarm client
|
||||
"""
|
||||
logger.info(f"Initializing Swarm client for agent: {agent.name}")
|
||||
print(f"Initializing Swarm client for agent: {agent.name}")
|
||||
|
||||
# Initialize default parameters
|
||||
if external_tools is None:
|
||||
|
|
@ -271,7 +205,10 @@ def run(
|
|||
})
|
||||
|
||||
# Run the agent with the formatted messages
|
||||
logger.info("Beginning Swarm run with run_sync")
|
||||
print("Beginning Swarm run with run_sync")
|
||||
response2 = Runner.run_sync(agent, formatted_messages)
|
||||
|
||||
logger.info(f"Completed Swarm run for agent: {agent.name}")
|
||||
print(f"Completed Swarm run for agent: {agent.name}")
|
||||
return response2
|
||||
Loading…
Add table
Add a link
Reference in a new issue