Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aixplain/factories/agent_factory/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def create_workflow_task(
name: Text,
description: Text,
expected_output: Text,
dependencies: Optional[List[Text]] = None,
dependencies: Optional[List[Text]] = [],
) -> WorkflowTask:
return WorkflowTask(
name=name,
Expand Down
40 changes: 20 additions & 20 deletions aixplain/factories/team_agent_factory/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,11 +244,13 @@ def build_team_agent_from_yaml(yaml_code: str, llm_id: str, api_key: str, team_i
return None
team_config = yaml.safe_load(yaml_code)

agents_data = team_config["agents"]
agents_data = team_config.get("agents", [])
tasks_data = team_config.get("tasks", [])
system_data = team_config["system"] if "system" in team_config else {"query": "", "name": "Test Team"}
team_name = system_data["name"]

system_data = team_config.get("system", {"query": "", "name": "Test Team"})
team_name = system_data.get("name", "")
team_description = system_data.get("description", "")
team_instructions = system_data.get("instructions", "")
llm = ModelFactory.get(llm_id)
# Create agent mapping by name for easier task assignment
agents_mapping = {}
agent_objs = []
Expand All @@ -257,38 +259,35 @@ def build_team_agent_from_yaml(yaml_code: str, llm_id: str, api_key: str, team_i
for agent_entry in agents_data:
agent_name = list(agent_entry.keys())[0]
agent_info = agent_entry[agent_name]
agent_instructions = agent_info["instructions"]
agent_goal = agent_info["goal"]
agent_backstory = agent_info["backstory"]

description = f"You are an expert {agent_instructions}. {agent_backstory} Your primary goal is to {agent_goal}. Use your expertise to ensure the success of your tasks."
agent_instructions = agent_info.get("instructions", "")
agent_description = agent_info["description"]
agent_name = agent_name.replace("_", " ")
agent_name = f"{agent_name} agent" if not agent_name.endswith(" agent") else agent_name
agent_obj = Agent(
id="",
name=agent_name,
description=description,
instructions=description,
description=agent_description,
instructions=agent_instructions,
tasks=[], # Tasks will be assigned later
tools=[parse_tool_from_yaml(tool) for tool in agent_info.get("tools", []) if tool != "language_model"],
llmId=llm_id,
llm=llm,
)
agents_mapping[agent_name] = agent_obj
agent_objs.append(agent_obj)

# Parse tasks and assign them to the corresponding agents
for task in tasks_data:
for task_name, task_info in task.items():
description = task_info["description"]
expected_output = task_info["expected_output"]
task_description = task_info.get("description", "")
expected_output = task_info.get("expected_output", "")
dependencies = task_info.get("dependencies", [])
agent_name = task_info["agent"]
agent_name = task_info.get("agent", "")
agent_name = agent_name.replace("_", " ")
agent_name = f"{agent_name} agent" if not agent_name.endswith(" agent") else agent_name

task_obj = AgentTask(
name=task_name,
description=description,
description=task_description,
expected_output=expected_output,
dependencies=dependencies,
)
Expand All @@ -303,17 +302,18 @@ def build_team_agent_from_yaml(yaml_code: str, llm_id: str, api_key: str, team_i
for i, agent in enumerate(agent_objs):
agent_objs[i] = AgentFactory.create(
name=agent.name,
description=agent.instructions,
description=agent.description,
instructions=agent.instructions,
tools=agent.tools,
llm_id=llm_id,
llm=llm,
tasks=agent.tasks,
)

return TeamAgentFactory.create(
name=team_name,
description=team_description,
instructions=team_instructions,
agents=agent_objs,
llm_id=llm_id,
llm=llm,
api_key=api_key,
use_mentalist=True,
inspectors=[],
Expand Down
9 changes: 6 additions & 3 deletions aixplain/modules/agent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ def from_dict(cls, data: Dict) -> "Agent":
"""
from aixplain.factories.agent_factory.utils import build_tool
from aixplain.enums import AssetStatus
from aixplain.modules.agent_task import WorkflowTask
from aixplain.modules.agent import WorkflowTask

# Extract tools from assets using proper tool building
tools = []
Expand Down Expand Up @@ -805,7 +805,8 @@ def evolve(
Returns:
AgentResponse: Final response from the evolution process.
"""
from aixplain.utils.evolve_utils import from_yaml, create_llm_dict
from aixplain.utils.evolve_utils import create_llm_dict
from aixplain.factories.team_agent_factory.utils import build_team_agent_from_yaml

# Create EvolveParam from individual parameters
evolve_parameters = EvolveParam(
Expand Down Expand Up @@ -841,9 +842,11 @@ def evolve(

if "current_code" in result_data and result_data["current_code"] is not None:
if evolve_parameters.evolve_type == EvolveType.TEAM_TUNING:
result_data["evolved_agent"] = from_yaml(
result_data["evolved_agent"] = build_team_agent_from_yaml(
result_data["current_code"],
self.llm_id,
self.api_key,
self.id,
)
elif evolve_parameters.evolve_type == EvolveType.INSTRUCTION_TUNING:
self.instructions = result_data["current_code"]
Expand Down
2 changes: 1 addition & 1 deletion aixplain/modules/agent/agent_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(
name: Text,
description: Text,
expected_output: Text,
dependencies: Optional[List[Union[Text, "WorkflowTask"]]] = None,
dependencies: Optional[List[Union[Text, "WorkflowTask"]]] = [],
):
"""Initialize a new WorkflowTask instance.

Expand Down
15 changes: 9 additions & 6 deletions aixplain/modules/team_agent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,6 @@ def poll(self, poll_url: Text, name: Text = "model_process") -> AgentResponse:
evolved_agent = self
current_code = resp_data.get("current_code", "")
evolved_agent.description = current_code
evolved_agent.instructions = current_code
evolved_agent.update()
resp_data["evolved_agent"] = evolved_agent
else:
Expand Down Expand Up @@ -586,10 +585,10 @@ def from_dict(cls, data: Dict) -> "TeamAgent":
Returns:
TeamAgent instance
"""
from aixplain.factories.agent_factory import AgentFactory
from aixplain.factories.model_factory import ModelFactory
from aixplain.enums import AssetStatus
from aixplain.modules.team_agent import Inspector, InspectorTarget
from aixplain.modules.agent import Agent

# Extract agents from agents list using proper agent loading
agents = []
Expand All @@ -598,14 +597,15 @@ def from_dict(cls, data: Dict) -> "TeamAgent":
if "assetId" in agent_data:
try:
# Load agent using AgentFactory
agent = AgentFactory.get(agent_data["assetId"])
agent = Agent.from_dict(agent_data)
agents.append(agent)
except Exception as e:
# Log warning but continue processing other agents
import logging

logging.warning(f"Failed to load agent {agent_data['assetId']}: {e}")

else:
agents.append(Agent.from_dict(agent_data))
# Extract inspectors using proper model validation
inspectors = []
if "inspectors" in data:
Expand Down Expand Up @@ -864,7 +864,8 @@ def evolve(
AgentResponse: Final response from the evolution process.
"""
from aixplain.enums import EvolveType
from aixplain.utils.evolve_utils import from_yaml, create_llm_dict
from aixplain.utils.evolve_utils import create_llm_dict
from aixplain.factories.team_agent_factory.utils import build_team_agent_from_yaml

# Create EvolveParam from individual parameters
evolve_parameters = EvolveParam(
Expand Down Expand Up @@ -899,9 +900,11 @@ def evolve(
current_code = result_data.get("current_code") if isinstance(result_data, dict) else result_data.current_code
if current_code is not None:
if evolve_parameters.evolve_type == EvolveType.TEAM_TUNING:
result_data["evolved_agent"] = from_yaml(
result_data["evolved_agent"] = build_team_agent_from_yaml(
result_data["current_code"],
self.llm_id,
self.api_key,
self.id,
)
elif evolve_parameters.evolve_type == EvolveType.INSTRUCTION_TUNING:
self.instructions = result_data["current_code"]
Expand Down
1 change: 0 additions & 1 deletion aixplain/modules/team_agent/evolver_response_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ def from_dict(cls, data: Dict[str, Any], llm_id: Text, api_key: Text) -> "Evolve

yaml_code = data.get("current_code", "")
evolved_team_agent = build_team_agent_from_yaml(yaml_code=yaml_code, llm_id=llm_id, api_key=api_key)

return cls(
evolved_agent=evolved_team_agent,
current_code=yaml_code,
Expand Down
174 changes: 0 additions & 174 deletions aixplain/utils/evolve_utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import yaml
from typing import Union, Dict, Any, Optional, Text
from aixplain.enums import Function, Supplier
from aixplain.modules.agent import Agent
from aixplain.modules.team_agent import TeamAgent
from aixplain.modules.model.llm_model import LLM
from aixplain.factories import AgentFactory, TeamAgentFactory


def create_llm_dict(llm: Optional[Union[Text, LLM]]) -> Optional[Dict[str, Any]]:
Expand Down Expand Up @@ -32,172 +27,3 @@ def create_llm_dict(llm: Optional[Union[Text, LLM]]) -> Optional[Dict[str, Any]]
}
else:
return {"id": llm}


def generate_tools_from_str(tools: list) -> list:
obj_tools = []
for tool in tools:
tool_name = tool.strip()
if tool_name == "translation":
obj_tools.append(
AgentFactory.create_model_tool(
function=Function.TRANSLATION,
supplier=Supplier.GOOGLE,
)
)
elif tool_name == "speech-recognition":
obj_tools.append(
AgentFactory.create_model_tool(
function=Function.SPEECH_RECOGNITION,
supplier=Supplier.GOOGLE,
)
)
elif tool_name == "text-to-speech":
obj_tools.append(
AgentFactory.create_model_tool(
function=Function.SPEECH_SYNTHESIS,
supplier=Supplier.GOOGLE,
)
)
elif tool_name == "serper_search":
obj_tools.append(AgentFactory.create_model_tool(model="65c51c556eb563350f6e1bb1"))
elif tool_name == "website_search":
obj_tools.append(AgentFactory.create_model_tool(model="6736411cf127849667606689"))
elif tool_name == "website_scrape":
obj_tools.append(AgentFactory.create_model_tool(model="6748e4746eb5633559668a15"))
else:
continue
return obj_tools


def from_yaml(
yaml_code: str,
llm_id: str,
) -> Union[TeamAgent, Agent]:
team_config = yaml.safe_load(yaml_code)

agents_data = team_config["agents"]
tasks_data = team_config.get("tasks", [])
system_data = team_config["system"] if "system" in team_config else {"query": ""}
expected_output = system_data.get("expected_output")
team_name = system_data.get("name")
team_description = system_data.get("description", "")
team_instructions = system_data.get("instructions", "")

# Create agent mapping by name for easier task assignment
agents_mapping = {}
agent_objs = []

# Parse agents
for agent_entry in agents_data:
# Handle different YAML structures
if isinstance(agent_entry, dict):
# Case 1: Standard structure - {agent_name: {instructions: ..., goal: ..., backstory: ...}}
for agent_name, agent_info in agent_entry.items():
# Check if agent_info is a list (malformed YAML structure)
if isinstance(agent_info, list):
# Handle malformed structure where agent_info is a list
# This happens when YAML has unquoted keys that create nested structures
continue
elif isinstance(agent_info, dict):
agent_instructions = agent_info["instructions"]
agent_goal = agent_info["goal"]
agent_backstory = agent_info["backstory"]

description = f"## ROLE\n{agent_instructions}\n\n## GOAL\n{agent_goal}\n\n## BACKSTORY\n{agent_backstory}"
agent_obj = AgentFactory.create(
name=agent_name.replace("_", " "),
description=description,
tasks=[], # Tasks will be assigned later
tools=generate_tools_from_str(agent_info.get("tools", [])),
llm_id=llm_id,
)
agents_mapping[agent_name] = agent_obj
agent_objs.append(agent_obj)
elif isinstance(agent_entry, list):
# Case 2: Handle list structure (alternative YAML format)
for item in agent_entry:
if isinstance(item, dict):
for agent_name, agent_info in item.items():
if isinstance(agent_info, dict):
agent_instructions = agent_info["instructions"]
agent_goal = agent_info["goal"]
agent_backstory = agent_info["backstory"]

description = (
f"## ROLE\n{agent_instructions}\n\n## GOAL\n{agent_goal}\n\n## BACKSTORY\n{agent_backstory}"
)
agent_tools = generate_tools_from_str(agent_info.get("tools", []))
agent_obj = AgentFactory.create(
name=agent_name.replace("_", " "),
description=description,
tools=agent_tools,
tasks=[],
llm_id=llm_id,
)
agents_mapping[agent_name] = agent_obj
agent_objs.append(agent_obj)

# Parse tasks and assign them to the corresponding agents
for task_entry in tasks_data:
# Handle different YAML structures for tasks
if isinstance(task_entry, dict):
# Case 1: Standard structure - {task_name: {description: ..., expected_output: ..., agent: ...}}
for task_name, task_info in task_entry.items():
# Check if task_info is a list (malformed YAML structure)
if isinstance(task_info, list):
# Handle malformed structure where task_info is a list
continue
elif isinstance(task_info, dict):
description = task_info["description"]
expected_output = task_info["expected_output"]
dependencies = task_info.get("dependencies", [])
agent_name = task_info["agent"]
task_obj = AgentFactory.create_task(
name=task_name.replace("_", " "),
description=description,
expected_output=expected_output,
dependencies=dependencies,
)

# Assign the task to the corresponding agent
if agent_name in agents_mapping:
agent = agents_mapping[agent_name]
agent.tasks.append(task_obj)
else:
raise ValueError(f"Agent '{agent_name}' referenced in tasks not found.")
elif isinstance(task_entry, list):
# Case 2: Handle list structure (alternative YAML format)
for item in task_entry:
if isinstance(item, dict):
for task_name, task_info in item.items():
if isinstance(task_info, dict):
description = task_info["description"]
expected_output = task_info["expected_output"]
dependencies = task_info.get("dependencies", [])
agent_name = task_info["agent"]

task_obj = AgentFactory.create_task(
name=task_name.replace("_", " "),
description=description,
expected_output=expected_output,
dependencies=dependencies,
)

# Assign the task to the corresponding agent
if agent_name in agents_mapping:
agent = agents_mapping[agent_name]
agent.tasks.append(task_obj)
else:
raise ValueError(f"Agent '{agent_name}' referenced in tasks not found.")

team = TeamAgentFactory.create(
name=team_name,
description=team_description,
instructions=team_instructions,
agents=agent_objs,
llm_id=llm_id,
use_mentalist=True,
inspectors=[],
)
return team
Loading