[FEAT][InteractiveGroupChat] + [Swarms Examples][index.md]

pull/870/head
Kye Gomez 3 weeks ago
parent a5567d1323
commit 0e0a46019d

1
.gitignore vendored

@ -14,6 +14,7 @@ Cargo.lock
.pytest_cache .pytest_cache
static/generated static/generated
conversations/ conversations/
next_swarms_update.txt
runs runs
Financial-Analysis-Agent_state.json Financial-Analysis-Agent_state.json
conversations/ conversations/

@ -0,0 +1,108 @@
# Swarms Examples Index
A comprehensive index of examples from the [Swarms Examples Repository](https://github.com/The-Swarm-Corporation/swarms-examples).
Additionally, we have more comprehensive examples available in [The Swarms Cookbook](https://github.com/The-Swarm-Corporation/Cookbook).
## Single Agent Examples
### Core Agents
| Category | Example | Description |
|----------|---------|-------------|
| Basic | [Easy Example](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/easy_example.py) | Basic agent implementation demonstrating core functionality and setup |
| Settings | [Agent Settings](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/agent_settings.py) | Comprehensive configuration options for customizing agent behavior and capabilities |
| YAML | [Agents from YAML](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/agents_from_yaml_example.py) | Creating and configuring agents using YAML configuration files for easy deployment |
| Memory | [Agent with Long-term Memory](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/memory/agents_and_memory/agent_with_longterm_memory.py) | Implementation of persistent memory capabilities for maintaining context across sessions |
### Model Integrations
| Category | Example | Description |
|----------|---------|-------------|
| Azure | [Azure OpenAI Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/settings/various_models/basic_agent_with_azure_openai.py) | Integration with Azure OpenAI services for enterprise-grade AI capabilities |
| Groq | [Groq Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/settings/various_models/groq_agent.py) | High-performance inference using Groq's accelerated computing platform |
| Custom | [Custom Model Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/settings/various_models/custom_model_with_agent.py) | Framework for integrating custom ML models into the agent architecture |
### Tools and Function Calling
| Category | Example | Description |
|----------|---------|-------------|
| Basic Tools | [Tool Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/tools/tool_agent.py) | Basic tool-using agent demonstrating external tool integration capabilities |
| Advanced Tools | [Agent with Many Tools](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/tools/agent_with_many_tools.py) | Advanced agent utilizing multiple tools for complex task execution |
| OpenAI Functions | [OpenAI Function Caller](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/tools/function_calling/openai_function_caller_example.py) | Integration with OpenAI's function calling API for structured outputs |
| Command Line | [Command Tool Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/tools/tool_agent/command_r_tool_agent.py) | Command-line interface tool integration |
| Jamba | [Jamba Tool Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/tools/tool_agent/jamba_tool_agent.py) | Integration with Jamba framework for enhanced tool capabilities |
| Pydantic | [Pydantic Tool Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/tools/tool_agent/tool_agent_pydantic.py) | Tool validation and schema enforcement using Pydantic |
### Third-Party Integrations
| Category | Example | Description |
|----------|---------|-------------|
| Microsoft | [AutoGen Integration](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/3rd_party_agents/auto_gen.py) | Integration with Microsoft's AutoGen framework for autonomous agents |
| LangChain | [LangChain Integration](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/3rd_party_agents/langchain.py) | Combining LangChain's capabilities with Swarms for enhanced functionality |
| Browser | [Multion Integration](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/3rd_party_agents/multion_agent.py) | Web automation and browsing capabilities using Multion |
| Team AI | [Crew AI](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/3rd_party_agents/crew_ai.py) | Team-based AI collaboration using Crew AI framework |
| Development | [Griptape](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/3rd_party_agents/griptape.py) | Integration with Griptape for structured AI application development |
### Industry-Specific Agents
| Category | Example | Description |
|----------|---------|-------------|
| Finance | [401k Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/use_cases/finance/401k_agent.py) | Retirement planning assistant with investment strategy recommendations |
| Finance | [Estate Planning](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/use_cases/finance/estate_planning_agent.py) | Comprehensive estate planning and wealth management assistant |
| Security | [Perimeter Defense](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/use_cases/security/perimeter_defense_agent.py) | Security monitoring and threat detection system |
| Research | [Perplexity Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/use_cases/research/perplexity_agent.py) | Advanced research automation using Perplexity AI integration |
| Legal | [Alberto Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/use_cases/law/alberto_agent.py) | Legal research and document analysis assistant |
| Healthcare | [Pharma Agent](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/agents/use_cases/pharma/pharma_agent_two.py) | Pharmaceutical research and drug interaction analysis |
## Multi-Agent Examples
### Core Architectures
| Category | Example | Description |
|----------|---------|-------------|
| Basic | [Build a Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/base_swarm/build_a_swarm.py) | Foundation for creating custom swarm architectures with multiple agents |
| Auto Swarm | [Auto Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/auto_swarm/auto_swarm_example.py) | Self-organizing swarm with automatic task distribution and management |
| Concurrent | [Concurrent Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/concurrent_swarm/concurrent_swarm_example.py) | Parallel execution of tasks across multiple agents for improved performance |
| Star | [Star Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/different_architectures/star_swarm.py) | Centralized architecture with a hub agent coordinating peripheral agents |
| Circular | [Circular Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/different_architectures/circular_swarm.py) | Ring topology for cyclic information flow between agents |
### Experimental Architectures
| Category | Example | Description |
|----------|---------|-------------|
| Monte Carlo | [Monte Carlo Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/experimental/monte_carlo_swarm.py) | Probabilistic decision-making using Monte Carlo simulation across agents |
| Federated | [Federated Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/experimental/federated_swarm.py) | Distributed learning system with privacy-preserving agent collaboration |
| Ant Colony | [Ant Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/experimental/ant_swarm.py) | Bio-inspired optimization using ant colony algorithms for agent coordination |
| Matrix | [Agent Matrix](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/experimental/agent_matrix.py) | Grid-based agent organization for complex problem-solving |
| DFS | [DFS Search Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/experimental/dfs_search_swarm.py) | Depth-first search swarm for complex problem exploration |
| Pulsar | [Pulsar Swarm](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/experimental/pulsar_swarm.py) | Pulsar-based coordination for synchronized agent behavior |
### Collaboration Patterns
| Category | Example | Description |
|----------|---------|-------------|
| Delegation | [Agent Delegation](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/multi_agent_collaboration/agent_delegation.py) | Task delegation and management system |
| Communication | [Message Pool](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/multi_agent_collaboration/message_pool.py) | Shared communication system for efficient agent interaction |
| Scheduling | [Round Robin](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/multi_agent_collaboration/round_robin_example.py) | Round-robin task scheduling and execution |
| Load Balancing | [Load Balancer](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/multi_agent_collaboration/load_balancer_example.py) | Dynamic task distribution system for optimal resource utilization |
| Consensus | [Majority Voting](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/structs/swarms/multi_agent_collaboration/majority_voting.py) | Consensus-building system using democratic voting among agents |
### Industry Applications
| Category | Example | Description |
|----------|---------|-------------|
| Finance | [Accountant Team](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/accountant_team/account_team2_example.py) | Multi-agent system for financial analysis, bookkeeping, and tax planning |
| Marketing | [Ad Generation](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/ad_gen/ad_gen_example.py) | Collaborative ad creation with copywriting and design agents |
| Aerospace | [Space Traffic Control](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/agentic_space_traffic_control/game.py) | Complex simulation of space traffic management with multiple coordinating agents |
| Agriculture | [Plant Biology](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/plant_biologist_swarm/agricultural_swarm.py) | Agricultural analysis and optimization using specialized biology agents |
| Urban Dev | [Urban Planning](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/urban_planning/urban_planning_example.py) | City development planning with multiple specialized urban development agents |
| Education | [Education System](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/education/education_example.py) | Personalized learning system with multiple teaching and assessment agents |
| Security | [Email Phishing Detection](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/email_phiser/email_swarm.py) | Multi-agent security analysis and threat detection |
| Fashion | [Personal Stylist](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/personal_stylist/personal_stylist_example.py) | Fashion recommendation system with style analysis and matching agents |
| Healthcare | [Healthcare Assistant](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/positive_med/positive_med_example.py) | Medical diagnosis and treatment planning with specialist consultation agents |
| Security Ops | [Security Team](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/security_team/security_team_example.py) | Comprehensive security operations with threat detection and response agents |
| Medical | [X-Ray Analysis](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/demos/xray/xray_example.py) | Multi-agent medical imaging analysis and diagnosis |
| Business | [Business Strategy](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/business_strategy/business_strategy_graph/growth_agent.py) | Strategic planning and business development swarm |
| Research | [Astronomy Research](https://github.com/The-Swarm-Corporation/swarms-examples/blob/main/examples/applications/astronomy/multiversal_detection/test.py) | Collaborative space research and astronomical analysis |
## Additional Resources
- [Github](https://github.com/kyegomez/swarms)
- Discord (https://t.co/zlLe07AqUX)
- Telegram (https://t.co/dSRy143zQv)
- X Community (https://x.com/i/communities/1875452887414804745)

@ -242,6 +242,7 @@ nav:
- MatrixSwarm: "swarms/structs/matrix_swarm.md" - MatrixSwarm: "swarms/structs/matrix_swarm.md"
- ModelRouter: "swarms/structs/model_router.md" - ModelRouter: "swarms/structs/model_router.md"
- MALT: "swarms/structs/malt.md" - MALT: "swarms/structs/malt.md"
- Interactive Group Chat: "swarms/structs/interactive_groupchat.md"
- Various Execution Methods: "swarms/structs/various_execution_methods.md" - Various Execution Methods: "swarms/structs/various_execution_methods.md"
- Deep Research Swarm: "swarms/structs/deep_research_swarm.md" - Deep Research Swarm: "swarms/structs/deep_research_swarm.md"
- Swarm Matcher: "swarms/structs/swarm_matcher.md" - Swarm Matcher: "swarms/structs/swarm_matcher.md"
@ -305,6 +306,7 @@ nav:
- Swarms 5.9.2: "swarms/changelog/changelog_new.md" - Swarms 5.9.2: "swarms/changelog/changelog_new.md"
- Examples: - Examples:
- Overview: "examples/index.md"
- Customizing Agents: - Customizing Agents:
- Basic Agent: "swarms/examples/basic_agent.md" - Basic Agent: "swarms/examples/basic_agent.md"
- Agents with Callable Tools: "swarms/examples/agent_with_tools.md" - Agents with Callable Tools: "swarms/examples/agent_with_tools.md"

@ -1,11 +1,11 @@
# InteractiveGroupChat Documentation # InteractiveGroupChat Documentation
The InteractiveGroupChat is a sophisticated multi-agent system that enables interactive conversations between users and AI agents using @mentions. This system allows users to direct messages to specific agents and facilitates collaborative responses when multiple agents are mentioned. The InteractiveGroupChat is a sophisticated multi-agent system that enables interactive conversations between users and AI agents using @mentions. This system allows users to direct tasks to specific agents and facilitates collaborative responses when multiple agents are mentioned.
## Features ## Features
- **@mentions Support**: Direct messages to specific agents using @agent_name syntax - **@mentions Support**: Direct tasks to specific agents using @agent_name syntax
- **Multi-Agent Collaboration**: Multiple mentioned agents can see and respond to each other's messages - **Multi-Agent Collaboration**: Multiple mentioned agents can see and respond to each other's tasks
- **Callable Function Support**: Supports both Agent instances and callable functions as chat participants - **Callable Function Support**: Supports both Agent instances and callable functions as chat participants
- **Comprehensive Error Handling**: Custom error classes for different scenarios - **Comprehensive Error Handling**: Custom error classes for different scenarios
- **Conversation History**: Maintains a complete history of the conversation - **Conversation History**: Maintains a complete history of the conversation
@ -17,186 +17,248 @@ The InteractiveGroupChat is a sophisticated multi-agent system that enables inte
pip install swarms pip install swarms
``` ```
## Basic Usage ## Methods Reference
### Constructor (`__init__`)
**Description:**
Initializes a new InteractiveGroupChat instance with the specified configuration.
**Arguments:**
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `id` | str | Unique identifier for the chat | auto-generated key |
| `name` | str | Name of the group chat | "InteractiveGroupChat" |
| `description` | str | Description of the chat's purpose | generic description |
| `agents` | List[Union[Agent, Callable]] | List of participating agents | empty list |
| `max_loops` | int | Maximum conversation turns | 1 |
| `output_type` | str | Type of output format | "string" |
| `interactive` | bool | Whether to enable interactive mode | False |
**Example:**
```python ```python
from swarms import Agent, InteractiveGroupChat from swarms import Agent, InteractiveGroupChat
# Initialize agents # Create agents
financial_advisor = Agent( financial_advisor = Agent(
agent_name="FinancialAdvisor", agent_name="FinancialAdvisor",
system_prompt="You are a financial advisor specializing in investment strategies.", system_prompt="You are a financial advisor specializing in investment strategies.",
model_name="gpt-4o-mini" model_name="gpt-4"
) )
tax_expert = Agent( tax_expert = Agent(
agent_name="TaxExpert", agent_name="TaxExpert",
system_prompt="You are a tax expert providing tax-related guidance.", system_prompt="You are a tax expert providing tax-related guidance.",
model_name="gpt-4o-mini" model_name="gpt-4"
) )
# Create the interactive group chat # Initialize group chat
chat = InteractiveGroupChat( chat = InteractiveGroupChat(
name="Financial Team", id="finance-chat-001",
description="Financial advisory team", name="Financial Advisory Team",
agents=[financial_advisor, tax_expert] description="Expert financial guidance team",
agents=[financial_advisor, tax_expert],
max_loops=3,
output_type="string",
interactive=True
) )
```
# Send a message to a single agent ### Run Method (`run`)
response = chat.run("@FinancialAdvisor what are good investment strategies?")
# Send a message to multiple agents **Description:**
response = chat.run("@FinancialAdvisor and @TaxExpert, how can I optimize my investment taxes?") Processes a task and gets responses from mentioned agents. This is the main method for sending tasks in non-interactive mode.
```
**Arguments:**
## Advanced Usage - `task` (str): The input task containing @mentions to agents
### Using Callable Functions **Returns:**
- str: Formatted conversation history including agent responses
**Example:**
```python ```python
def custom_agent(context: str) -> str: # Single agent interaction
"""A custom callable function that can act as an agent""" response = chat.run("@FinancialAdvisor what are the best ETFs for 2024?")
return "Custom response based on: " + context print(response)
# Add both Agent instances and callable functions # Multiple agent collaboration
agents = [financial_advisor, tax_expert, custom_agent] response = chat.run("@FinancialAdvisor and @TaxExpert, how can I minimize taxes on my investments?")
chat = InteractiveGroupChat(agents=agents) print(response)
```
### Start Interactive Session (`start_interactive_session`)
**Description:**
Starts an interactive terminal session for real-time chat with agents. This creates a REPL (Read-Eval-Print Loop) interface.
**Arguments:**
None
# Interact with the callable function **Example:**
response = chat.run("@custom_agent what do you think?")
```python
# Initialize chat with interactive mode
chat = InteractiveGroupChat(
agents=[financial_advisor, tax_expert],
interactive=True
)
# Start the interactive session
chat.start_interactive_session()
``` ```
## Configuration Options ### Extract Mentions (`_extract_mentions`)
**Description:**
| Parameter | Type | Default | Description | Internal method that extracts @mentions from a task. Used by the run method to identify which agents should respond.
|-----------|------|---------|-------------|
| name | str | "InteractiveGroupChat" | Name of the group chat |
| description | str | "An interactive group chat..." | Description of the chat's purpose |
| agents | List[Union[Agent, Callable]] | [] | List of agents or callable functions |
| max_loops | int | 1 | Maximum conversation turns |
| output_type | str | "string" | Output format type |
## Error Handling **Arguments:**
The system includes several custom error classes: - `task` (str): The input task to extract mentions from
- **InteractiveGroupChatError**: Base exception class **Returns:**
- **AgentNotFoundError**: Raised when a mentioned agent doesn't exist
- **NoMentionedAgentsError**: Raised when no agents are mentioned
- **InvalidMessageFormatError**: Raised for invalid message formats
Example error handling: - List[str]: List of mentioned agent names
**Example:**
```python ```python
try: # Internal usage example (not typically called directly)
response = chat.run("@NonExistentAgent hello!") chat = InteractiveGroupChat(agents=[financial_advisor, tax_expert])
except AgentNotFoundError as e: mentions = chat._extract_mentions("@FinancialAdvisor and @TaxExpert, please help")
print(f"Agent not found: {e}") print(mentions) # ['FinancialAdvisor', 'TaxExpert']
except NoMentionedAgentsError as e:
print(f"No agents mentioned: {e}")
``` ```
## Best Practices ### Validate Initialization (`_validate_initialization`)
**Description:**
1. **Agent Naming**: Use clear, unique names for agents to avoid confusion Internal method that validates the group chat configuration during initialization.
2. **Message Format**: Always use @mentions to direct messages to specific agents
3. **Error Handling**: Implement proper error handling for various scenarios
4. **Context Management**: Be aware that agents can see the full conversation history
5. **Resource Management**: Consider the number of agents and message length to optimize performance
## Logging **Arguments:**
None
The system uses loguru for comprehensive logging: **Example:**
```python ```python
from loguru import logger # Internal validation happens automatically during initialization
chat = InteractiveGroupChat(
agents=[financial_advisor], # Valid: at least one agent
max_loops=5 # Valid: positive number
)
```
# Configure logging ### Setup Conversation Context (`_setup_conversation_context`)
logger.add("groupchat.log", rotation="500 MB")
# Logs will include: **Description:**
# - Agent responses
# - Error messages
# - System events
```
## Examples Internal method that sets up the initial conversation context with group chat information.
### Basic Interaction **Arguments:**
```python None
# Single agent interaction
response = chat.run("@FinancialAdvisor what are the best investment strategies for 2024?")
# Multiple agent collaboration **Example:**
response = chat.run("@TaxExpert and @InvestmentAnalyst, how can we optimize investment taxes?")
```python
# Context is automatically set up during initialization
chat = InteractiveGroupChat(
name="Investment Team",
description="Expert investment advice",
agents=[financial_advisor, tax_expert]
)
# The conversation context now includes chat name, description, and agent info
``` ```
### Error Handling ### Update Agent Prompts (`_update_agent_prompts`)
```python **Description:**
try:
# Invalid agent mention
response = chat.run("@NonExistentAgent hello!")
except AgentNotFoundError as e:
print(f"Error: {e}")
try: Internal method that updates each agent's system prompt with information about other agents and the group chat.
# No mentions
response = chat.run("Hello everyone!") **Arguments:**
except NoMentionedAgentsError as e:
print(f"Error: {e}")
```
### Custom Callable Integration None
**Example:**
```python ```python
def market_analyzer(context: str) -> str: # Agent prompts are automatically updated during initialization
"""Custom market analysis function""" chat = InteractiveGroupChat(agents=[financial_advisor, tax_expert])
return "Market analysis based on: " + context # Each agent now knows about the other participants in the chat
```
## Error Classes
agents = [financial_advisor, tax_expert, market_analyzer] ### InteractiveGroupChatError
chat = InteractiveGroupChat(agents=agents)
response = chat.run("@market_analyzer what's your analysis of the current market?") **Description:**
Base exception class for InteractiveGroupChat errors.
**Example:**
```python
try:
# Some operation that might fail
chat.run("@InvalidAgent hello")
except InteractiveGroupChatError as e:
print(f"Chat error occurred: {e}")
``` ```
## API Reference ### AgentNotFoundError
### InteractiveGroupChat Class **Description:**
Raised when a mentioned agent is not found in the group.
**Example:**
```python ```python
class InteractiveGroupChat: try:
def __init__( chat.run("@NonExistentAgent hello!")
self, except AgentNotFoundError as e:
name: str = "InteractiveGroupChat", print(f"Agent not found: {e}")
description: str = "An interactive group chat for multiple agents",
agents: List[Union[Agent, Callable]] = [],
max_loops: int = 1,
output_type: str = "string",
):
"""Initialize the interactive group chat."""
def run(self, message: str) -> str:
"""Process a message and get responses from mentioned agents."""
``` ```
### Custom Error Classes ### NoMentionedAgentsError
**Description:**
Raised when no agents are mentioned in the task.
**Example:**
```python ```python
class InteractiveGroupChatError(Exception): try:
"""Base exception class for InteractiveGroupChat errors""" chat.run("Hello everyone!") # No @mentions
except NoMentionedAgentsError as e:
print(f"No agents mentioned: {e}")
```
class AgentNotFoundError(InteractiveGroupChatError): ### InvalidtaskFormatError
"""Raised when a mentioned agent is not found"""
class NoMentionedAgentsError(InteractiveGroupChatError): **Description:**
"""Raised when no agents are mentioned"""
class InvalidMessageFormatError(InteractiveGroupChatError): Raised when the task format is invalid.
"""Raised when the message format is invalid"""
**Example:**
```python
try:
chat.run("@Invalid@Format")
except InvalidtaskFormatError as e:
print(f"Invalid task format: {e}")
``` ```
## Best Practices
| Best Practice | Description | Example |
|--------------|-------------|---------|
| Agent Naming | Use clear, unique names for agents to avoid confusion | `financial_advisor`, `tax_expert` |
| task Format | Always use @mentions to direct tasks to specific agents | `@financial_advisor What's your investment advice?` |
| Error Handling | Implement proper error handling for various scenarios | `try/except` blocks for `AgentNotFoundError` |
| Context Management | Be aware that agents can see the full conversation history | Monitor conversation length and relevance |
| Resource Management | Consider the number of agents and task length to optimize performance | Limit max_loops and task size |
## Contributing ## Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository. Contributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository.

@ -84,6 +84,7 @@ from swarms.structs.swarming_architectures import (
staircase_swarm, staircase_swarm,
star_swarm, star_swarm,
) )
from swarms.structs.interactive_groupchat import InteractiveGroupChat
__all__ = [ __all__ = [
"Agent", "Agent",
@ -156,4 +157,5 @@ __all__ = [
"aggregate", "aggregate",
"find_agent_by_name", "find_agent_by_name",
"run_agent", "run_agent",
"InteractiveGroupChat",
] ]

@ -1,12 +1,14 @@
from typing import List, Union, Callable
import re import re
from typing import Callable, List, Union
from loguru import logger from loguru import logger
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.conversation import Conversation from swarms.structs.conversation import Conversation
from swarms.utils.generate_keys import generate_api_key
from swarms.utils.history_output_formatter import ( from swarms.utils.history_output_formatter import (
history_output_formatter, history_output_formatter,
) )
from swarms.utils.generate_keys import generate_api_key
class InteractiveGroupChatError(Exception): class InteractiveGroupChatError(Exception):
@ -22,13 +24,13 @@ class AgentNotFoundError(InteractiveGroupChatError):
class NoMentionedAgentsError(InteractiveGroupChatError): class NoMentionedAgentsError(InteractiveGroupChatError):
"""Raised when no agents are mentioned in the message""" """Raised when no agents are mentioned in the task"""
pass pass
class InvalidMessageFormatError(InteractiveGroupChatError): class InvalidTaskFormatError(InteractiveGroupChatError):
"""Raised when the message format is invalid""" """Raised when the task format is invalid"""
pass pass
@ -38,7 +40,7 @@ class InteractiveGroupChat:
An interactive group chat system that enables conversations with multiple agents using @mentions. An interactive group chat system that enables conversations with multiple agents using @mentions.
This class allows users to interact with multiple agents by mentioning them using @agent_name syntax. This class allows users to interact with multiple agents by mentioning them using @agent_name syntax.
When multiple agents are mentioned, they can see and respond to each other's messages. When multiple agents are mentioned, they can see and respond to each other's tasks.
Attributes: Attributes:
name (str): Name of the group chat name (str): Name of the group chat
@ -175,22 +177,22 @@ class InteractiveGroupChat:
f"Updated system prompt for agent: {agent.agent_name}" f"Updated system prompt for agent: {agent.agent_name}"
) )
def _extract_mentions(self, message: str) -> List[str]: def _extract_mentions(self, task: str) -> List[str]:
""" """
Extracts @mentions from the message. Extracts @mentions from the task.
Args: Args:
message (str): The input message task (str): The input task
Returns: Returns:
List[str]: List of mentioned agent names List[str]: List of mentioned agent names
Raises: Raises:
InvalidMessageFormatError: If the message format is invalid InvalidtaskFormatError: If the task format is invalid
""" """
try: try:
# Find all @mentions using regex # Find all @mentions using regex
mentions = re.findall(r"@(\w+)", message) mentions = re.findall(r"@(\w+)", task)
return [ return [
mention mention
for mention in mentions for mention in mentions
@ -198,9 +200,7 @@ class InteractiveGroupChat:
] ]
except Exception as e: except Exception as e:
logger.error(f"Error extracting mentions: {e}") logger.error(f"Error extracting mentions: {e}")
raise InvalidMessageFormatError( raise InvalidTaskFormatError(f"Invalid task format: {e}")
f"Invalid message format: {e}"
)
def start_interactive_session(self): def start_interactive_session(self):
""" """
@ -248,7 +248,7 @@ class InteractiveGroupChat:
print("\nHelp:") print("\nHelp:")
print("1. Mention agents using @agent_name") print("1. Mention agents using @agent_name")
print( print(
"2. You can mention multiple agents in one message" "2. You can mention multiple agents in one task"
) )
print("3. Available agents:") print("3. Available agents:")
for name in self.agent_map: for name in self.agent_map:
@ -261,7 +261,7 @@ class InteractiveGroupChat:
if not user_input: if not user_input:
continue continue
# Process the message and get responses # Process the task and get responses
try: try:
response = self.run(user_input) response = self.run(user_input)
print("\nChat:") print("\nChat:")
@ -285,23 +285,23 @@ class InteractiveGroupChat:
"The session will continue. You can type 'exit' to end it." "The session will continue. You can type 'exit' to end it."
) )
def run(self, message: str) -> str: def run(self, task: str) -> str:
""" """
Process a message and get responses from mentioned agents. Process a task and get responses from mentioned agents.
If interactive mode is enabled, this will be called by start_interactive_session(). If interactive mode is enabled, this will be called by start_interactive_session().
Otherwise, it can be called directly for single message processing. Otherwise, it can be called directly for single task processing.
""" """
try: try:
# Extract mentioned agents # Extract mentioned agents
mentioned_agents = self._extract_mentions(message) mentioned_agents = self._extract_mentions(task)
if not mentioned_agents: if not mentioned_agents:
raise NoMentionedAgentsError( raise NoMentionedAgentsError(
"No valid agents mentioned in the message" "No valid agents mentioned in the task"
) )
# Add user message to conversation # Add user task to conversation
self.conversation.add(role="User", content=message) self.conversation.add(role="User", content=task)
# Get responses from mentioned agents # Get responses from mentioned agents
for agent_name in mentioned_agents: for agent_name in mentioned_agents:
@ -320,7 +320,7 @@ class InteractiveGroupChat:
# Get response from agent # Get response from agent
if isinstance(agent, Agent): if isinstance(agent, Agent):
response = agent.run( response = agent.run(
task=f"{context}\nPlease respond to the latest message as {agent_name}." task=f"{context}\nPlease respond to the latest task as {agent_name}."
) )
else: else:
# For callable functions # For callable functions

Loading…
Cancel
Save