[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
static/generated
conversations/
next_swarms_update.txt
runs
Financial-Analysis-Agent_state.json
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"
- ModelRouter: "swarms/structs/model_router.md"
- MALT: "swarms/structs/malt.md"
- Interactive Group Chat: "swarms/structs/interactive_groupchat.md"
- Various Execution Methods: "swarms/structs/various_execution_methods.md"
- Deep Research Swarm: "swarms/structs/deep_research_swarm.md"
- Swarm Matcher: "swarms/structs/swarm_matcher.md"
@ -305,6 +306,7 @@ nav:
- Swarms 5.9.2: "swarms/changelog/changelog_new.md"
- Examples:
- Overview: "examples/index.md"
- Customizing Agents:
- Basic Agent: "swarms/examples/basic_agent.md"
- Agents with Callable Tools: "swarms/examples/agent_with_tools.md"

@ -1,11 +1,11 @@
# 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
- **@mentions Support**: Direct messages to specific agents using @agent_name syntax
- **Multi-Agent Collaboration**: Multiple mentioned agents can see and respond to each other's messages
- **@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 tasks
- **Callable Function Support**: Supports both Agent instances and callable functions as chat participants
- **Comprehensive Error Handling**: Custom error classes for different scenarios
- **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
```
## 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
from swarms import Agent, InteractiveGroupChat
# Initialize agents
# Create agents
financial_advisor = Agent(
agent_name="FinancialAdvisor",
system_prompt="You are a financial advisor specializing in investment strategies.",
model_name="gpt-4o-mini"
model_name="gpt-4"
)
tax_expert = Agent(
agent_name="TaxExpert",
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(
name="Financial Team",
description="Financial advisory team",
agents=[financial_advisor, tax_expert]
id="finance-chat-001",
name="Financial Advisory Team",
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
response = chat.run("@FinancialAdvisor what are good investment strategies?")
### Run Method (`run`)
# Send a message to multiple agents
response = chat.run("@FinancialAdvisor and @TaxExpert, how can I optimize my investment taxes?")
```
**Description:**
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
def custom_agent(context: str) -> str:
"""A custom callable function that can act as an agent"""
return "Custom response based on: " + context
# Single agent interaction
response = chat.run("@FinancialAdvisor what are the best ETFs for 2024?")
print(response)
# Add both Agent instances and callable functions
agents = [financial_advisor, tax_expert, custom_agent]
chat = InteractiveGroupChat(agents=agents)
# Multiple agent collaboration
response = chat.run("@FinancialAdvisor and @TaxExpert, how can I minimize taxes on my investments?")
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
response = chat.run("@custom_agent what do you think?")
**Example:**
```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 |
|-----------|------|---------|-------------|
| 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 |
Internal method that extracts @mentions from a task. Used by the run method to identify which agents should respond.
## Error Handling
**Arguments:**
The system includes several custom error classes:
- `task` (str): The input task to extract mentions from
- **InteractiveGroupChatError**: Base exception class
- **AgentNotFoundError**: Raised when a mentioned agent doesn't exist
- **NoMentionedAgentsError**: Raised when no agents are mentioned
- **InvalidMessageFormatError**: Raised for invalid message formats
**Returns:**
Example error handling:
- List[str]: List of mentioned agent names
**Example:**
```python
try:
response = chat.run("@NonExistentAgent hello!")
except AgentNotFoundError as e:
print(f"Agent not found: {e}")
except NoMentionedAgentsError as e:
print(f"No agents mentioned: {e}")
# Internal usage example (not typically called directly)
chat = InteractiveGroupChat(agents=[financial_advisor, tax_expert])
mentions = chat._extract_mentions("@FinancialAdvisor and @TaxExpert, please help")
print(mentions) # ['FinancialAdvisor', 'TaxExpert']
```
## Best Practices
### Validate Initialization (`_validate_initialization`)
**Description:**
1. **Agent Naming**: Use clear, unique names for agents to avoid confusion
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
Internal method that validates the group chat configuration during initialization.
## Logging
**Arguments:**
None
The system uses loguru for comprehensive logging:
**Example:**
```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
logger.add("groupchat.log", rotation="500 MB")
### Setup Conversation Context (`_setup_conversation_context`)
# Logs will include:
# - Agent responses
# - Error messages
# - System events
```
**Description:**
## Examples
Internal method that sets up the initial conversation context with group chat information.
### Basic Interaction
**Arguments:**
```python
# Single agent interaction
response = chat.run("@FinancialAdvisor what are the best investment strategies for 2024?")
None
# Multiple agent collaboration
response = chat.run("@TaxExpert and @InvestmentAnalyst, how can we optimize investment taxes?")
**Example:**
```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
try:
# Invalid agent mention
response = chat.run("@NonExistentAgent hello!")
except AgentNotFoundError as e:
print(f"Error: {e}")
**Description:**
try:
# No mentions
response = chat.run("Hello everyone!")
except NoMentionedAgentsError as e:
print(f"Error: {e}")
```
Internal method that updates each agent's system prompt with information about other agents and the group chat.
**Arguments:**
### Custom Callable Integration
None
**Example:**
```python
def market_analyzer(context: str) -> str:
"""Custom market analysis function"""
return "Market analysis based on: " + context
# Agent prompts are automatically updated during initialization
chat = InteractiveGroupChat(agents=[financial_advisor, tax_expert])
# Each agent now knows about the other participants in the chat
```
## Error Classes
agents = [financial_advisor, tax_expert, market_analyzer]
chat = InteractiveGroupChat(agents=agents)
### InteractiveGroupChatError
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
class InteractiveGroupChat:
def __init__(
self,
name: str = "InteractiveGroupChat",
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."""
try:
chat.run("@NonExistentAgent hello!")
except AgentNotFoundError as e:
print(f"Agent not found: {e}")
```
### Custom Error Classes
### NoMentionedAgentsError
**Description:**
Raised when no agents are mentioned in the task.
**Example:**
```python
class InteractiveGroupChatError(Exception):
"""Base exception class for InteractiveGroupChat errors"""
try:
chat.run("Hello everyone!") # No @mentions
except NoMentionedAgentsError as e:
print(f"No agents mentioned: {e}")
```
class AgentNotFoundError(InteractiveGroupChatError):
"""Raised when a mentioned agent is not found"""
### InvalidtaskFormatError
class NoMentionedAgentsError(InteractiveGroupChatError):
"""Raised when no agents are mentioned"""
**Description:**
class InvalidMessageFormatError(InteractiveGroupChatError):
"""Raised when the message format is invalid"""
Raised when the task 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
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,
star_swarm,
)
from swarms.structs.interactive_groupchat import InteractiveGroupChat
__all__ = [
"Agent",
@ -156,4 +157,5 @@ __all__ = [
"aggregate",
"find_agent_by_name",
"run_agent",
"InteractiveGroupChat",
]

@ -1,12 +1,14 @@
from typing import List, Union, Callable
import re
from typing import Callable, List, Union
from loguru import logger
from swarms.structs.agent import Agent
from swarms.structs.conversation import Conversation
from swarms.utils.generate_keys import generate_api_key
from swarms.utils.history_output_formatter import (
history_output_formatter,
)
from swarms.utils.generate_keys import generate_api_key
class InteractiveGroupChatError(Exception):
@ -22,13 +24,13 @@ class AgentNotFoundError(InteractiveGroupChatError):
class NoMentionedAgentsError(InteractiveGroupChatError):
"""Raised when no agents are mentioned in the message"""
"""Raised when no agents are mentioned in the task"""
pass
class InvalidMessageFormatError(InteractiveGroupChatError):
"""Raised when the message format is invalid"""
class InvalidTaskFormatError(InteractiveGroupChatError):
"""Raised when the task format is invalid"""
pass
@ -38,7 +40,7 @@ class InteractiveGroupChat:
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.
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:
name (str): Name of the group chat
@ -70,7 +72,7 @@ class InteractiveGroupChat:
output_type: str = "string",
interactive: bool = False,
):
self.id = id
self.id = id
self.name = name
self.description = description
self.agents = agents
@ -175,22 +177,22 @@ class InteractiveGroupChat:
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:
message (str): The input message
task (str): The input task
Returns:
List[str]: List of mentioned agent names
Raises:
InvalidMessageFormatError: If the message format is invalid
InvalidtaskFormatError: If the task format is invalid
"""
try:
# Find all @mentions using regex
mentions = re.findall(r"@(\w+)", message)
mentions = re.findall(r"@(\w+)", task)
return [
mention
for mention in mentions
@ -198,9 +200,7 @@ class InteractiveGroupChat:
]
except Exception as e:
logger.error(f"Error extracting mentions: {e}")
raise InvalidMessageFormatError(
f"Invalid message format: {e}"
)
raise InvalidTaskFormatError(f"Invalid task format: {e}")
def start_interactive_session(self):
"""
@ -248,7 +248,7 @@ class InteractiveGroupChat:
print("\nHelp:")
print("1. Mention agents using @agent_name")
print(
"2. You can mention multiple agents in one message"
"2. You can mention multiple agents in one task"
)
print("3. Available agents:")
for name in self.agent_map:
@ -261,7 +261,7 @@ class InteractiveGroupChat:
if not user_input:
continue
# Process the message and get responses
# Process the task and get responses
try:
response = self.run(user_input)
print("\nChat:")
@ -285,23 +285,23 @@ class InteractiveGroupChat:
"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().
Otherwise, it can be called directly for single message processing.
Otherwise, it can be called directly for single task processing.
"""
try:
# Extract mentioned agents
mentioned_agents = self._extract_mentions(message)
mentioned_agents = self._extract_mentions(task)
if not mentioned_agents:
raise NoMentionedAgentsError(
"No valid agents mentioned in the message"
"No valid agents mentioned in the task"
)
# Add user message to conversation
self.conversation.add(role="User", content=message)
# Add user task to conversation
self.conversation.add(role="User", content=task)
# Get responses from mentioned agents
for agent_name in mentioned_agents:
@ -320,7 +320,7 @@ class InteractiveGroupChat:
# Get response from agent
if isinstance(agent, Agent):
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:
# For callable functions

Loading…
Cancel
Save