Create and Run Agents from YAML

The create_agents_from_yaml function is designed to dynamically create agents and orchestrate zytron based on configurations defined in a YAML file. It is particularly suited for enterprise use-cases, offering scalability and reliability for agent-based workflows.

Key Features:

  • Multi-Agent Creation: Automatically instantiate multiple agents from a YAML file.

  • Zytron Architecture: Supports zytron architectures where agents collaborate to solve complex tasks.

  • Logging with Loguru: Includes robust logging for tracking operations and diagnosing issues.

  • Flexible Return Types: Offers several return types based on the requirements of the system.

  • Customizable: Supports additional arguments (*args and **kwargs) for fine-tuning agent behavior.

  • Error Handling: Handles missing configurations and invalid inputs with meaningful error messages.


Parameters

Parameter
Description
Type
Default Value
Example

model

A callable representing the model (LLM or other) that agents will use.

Callable

None

OpenAIChat(model_name="gpt-4")

yaml_file

Path to the YAML file containing agent configurations.

String

"agents.yaml"

"config/agents.yaml"

return_type

Determines the type of return object. Options: "auto", "zytron", "agents", "both", "tasks", "run_zytron".

String

"auto"

"both"

*args

Additional positional arguments for further customization (e.g., agent behavior).

List

N/A

N/A

**kwargs

Additional keyword arguments for customization (e.g., specific parameters passed to the agents or zytron).

Dict

N/A

N/A


Return Types

Return Type
Description

ZytronRouter

Returns a ZytronRouter object, orchestrating the created agents, only if zytron architecture is defined in YAML.

Agent

Returns a single agent if only one is defined.

List[Agent]

Returns a list of agents if multiple are defined.

Tuple

If both agents and a zytron are present, returns both as a tuple (ZytronRouter, List[Agent]).

List[Dict]

Returns a list of task results if tasks were executed.

None

Returns nothing if an invalid return type is provided or an error occurs.


Detailed Return Types

Return Type
Condition
Example Return Value

"auto"

Automatically determines the return based on YAML content.

ZytronRouter if zytron architecture is defined, otherwise Agent or List[Agent].

"zytron"

Returns ZytronRouter if present; otherwise returns agents.

<ZytronRouter>

"agents"

Returns a list of agents (or a single agent if only one is defined).

[<Agent>, <Agent>] or <Agent>

"both"

Returns both Zytron Router and agents in a tuple.

(<ZytronRouter>, [<Agent>, <Agent>])

"tasks"

Returns the task results, if tasks were executed by agents.

[{'task': 'task_output'}, {'task2': 'output'}]

"run_zytron"

Executes the zytron (if defined) and returns the result.

'Zytron task output here'


Example Use Cases

  1. Creating Multiple Agents for Financial Analysis

agents:
  - agent_name: "Financial-Analysis-Agent"
    system_prompt: "Analyze the best investment strategy for 2024."
    max_loops: 1
    autosave: true
    verbose: false
    context_length: 100000
    output_type: "str"
    task: "Analyze stock options for long-term gains."

  - agent_name: "Risk-Analysis-Agent"
    system_prompt: "Evaluate the risk of tech stocks in 2024."
    max_loops: 2
    autosave: false
    verbose: true
    context_length: 50000
    output_type: "json"
    task: "What are the riskiest stocks in the tech sector?"
from zytron.structs.agent import Agent
from zytron.structs.zytron_router import ZytronRouter

# Model representing your LLM
def model(prompt):
    return f"Processed: {prompt}"

# Create agents and return them as a list
agents = create_agents_from_yaml(model=model, yaml_file="agents.yaml", return_type="agents")
print(agents)
  1. Running a Zytron of Agents to Solve a Complex Task

agents:
  - agent_name: "Legal-Agent"
    system_prompt: "Provide legal advice on corporate structuring."
    task: "How to incorporate a business as an LLC?"

zytron_architecture:
  name: "Corporate-Zytron"
  description: "A zytron for helping businesses with legal and tax advice."
  zytron_type: "ConcurrentWorkflow"
  task: "How can we optimize a business structure for maximum tax efficiency?"
  max_loops: 3
import os

from dotenv import load_dotenv
from loguru import logger
from zytron_models import OpenAIChat

from zytron.agents.create_agents_from_yaml import (
    create_agents_from_yaml,
)

# Load environment variables
load_dotenv()

# Path to your YAML file
yaml_file = "agents_multi_agent.yaml"


# Get the OpenAI API key from the environment variable
api_key = os.getenv("GROQ_API_KEY")

# Model
model = OpenAIChat(
    openai_api_base="https://api.groq.com/openai/v1",
    openai_api_key=api_key,
    model_name="llama-3.1-70b-versatile",
    temperature=0.1,
)

try:
    # Create agents and run tasks (using 'both' to return agents and task results)
    task_results = create_agents_from_yaml(
        model=model, yaml_file=yaml_file, return_type="run_zytron"
    )

    logger.info(f"Results from agents: {task_results}")
except Exception as e:
    logger.error(f"An error occurred: {e}")
  1. Returning Both Agents and Tasks

agents:
  - agent_name: "Market-Research-Agent"
    system_prompt: "What are the latest trends in AI?"
    task: "Provide a market analysis for AI technologies in 2024."
from zytron.structs.agent import Agent

# Model representing your LLM
def model(prompt):
    return f"Processed: {prompt}"

# Create agents and run tasks, return both agents and task results
zytron, agents = create_agents_from_yaml(model=model, yaml_file="agents.yaml", return_type="both")
print(zytron, agents)


YAML Schema Overview:

Below is a breakdown of the attributes expected in the YAML configuration file, which governs how agents and zytron are created.

YAML Attributes Table:

Attribute Name
Description
Type
Required
Default/Example Value

agents

List of agents to be created. Each agent must have specific configurations.

List of dicts

Yes

agent_name

The name of the agent.

String

Yes

"Stock-Analysis-Agent"

system_prompt

The system prompt that the agent will use.

String

Yes

"Your full system prompt here"

max_loops

Maximum number of iterations or loops for the agent.

Integer

No

1

autosave

Whether the agent should automatically save its state.

Boolean

No

true

dashboard

Whether to enable a dashboard for the agent.

Boolean

No

false

verbose

Whether to run the agent in verbose mode (for debugging).

Boolean

No

false

dynamic_temperature_enabled

Enable dynamic temperature adjustments during agent execution.

Boolean

No

false

saved_state_path

Path where the agent's state is saved for recovery.

String

No

"path_to_save_state.json"

user_name

Name of the user interacting with the agent.

String

No

"default_user"

retry_attempts

Number of times to retry an operation in case of failure.

Integer

No

1

context_length

Maximum context length for agent interactions.

Integer

No

100000

return_step_meta

Whether to return metadata for each step of the task.

Boolean

No

false

output_type

The type of output the agent will return (e.g., str, json).

String

No

"str"

task

Task to be executed by the agent (optional).

String

No

"What is the best strategy for long-term stock investment?"

Zytron Architecture (Optional):

Attribute Name
Description
Type
Required
Default/Example Value

zytron_architecture

Defines the zytron configuration. For more information on what can be added to the zytron architecture, please refer to the Zytron Router documentation.

Dict

No

name

The name of the zytron.

String

Yes

"MyZytron"

description

Description of the zytron and its purpose.

String

No

"A zytron for collaborative task solving"

max_loops

Maximum number of loops for the zytron.

Integer

No

5

zytron_type

The type of zytron (e.g., ConcurrentWorkflow) SequentialWorkflow.

String

Yes

"ConcurrentWorkflow"

task

The primary task assigned to the zytron.

String

No

"How can we trademark concepts as a delaware C CORP for free?"


YAML Schema Example:

Below is an updated YAML schema that conforms to the function's expectations:

agents:
  - agent_name: "Financial-Analysis-Agent"
    system_prompt: "Your full system prompt here"
    max_loops: 1
    autosave: true
    dashboard: false
    verbose: true
    dynamic_temperature_enabled: true
    saved_state_path: "finance_agent.json"
    user_name: "zytron_corp"
    retry_attempts: 1
    context_length: 200000
    return_step_meta: false
    output_type: "str"
    # task: "How can I establish a ROTH IRA to buy stocks and get a tax break?" # Turn off if using zytron

  - agent_name: "Stock-Analysis-Agent"
    system_prompt: "Your full system prompt here"
    max_loops: 2
    autosave: true
    dashboard: false
    verbose: true
    dynamic_temperature_enabled: false
    saved_state_path: "stock_agent.json"
    user_name: "stock_user"
    retry_attempts: 3
    context_length: 150000
    return_step_meta: true
    output_type: "json"
    # task: "What is the best strategy for long-term stock investment?"

# Optional Zytron Configuration
zytron_architecture:
  name: "MyZytron"
  description: "A zytron for collaborative task solving"
  max_loops: 5
  zytron_type: "ConcurrentWorkflow"
  task: "How can we trademark concepts as a delaware C CORP for free?" # Main task 

Diagram

Send to

Send to

Task

Financial-Analysis-Agent

Stock-Analysis-Agent


How to Use create_agents_from_yaml Function with YAML:

  • You need to plug in your specific model until we can create a model router that can fetch any model and set specific settings

Example Code:

import os

from dotenv import load_dotenv
from loguru import logger
from zytron_models import OpenAIChat

from zytron.agents.create_agents_from_yaml import (
    create_agents_from_yaml,
)

# Load environment variables
load_dotenv()

# Path to your YAML file
yaml_file = "agents.yaml"


# Get the OpenAI API key from the environment variable
api_key = os.getenv("GROQ_API_KEY")

# Model
model = OpenAIChat(
    openai_api_base="https://api.groq.com/openai/v1",
    openai_api_key=api_key,
    model_name="llama-3.1-70b-versatile",
    temperature=0.1,
)

try:
    # Create agents and run tasks (using 'both' to return agents and task results)
    task_results = create_agents_from_yaml(
        model=model, yaml_file=yaml_file, return_type="run_zytron" # 
    )

    logger.info(f"Results from agents: {task_results}")
except Exception as e:
    logger.error(f"An error occurred: {e}")

Error Handling:

  1. FileNotFoundError: If the specified YAML file does not exist.

  2. ValueError: Raised if there are invalid or missing configurations in the YAML file.

  3. Invalid Return Type: If an invalid return type is specified, the function will raise a ValueError.

Last updated