docs improvement

pull/962/merge
Kye Gomez 5 days ago
parent c6443ffdf2
commit 7119e514e1

@ -226,6 +226,7 @@ print(final_post)
| **[ForestSwarm](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/)** | Dynamically selects the most suitable agent or tree of agents for a given task. | Task routing, optimizing for expertise, complex decision-making trees. | | **[ForestSwarm](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/)** | Dynamically selects the most suitable agent or tree of agents for a given task. | Task routing, optimizing for expertise, complex decision-making trees. |
| **[SpreadSheetSwarm](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)** | Manages thousands of agents concurrently, tracking tasks and outputs in a structured format. | Massive-scale parallel operations, large-scale data generation and analysis. | | **[SpreadSheetSwarm](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)** | Manages thousands of agents concurrently, tracking tasks and outputs in a structured format. | Massive-scale parallel operations, large-scale data generation and analysis. |
| **[HierarchicalSwarm](https://docs.swarms.world/en/latest/swarms/structs/hiearchical_swarm/)** | Orchestrates agents with a director that creates plans and distributes tasks to specialized worker agents. | Complex project management, team coordination, hierarchical decision-making with feedback loops. | | **[HierarchicalSwarm](https://docs.swarms.world/en/latest/swarms/structs/hiearchical_swarm/)** | Orchestrates agents with a director that creates plans and distributes tasks to specialized worker agents. | Complex project management, team coordination, hierarchical decision-making with feedback loops. |
| **[HeavySwarm](https://docs.swarms.world/en/latest/swarms/structs/heavy_swarm/)** | Implements a 5-phase workflow with specialized agents (Research, Analysis, Alternatives, Verification) for comprehensive task analysis. | Complex research and analysis tasks, financial analysis, strategic planning, comprehensive reporting. |
| **[SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)** | Universal orchestrator that provides a single interface to run any type of swarm with dynamic selection. | Simplifying complex workflows, switching between swarm strategies, unified multi-agent management. | | **[SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)** | Universal orchestrator that provides a single interface to run any type of swarm with dynamic selection. | Simplifying complex workflows, switching between swarm strategies, unified multi-agent management. |
----- -----
@ -537,6 +538,49 @@ The `HierarchicalSwarm` excels at:
--- ---
### HeavySwarm
`HeavySwarm` implements a sophisticated 5-phase workflow inspired by X.AI's Grok heavy implementation. It uses specialized agents (Research, Analysis, Alternatives, Verification) to provide comprehensive task analysis through intelligent question generation, parallel execution, and synthesis. This architecture excels at complex research and analysis tasks requiring thorough investigation and multiple perspectives.
```python
from swarms import HeavySwarm
# Initialize the HeavySwarm with configuration
swarm = HeavySwarm(
worker_model_name="gpt-4o-mini", # Model for worker agents
question_agent_model_name="gpt-4o-mini", # Model for question generation
loops_per_agent=1, # Number of loops per agent
show_dashboard=True, # Enable real-time dashboard
)
# Run complex analysis task
result = swarm.run(
"Provide 3 publicly traded biotech companies that are currently trading below their cash value. "
"For each company identified, provide available data or projections for the next 6 months, "
"including any relevant financial metrics, upcoming catalysts, or events that could impact valuation. "
"Present your findings in a clear, structured format with ticker symbols, current prices, "
"cash values, and percentage differences."
)
print(result)
```
The `HeavySwarm` provides:
- **5-Phase Analysis**: Question generation, research, analysis, alternatives, and verification
- **Specialized Agents**: Each phase uses purpose-built agents for optimal results
- **Comprehensive Coverage**: Multiple perspectives and thorough investigation
- **Real-time Dashboard**: Optional visualization of the analysis process
- **Structured Output**: Well-organized and actionable results
This architecture is perfect for financial analysis, strategic planning, research reports, and any task requiring deep, multi-faceted analysis. [Learn more about HeavySwarm](https://docs.swarms.world/en/latest/swarms/structs/heavy_swarm/)
---
## Documentation ## Documentation
Documentation is located here at: [docs.swarms.world](https://docs.swarms.world) Documentation is located here at: [docs.swarms.world](https://docs.swarms.world)

@ -157,34 +157,36 @@ nav:
- Feature Set: "swarms/features.md" - Feature Set: "swarms/features.md"
- Agents: - Agents:
- Overview: "swarms/agents/index.md" - Overview: "swarms/agents/index.md"
- Concepts: - Architecture: "swarms/framework/agents_explained.md"
# - Managing Prompts in Production: "swarms/prompts/main.md" - Agent Class Reference: "swarms/structs/agent.md"
- Introduction into The Agent Architecture: "swarms/framework/agents_explained.md" - LLM Providers: "swarms/models/agent_and_models.md"
# - Introduction to Tools: "swarms/tools/overview.md" - Tools and MCP: "swarms/tools/tools_examples.md"
- Documentation: - Multi-Agent Helpers: "swarms/structs/agent_multi_agent_communication.md"
- Agent Class Documentation: "swarms/structs/agent.md" - Build, Run, and Manage Agents With YAML: "swarms/agents/create_agents_yaml.md"
- Create and Run Agents from YAML: "swarms/agents/create_agents_yaml.md"
- Integrating Various Models into Your Agents: "swarms/models/agent_and_models.md"
- Tools: - Additional Capabilities:
- Tools Reference:
- Overview: "swarms/tools/main.md" - Overview: "swarms/tools/main.md"
- What are tools?: "swarms/tools/build_tool.md" - What are tools?: "swarms/tools/build_tool.md"
- Structured Outputs: "swarms/agents/structured_outputs.md" - Structured Outputs: "swarms/agents/structured_outputs.md"
- Agent MCP Integration: "swarms/structs/agent_mcp.md" - Agent MCP Integration: "swarms/structs/agent_mcp.md"
- Comprehensive Tool Guide with MCP, Callables, and more: "swarms/tools/tools_examples.md" - Long Term Memory Reference:
- RAG || Long Term Memory:
- Integrating RAG with Agents: "swarms/memory/diy_memory.md" - Integrating RAG with Agents: "swarms/memory/diy_memory.md"
- Third-Party Agent Integrations:
- Third-Party Agents:
- Creating Custom Agents: "swarms/agents/new_agent.md"
- OpenAI Assistant: "swarms/agents/openai_assistant.md" - OpenAI Assistant: "swarms/agents/openai_assistant.md"
- Integrating External Agents from Griptape, Langchain, etc: "swarms/agents/external_party_agents.md" - Integrating External Agents from Griptape, Langchain, etc: "swarms/agents/external_party_agents.md"
- Creating Custom Agents: "swarms/agents/new_agent.md"
- PreBuilt Reasoning Agents: - Specialized Reasoning Agents:
- Self Consistency Agent: "swarms/agents/consistency_agent.md" - Self Consistency Agent: "swarms/agents/consistency_agent.md"
- IRE Agent: "swarms/agents/iterative_agent.md" - IRE Agent: "swarms/agents/iterative_agent.md"
- Reasoning Duo: "swarms/agents/reasoning_duo.md" - Reasoning Duo: "swarms/agents/reasoning_duo.md"
- Reasoning Agent Router: "swarms/agents/reasoning_agent_router.md"
- Reflexion Agent: "swarms/agents/reflexion_agent.md" - Reflexion Agent: "swarms/agents/reflexion_agent.md"
- GKP Agent: "swarms/agents/gkp_agent.md" - GKP Agent: "swarms/agents/gkp_agent.md"
- Agent Judge: "swarms/agents/agent_judge.md" - Agent Judge: "swarms/agents/agent_judge.md"
- Reasoning Agent Router: "swarms/agents/reasoning_agent_router.md"
- Multi-Agent Architectures: - Multi-Agent Architectures:
- Introduction to Multi-Agent Collaboration: "swarms/concept/why.md" - Introduction to Multi-Agent Collaboration: "swarms/concept/why.md"

@ -0,0 +1,205 @@
# Agent Multi-Agent Communication Methods
The Agent class provides powerful built-in methods for facilitating communication and collaboration between multiple agents. These methods enable agents to talk to each other, pass information, and coordinate complex multi-agent workflows seamlessly.
## Overview
Multi-agent communication is essential for building sophisticated AI systems where different agents need to collaborate, share information, and coordinate their actions. The Agent class provides several methods to facilitate this communication:
| Method | Purpose | Use Case |
|--------|---------|----------|
| `talk_to` | Direct communication between two agents | Agent handoffs, expert consultation |
| `talk_to_multiple_agents` | Concurrent communication with multiple agents | Broadcasting, consensus building |
| `receive_message` | Process incoming messages from other agents | Message handling, task delegation |
| `send_agent_message` | Send formatted messages to other agents | Direct messaging, notifications |
## Features
| Feature | Description |
|---------------------------------|--------------------------------------------------------------------|
| **Direct Agent Communication** | Enable one-to-one conversations between agents |
| **Concurrent Multi-Agent Communication** | Broadcast messages to multiple agents simultaneously |
| **Message Processing** | Handle incoming messages with contextual formatting |
| **Error Handling** | Robust error handling for failed communications |
| **Threading Support** | Efficient concurrent processing using ThreadPoolExecutor |
| **Flexible Parameters** | Support for images, custom arguments, and kwargs |
---
## Core Methods
### `talk_to(agent, task, img=None, *args, **kwargs)`
Enables direct communication between the current agent and another agent. The method processes the task, generates a response, and then passes that response to the target agent.
**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent` | `Any` | Required | The target agent instance to communicate with |
| `task` | `str` | Required | The task or message to send to the agent |
| `img` | `str` | `None` | Optional image path for multimodal communication |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
**Returns:** `Any` - The response from the target agent
**Usage Example:**
```python
from swarms import Agent
# Create two specialized agents
researcher = Agent(
agent_name="Research-Agent",
system_prompt="You are a research specialist focused on gathering and analyzing information.",
max_loops=1,
)
analyst = Agent(
agent_name="Analysis-Agent",
system_prompt="You are an analytical specialist focused on interpreting research data.",
max_loops=1,
)
# Agent communication
research_result = researcher.talk_to(
agent=analyst,
task="Analyze the market trends for renewable energy stocks"
)
print(research_result)
```
### `talk_to_multiple_agents(agents, task, *args, **kwargs)`
Enables concurrent communication with multiple agents using ThreadPoolExecutor for efficient parallel processing.
**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agents` | `List[Union[Any, Callable]]` | Required | List of agent instances to communicate with |
| `task` | `str` | Required | The task or message to send to all agents |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
**Returns:** `List[Any]` - List of responses from all agents (or None for failed communications)
**Usage Example:**
```python
from swarms import Agent
# Create multiple specialized agents
agents = [
Agent(
agent_name="Financial-Analyst",
system_prompt="You are a financial analysis expert.",
max_loops=1,
),
Agent(
agent_name="Risk-Assessor",
system_prompt="You are a risk assessment specialist.",
max_loops=1,
),
Agent(
agent_name="Market-Researcher",
system_prompt="You are a market research expert.",
max_loops=1,
)
]
coordinator = Agent(
agent_name="Coordinator-Agent",
system_prompt="You coordinate multi-agent analysis.",
max_loops=1,
)
# Broadcast to multiple agents
responses = coordinator.talk_to_multiple_agents(
agents=agents,
task="Evaluate the investment potential of Tesla stock"
)
# Process responses
for i, response in enumerate(responses):
if response:
print(f"Agent {i+1} Response: {response}")
else:
print(f"Agent {i+1} failed to respond")
```
### `receive_message(agent_name, task, *args, **kwargs)`
Processes incoming messages from other agents with proper context formatting.
**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent_name` | `str` | Required | Name of the sending agent |
| `task` | `str` | Required | The message content |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
**Returns:** `Any` - The agent's response to the received message
**Usage Example:**
```python
from swarms import Agent
# Create an agent that can receive messages
recipient_agent = Agent(
agent_name="Support-Agent",
system_prompt="You provide helpful support and assistance.",
max_loops=1,
)
# Simulate receiving a message from another agent
response = recipient_agent.receive_message(
agent_name="Customer-Service-Agent",
task="A customer is asking about refund policies. Can you help?"
)
print(response)
```
### `send_agent_message(agent_name, message, *args, **kwargs)`
Sends a formatted message from the current agent to a specified target agent.
**Parameters:**
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent_name` | `str` | Required | Name of the target agent |
| `message` | `str` | Required | The message to send |
| `*args` | `Any` | - | Additional positional arguments |
| `**kwargs` | `Any` | - | Additional keyword arguments |
**Returns:** `Any` - The result of sending the message
**Usage Example:**
```python
from swarms import Agent
sender_agent = Agent(
agent_name="Notification-Agent",
system_prompt="You send notifications and updates.",
max_loops=1,
)
# Send a message to another agent
result = sender_agent.send_agent_message(
agent_name="Task-Manager-Agent",
message="Task XYZ has been completed successfully"
)
print(result)
```
This comprehensive guide covers all aspects of multi-agent communication using the Agent class methods. These methods provide the foundation for building sophisticated multi-agent systems with robust communication capabilities.

@ -35,6 +35,6 @@ agent_spec = AgentSpecParam(
print(json.dumps(client.models.list_available(), indent=4)) print(json.dumps(client.models.list_available(), indent=4))
print(json.dumps(client.health.check(), indent=4)) print(json.dumps(client.health.check(), indent=4))
print(json.dumps(client.client.get_logs(), indent=4)) print(json.dumps(client.swarms.get_logs(), indent=4))
print(json.dumps(client.client.rate.get_limits(), indent=4)) print(json.dumps(client.client.rate.get_limits(), indent=4))
print(json.dumps(client.swarms.check_available(), indent=4)) print(json.dumps(client.swarms.check_available(), indent=4))

@ -0,0 +1,302 @@
"""
Agent Multi-Agent Communication Examples
This file demonstrates the multi-agent communication methods available in the Agent class:
- talk_to: Direct communication between two agents
- talk_to_multiple_agents: Concurrent communication with multiple agents
- receive_message: Process incoming messages from other agents
- send_agent_message: Send formatted messages to other agents
Run: python agent_communication_examples.py
"""
import os
from swarms import Agent
# Set up your API key
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
def example_1_direct_agent_communication():
"""Example 1: Direct communication between two agents using talk_to method"""
print("=" * 60)
print("Example 1: Direct Agent Communication")
print("=" * 60)
# Create two specialized agents
researcher = Agent(
agent_name="Research-Agent",
system_prompt="You are a research specialist focused on gathering and analyzing information. Provide detailed, fact-based responses.",
max_loops=1,
verbose=False,
)
analyst = Agent(
agent_name="Analysis-Agent",
system_prompt="You are an analytical specialist focused on interpreting research data and providing strategic insights.",
max_loops=1,
verbose=False,
)
# Agent communication
print("Researcher talking to Analyst...")
research_result = researcher.talk_to(
agent=analyst,
task="Analyze the market trends for renewable energy stocks and provide investment recommendations",
)
print(f"\nFinal Analysis Result:\n{research_result}")
return research_result
def example_2_multiple_agent_communication():
"""Example 2: Broadcasting to multiple agents using talk_to_multiple_agents"""
print("\n" + "=" * 60)
print("Example 2: Multiple Agent Communication")
print("=" * 60)
# Create multiple specialized agents
agents = [
Agent(
agent_name="Financial-Analyst",
system_prompt="You are a financial analysis expert specializing in stock valuation and market trends.",
max_loops=1,
verbose=False,
),
Agent(
agent_name="Risk-Assessor",
system_prompt="You are a risk assessment specialist focused on identifying potential investment risks.",
max_loops=1,
verbose=False,
),
Agent(
agent_name="Market-Researcher",
system_prompt="You are a market research expert specializing in industry analysis and competitive intelligence.",
max_loops=1,
verbose=False,
),
]
coordinator = Agent(
agent_name="Coordinator-Agent",
system_prompt="You coordinate multi-agent analysis and synthesize diverse perspectives into actionable insights.",
max_loops=1,
verbose=False,
)
# Broadcast to multiple agents
print("Coordinator broadcasting to multiple agents...")
responses = coordinator.talk_to_multiple_agents(
agents=agents,
task="Evaluate the investment potential of Tesla stock for the next quarter",
)
# Process responses
print("\nResponses from all agents:")
for i, response in enumerate(responses):
if response:
print(f"\n{agents[i].agent_name} Response:")
print("-" * 40)
print(
response[:200] + "..."
if len(response) > 200
else response
)
else:
print(f"\n{agents[i].agent_name}: Failed to respond")
return responses
def example_3_message_handling():
"""Example 3: Message handling using receive_message and send_agent_message"""
print("\n" + "=" * 60)
print("Example 3: Message Handling")
print("=" * 60)
# Create an agent that can receive messages
support_agent = Agent(
agent_name="Support-Agent",
system_prompt="You provide helpful support and assistance. Always be professional and solution-oriented.",
max_loops=1,
verbose=False,
)
notification_agent = Agent(
agent_name="Notification-Agent",
system_prompt="You send notifications and updates to other systems and agents.",
max_loops=1,
verbose=False,
)
# Example of receiving a message
print("Support agent receiving message...")
received_response = support_agent.receive_message(
agent_name="Customer-Service-Agent",
task="A customer is asking about our refund policies for software purchases. Can you provide guidance?",
)
print(f"\nSupport Agent Response:\n{received_response}")
# Example of sending a message
print("\nNotification agent sending message...")
sent_result = notification_agent.send_agent_message(
agent_name="Task-Manager-Agent",
message="Customer support ticket #12345 has been resolved successfully",
)
print(f"\nNotification Result:\n{sent_result}")
return received_response, sent_result
def example_4_sequential_workflow():
"""Example 4: Sequential agent workflow using communication methods"""
print("\n" + "=" * 60)
print("Example 4: Sequential Agent Workflow")
print("=" * 60)
# Create specialized agents for a document processing workflow
extractor = Agent(
agent_name="Data-Extractor",
system_prompt="You extract key information and data points from documents. Focus on accuracy and completeness.",
max_loops=1,
verbose=False,
)
validator = Agent(
agent_name="Data-Validator",
system_prompt="You validate and verify extracted data for accuracy, completeness, and consistency.",
max_loops=1,
verbose=False,
)
formatter = Agent(
agent_name="Data-Formatter",
system_prompt="You format validated data into structured, professional reports and summaries.",
max_loops=1,
verbose=False,
)
# Sequential processing workflow
document_content = """
Q3 Financial Report Summary:
- Revenue: $2.5M (up 15% from Q2)
- Expenses: $1.8M (operational costs increased by 8%)
- Net Profit: $700K (improved profit margin of 28%)
- New Customers: 1,200 (25% growth rate)
- Customer Retention: 92%
- Market Share: Increased to 12% in our sector
"""
print("Starting sequential workflow...")
# Step 1: Extract data
print("\nStep 1: Data Extraction")
extracted_data = extractor.run(
f"Extract key financial metrics from this report: {document_content}"
)
print(f"Extracted: {extracted_data[:150]}...")
# Step 2: Validate data
print("\nStep 2: Data Validation")
validated_data = extractor.talk_to(
agent=validator,
task=f"Please validate this extracted data for accuracy and completeness: {extracted_data}",
)
print(f"Validated: {validated_data[:150]}...")
# Step 3: Format data
print("\nStep 3: Data Formatting")
final_output = validator.talk_to(
agent=formatter,
task=f"Format this validated data into a structured executive summary: {validated_data}",
)
print(f"\nFinal Report:\n{final_output}")
return final_output
def example_5_error_handling():
"""Example 5: Robust communication with error handling"""
print("\n" + "=" * 60)
print("Example 5: Communication with Error Handling")
print("=" * 60)
def safe_agent_communication(sender, receiver, message):
"""Safely handle agent communication with comprehensive error handling"""
try:
print(
f"Attempting communication: {sender.agent_name} -> {receiver.agent_name}"
)
response = sender.talk_to(agent=receiver, task=message)
return {
"success": True,
"response": response,
"error": None,
}
except Exception as e:
print(f"Communication failed: {e}")
return {
"success": False,
"response": None,
"error": str(e),
}
# Create agents
agent_a = Agent(
agent_name="Agent-A",
system_prompt="You are a helpful assistant focused on providing accurate information.",
max_loops=1,
verbose=False,
)
agent_b = Agent(
agent_name="Agent-B",
system_prompt="You are a knowledgeable expert in technology and business trends.",
max_loops=1,
verbose=False,
)
# Safe communication
result = safe_agent_communication(
sender=agent_a,
receiver=agent_b,
message="What are the latest trends in artificial intelligence and how might they impact business operations?",
)
if result["success"]:
print("\nCommunication successful!")
print(f"Response: {result['response'][:200]}...")
else:
print(f"\nCommunication failed: {result['error']}")
return result
def main():
"""Run all multi-agent communication examples"""
print("🤖 Agent Multi-Agent Communication Examples")
print(
"This demonstrates the communication methods available in the Agent class"
)
try:
# Run all examples
example_1_direct_agent_communication()
example_2_multiple_agent_communication()
example_3_message_handling()
example_4_sequential_workflow()
example_5_error_handling()
print("\n" + "=" * 60)
print("✅ All examples completed successfully!")
print("=" * 60)
except Exception as e:
print(f"\n❌ Error running examples: {e}")
print(
"Make sure to set your OPENAI_API_KEY environment variable"
)
if __name__ == "__main__":
main()

@ -1,16 +0,0 @@
from swarms.structs.heavy_swarm import HeavySwarm
swarm = HeavySwarm(
worker_model_name="claude-3-5-sonnet-20240620",
show_dashboard=True,
question_agent_model_name="gpt-4.1",
loops_per_agent=1,
)
out = swarm.run(
"Identify the top 3 energy sector ETFs listed on US exchanges that offer the highest potential for growth over the next 3-5 years. Focus specifically on funds with significant exposure to companies in the nuclear, natural gas, or oil industries. For each ETF, provide the rationale for its selection, recent performance metrics, sector allocation breakdown, and any notable holdings related to nuclear, gas, or oil. Exclude broad-based energy ETFs that do not have a clear emphasis on these sub-sectors."
)
print(out)

@ -0,0 +1,16 @@
from swarms.structs.heavy_swarm import HeavySwarm
swarm = HeavySwarm(
worker_model_name="claude-3-5-sonnet-20240620",
show_dashboard=True,
question_agent_model_name="gpt-4.1",
loops_per_agent=1,
)
out = swarm.run(
"Provide 3 publicly traded biotech companies that are currently trading below their cash value. For each company identified, provide available data or projections for the next 6 months, including any relevant financial metrics, upcoming catalysts, or events that could impact valuation. Present your findings in a clear, structured format. Be very specific and provide their ticker symbol, name, and the current price, cash value, and the percentage difference between the two."
)
print(out)

@ -259,7 +259,7 @@ class AgentJudge:
# 在任务说明中添加评估标准 # 在任务说明中添加评估标准
if self.evaluation_criteria: if self.evaluation_criteria:
criteria_names = list(self.evaluation_criteria.keys()) list(self.evaluation_criteria.keys())
task_instruction += "\nPlease use these specific evaluation criteria with their respective weights:\n" task_instruction += "\nPlease use these specific evaluation criteria with their respective weights:\n"
for ( for (
criterion, criterion,

@ -1,6 +1,3 @@
from swarms.prompts.prompt import Prompt
OPENAI_PROMPT_GENERATOR_SYS_PROMPT = """ OPENAI_PROMPT_GENERATOR_SYS_PROMPT = """
Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively. Given a task description or existing prompt, produce a detailed system prompt to guide a language model in completing the task effectively.
@ -51,9 +48,5 @@ The final prompt you output should adhere to the following structure below. Do n
""" """
prompt_generator_sys_prompt = Prompt(
name="openai-prompt-generator-optimizer-prompt", prompt_generator_sys_prompt = OPENAI_PROMPT_GENERATOR_SYS_PROMPT
description="Generate and or optimize existing prompts",
content=OPENAI_PROMPT_GENERATOR_SYS_PROMPT,
autosave=True,
)

@ -1261,12 +1261,6 @@ class Agent:
self, self,
task: Optional[str] = None, task: Optional[str] = None,
img: Optional[str] = None, img: Optional[str] = None,
is_last: bool = False,
device: str = "cpu", # gpu
device_id: int = 1,
all_cores: bool = True,
do_not_use_cluster_ops: bool = True,
all_gpus: bool = False,
*args, *args,
**kwargs, **kwargs,
) -> Any: ) -> Any:
@ -1337,37 +1331,6 @@ class Agent:
) )
return self.run(task=improved_prompt, *args, **kwargs) return self.run(task=improved_prompt, *args, **kwargs)
# def parse_and_execute_tools(self, response: str, *args, **kwargs):
# max_retries = 3 # Maximum number of retries
# retries = 0
# while retries < max_retries:
# try:
# logger.info("Executing tool...")
# # try to Execute the tool and return a string
# out = parse_and_execute_json(
# functions=self.tools,
# json_string=response,
# parse_md=True,
# *args,
# **kwargs,
# )
# logger.info(f"Tool Output: {out}")
# # Add the output to the memory
# # self.short_memory.add(
# # role="Tool Executor",
# # content=out,
# # )
# return out
# except Exception as error:
# retries += 1
# logger.error(
# f"Attempt {retries}: Error executing tool: {error}"
# )
# if retries == max_retries:
# raise error
# time.sleep(1) # Wait for a bit before retrying
def add_memory(self, message: str): def add_memory(self, message: str):
"""Add a memory to the agent """Add a memory to the agent
@ -3241,7 +3204,7 @@ class Agent:
f"Agent '{self.agent_name}' received None response from LLM in loop {loop_count}. " f"Agent '{self.agent_name}' received None response from LLM in loop {loop_count}. "
f"This may indicate an issue with the model or prompt. Skipping tool execution." f"This may indicate an issue with the model or prompt. Skipping tool execution."
) )
except Exception as e: except AgentToolExecutionError as e:
logger.error( logger.error(
f"Agent '{self.agent_name}' encountered error during tool execution in loop {loop_count}: {str(e)}. " f"Agent '{self.agent_name}' encountered error during tool execution in loop {loop_count}: {str(e)}. "
f"Full traceback: {traceback.format_exc()}. " f"Full traceback: {traceback.format_exc()}. "

Loading…
Cancel
Save