Update docs folder with new structure and content

pull/985/head
IlumCI 3 months ago
commit c4f41f90f5

@ -24,7 +24,7 @@ jobs:
uses: actions/checkout@v4 uses: actions/checkout@v4
# Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis # Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis
- name: Run Codacy Analysis CLI - name: Run Codacy Analysis CLI
uses: codacy/codacy-analysis-cli-action@97bf5df3c09e75f5bcd72695998f96ebd701846e uses: codacy/codacy-analysis-cli-action@562ee3e92b8e92df8b67e0a5ff8aa8e261919c08
with: with:
# Check https://github.com/codacy/codacy-analysis-cli#project-token to # Check https://github.com/codacy/codacy-analysis-cli#project-token to
# get your project token from your Codacy repository # get your project token from your Codacy repository

@ -11,7 +11,7 @@ jobs:
permissions: write-all permissions: write-all
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/first-interaction@v1.3.0 - uses: actions/first-interaction@v2.0.0
with: with:
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-message: issue-message:

@ -225,7 +225,15 @@ nav:
- Quickstart: "quickstart.md" - Quickstart: "quickstart.md"
- Agents: "swarms/agents/index.md" - Agents: "swarms/agents/index.md"
- Multi-Agent Architectures: "swarms/structs/index.md" - Multi-Agent Architectures: "swarms/structs/index.md"
- Protocol:
- Overview: "protocol/overview.md"
- SIPs: "protocol/sip.md"
- Feature Set: "swarms/features.md" - Feature Set: "swarms/features.md"
- Swarms Ecosystem: "swarms/ecosystem.md"
- Technical Support: "swarms/support.md"
- Agents: - Agents:
- Overview: "swarms/framework/agents_explained.md" - Overview: "swarms/framework/agents_explained.md"
- Quickstart: "swarms/agents/index.md" - Quickstart: "swarms/agents/index.md"
@ -347,10 +355,6 @@ nav:
- Deploy on Phala: "swarms_cloud/phala_deploy.md" - Deploy on Phala: "swarms_cloud/phala_deploy.md"
# - Deploy on FastAPI: "swarms_cloud/fastapi_deploy.md" # - Deploy on FastAPI: "swarms_cloud/fastapi_deploy.md"
- More About Us:
- Swarms Ecosystem: "swarms/ecosystem.md"
- Technical Support: "swarms/support.md"
- Examples: - Examples:
- Overview: "examples/index.md" - Overview: "examples/index.md"
@ -493,7 +497,7 @@ nav:
- Understanding Swarms Architecture: "swarms/concept/framework_architecture.md" - Understanding Swarms Architecture: "swarms/concept/framework_architecture.md"
- Development Philosophy & Principles: "swarms/concept/philosophy.md" - Development Philosophy & Principles: "swarms/concept/philosophy.md"
- About Swarms: # - About Swarms:
- Vision & Mission: "swarms/concept/vision.md" # - Vision & Mission: "swarms/concept/vision.md"
- Swarm Ecosystem: "swarms/concept/swarm_ecosystem.md" # - Swarm Ecosystem: "swarms/concept/swarm_ecosystem.md"
- Products: "swarms/products.md" # - Products: "swarms/products.md"

@ -0,0 +1 @@
# Backwards Compatability

@ -0,0 +1,439 @@
# Swarms Protocol Overview & Architecture
This document provides a comprehensive overview of the Swarms protocol architecture, illustrating the flow from agent classes to multi-agent structures, and showcasing the main components and folders within the `swarms/` package. The Swarms framework is designed for extensibility, modularity, and production-readiness, enabling the orchestration of intelligent agents, tools, memory, and complex multi-agent systems.
---
## Introduction
Swarms is an enterprise-grade, production-ready multi-agent orchestration framework. It enables developers and organizations to build, deploy, and manage intelligent agents that can reason, collaborate, and solve complex tasks autonomously or in groups. The architecture is inspired by the principles of modularity, composability, and scalability, ensuring that each component can be extended or replaced as needed.
The protocol is structured to support a wide range of use cases, from simple single-agent automations to sophisticated multi-agent workflows involving memory, tool use, and advanced reasoning.
For a high-level introduction and installation instructions, see the [Swarms Docs Home](https://docs.swarms.world/en/latest/).
---
## High-Level Architecture Flow
The Swarms protocol is organized into several key layers, each responsible for a specific aspect of the system. The typical flow is as follows:
1. **Agent Class (`swarms/agents`)**
- The core building block of the framework. Agents encapsulate logic, state, and behavior. They can be simple (stateless) or complex
(stateful, with memory and reasoning capabilities).
- Agents can be specialized for different tasks (e.g., reasoning agents, tool agents, judge agents, etc.).
- Example: A `ReasoningAgent` that can analyze data and make decisions, or a `ToolAgent` that wraps external APIs.
- [Quickstart for Agents](https://docs.swarms.world/en/latest/swarms/agents/)
- [Agent API Reference](https://docs.swarms.world/en/latest/swarms/structs/agent/)
2. **Tools with Memory (`swarms/tools`, `swarms/utils`)**
- Tools are modular components that agents use to interact with the outside world, perform computations, or access resources (APIs,
databases, files, etc.).
- Memory modules and utility functions allow agents to retain context, cache results, and manage state across interactions.
- Example: A tool for calling an LLM API, a memory cache for conversation history, or a utility for parsing and formatting data.
- [Tools Overview](https://docs.swarms.world/en/latest/swarms_tools/overview/)
- [BaseTool Reference](https://docs.swarms.world/en/latest/swarms/tools/base_tool/)
3. **Reasoning & Specialized Agents (`swarms/agents`)**
- These agents build on the base agent class, adding advanced reasoning, self-consistency, and specialized logic for tasks like
planning, evaluation, or multi-step workflows.
- Includes agents for self-reflection, iterative improvement, and domain-specific expertise.
- Example: A `SelfConsistencyAgent` that aggregates multiple reasoning paths, or a `JudgeAgent` that evaluates outputs from other
agents.
- [Reasoning Agents Overview](https://docs.swarms.world/en/latest/swarms/agents/reasoning_agents_overview/)
- [Self Consistency Agent](https://docs.swarms.world/en/latest/swarms/agents/consistency_agent/)
- [Agent Judge](https://docs.swarms.world/en/latest/swarms/agents/agent_judge/)
4. **Multi-Agent Structures (`swarms/structs`)**
- Agents are composed into higher-order structures for collaboration, voting, parallelism, and workflow orchestration.
- Includes swarms for majority voting, round-robin execution, hierarchical delegation, and more.
- Example: A `MajorityVotingSwarm` that aggregates outputs from several agents, or a `HierarchicalSwarm` that delegates tasks to
sub-agents.
- [Multi-Agent Architectures Overview](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/)
- [MajorityVotingSwarm](https://docs.swarms.world/en/latest/swarms/structs/majorityvoting/)
- [HierarchicalSwarm](https://docs.swarms.world/en/latest/swarms/structs/hierarchical_swarm/)
- [Sequential Workflow](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/)
- [Concurrent Workflow](https://docs.swarms.world/en/latest/swarms/structs/concurrentworkflow/)
5. **Supporting Components**
- **Communication (`swarms/communication`)**: Provides wrappers for inter-agent communication, database access, message passing, and
integration with external systems (e.g., Redis, DuckDB, Pulsar). See [Communication Structure](https://docs.swarms.world/en/latest/swarms/structs/conversation/)
- **Artifacts (`swarms/artifacts`)**: Manages the creation, storage, and retrieval of artifacts (outputs, files, logs) generated by
agents and swarms.
- **Prompts (`swarms/prompts`)**: Houses prompt templates, system prompts, and agent-specific prompts for LLM-based agents. See
[Prompts Management](https://docs.swarms.world/en/latest/swarms/prompts/main/)
- **Telemetry (`swarms/telemetry`)**: Handles logging, monitoring, and bootup routines for observability and debugging.
- **Schemas (`swarms/schemas`)**: Defines data schemas for agents, tools, completions, and communication protocols, ensuring type
safety and consistency.
- **CLI (`swarms/cli`)**: Provides command-line utilities for agent creation, management, and orchestration. See [CLI Documentation]
(https://docs.swarms.world/en/latest/swarms/cli/main/)
---
## Proposing Large Improvements or Enhancements: Swarms Improvement Proposals (SIPs)
For significant changes, new agent architectures, or radical new features, Swarms uses a formal process called **Swarms Improvement Proposals (SIPs)**. SIPs are design documents that describe new features, enhancements, or changes to the Swarms framework. They ensure that major changes are well-documented, discussed, and reviewed by the community before implementation.
**When to use a SIP:**
- Proposing new agent types, swarm patterns, or coordination mechanisms
- Core framework changes or breaking changes
- New integrations (LLM providers, tools, external services)
- Any complex or multi-component feature
**SIP Process Overview:**
1. Discuss your idea in [GitHub Discussions](https://github.com/kyegomez/swarms/discussions)
2. Submit a SIP as a GitHub Issue using the SIP template
3. Engage with the community and iterate on your proposal
4. Undergo review and, if accepted, proceed to implementation
**Learn more:** See the full [SIP Guidelines and Template](https://docs.swarms.world/en/latest/protocol/sip/)
---
## Detailed Architecture Diagram
The following Mermaid diagram visualizes the protocol flow and the relationship between the main folders in the `swarms/` package:
```mermaid
flowchart TD
A["Agent Class<br/>(swarms/agents)"] --> B["Tools with Memory<br/>(swarms/tools, swarms/utils)"]
B --> C["Reasoning & Specialized Agents<br/>(swarms/agents)"]
C --> D["Multi-Agent Structures<br/>(swarms/structs)"]
D --> E["Communication, Artifacts, Prompts, Telemetry, Schemas, CLI"]
subgraph Folders
A1["agents"]
A2["tools"]
A3["structs"]
A4["utils"]
A5["telemetry"]
A6["schemas"]
A7["prompts"]
A8["artifacts"]
A9["communication"]
A10["cli"]
end
%% Folder showcase
subgraph "swarms/"
A1
A2
A3
A4
A5
A6
A7
A8
A9
A10
end
%% Connect folder showcase to main flow
A1 -.-> A
A2 -.-> B
A3 -.-> D
A4 -.-> B
A5 -.-> E
A6 -.-> E
A7 -.-> E
A8 -.-> E
A9 -.-> E
A10 -.-> E
```
---
## Folder-by-Folder Breakdown
### `agents/`
**Purpose:** Defines all agent classes, including base agents, reasoning agents, tool agents, judge agents, and more.
**Highlights:**
- Modular agent design for extensibility.
- Support for YAML-based agent creation and configuration. See [YAML Agent Creation](https://docs.swarms.world/en/latest/swarms/
agents/create_agents_yaml/)
- Specialized agents for self-consistency, evaluation, and domain-specific tasks.
- **Example:**
- `ReasoningAgent`, `ToolAgent`, `JudgeAgent`, `ConsistencyAgent`, `OpenAIAssistant`, etc.
- [Agents Overview](https://docs.swarms.world/en/latest/swarms/framework/agents_explained/)
### `tools/`
**Purpose:** Houses all tool-related logic, including tool registry, function calling, tool schemas, and integration with external
APIs.
**Highlights:**
- Tools can be dynamically registered and called by agents.
- Support for OpenAI function calling, Cohere, and custom tool schemas.
- Utilities for parsing, formatting, and executing tool calls.
- **Example:**
- `base_tool.py`, `tool_registry.py`, `mcp_client_call.py`, `func_calling_utils.py`, etc.
- [Tools Reference](https://docs.swarms.world/en/latest/swarms/tools/tools_examples/)
- [What are tools?](https://docs.swarms.world/en/latest/swarms/tools/build_tool/)
### `structs/`
**Purpose:** Implements multi-agent structures, workflows, routers, registries, and orchestration logic.
**Highlights:**
- Swarms for majority voting, round-robin, hierarchical delegation, spreadsheet processing, and more.
- Workflow orchestration (sequential, concurrent, graph-based).
- Utilities for agent matching, rearrangement, and evaluation.
- **Example:**
- `MajorityVotingSwarm`, `HierarchicalSwarm`, `SwarmRouter`, `SequentialWorkflow`, `ConcurrentWorkflow`, etc.
- [Custom Multi Agent Architectures](https://docs.swarms.world/en/latest/swarms/structs/custom_swarm/)
- [SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)
- [AgentRearrange](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/)
### `utils/`
**Purpose:** Provides utility functions, memory management, caching, wrappers, and helpers used throughout the framework.
**Highlights:**
- Memory and caching for agents and tools. See [Integrating RAG with Agents](https://docs.swarms.world/en/latest/swarms/memory/
diy_memory/)
- Wrappers for concurrency, logging, and data processing.
- General-purpose utilities for string, file, and data manipulation.
**Example:**
- `agent_cache.py`, `concurrent_wrapper.py`, `file_processing.py`, `formatter.py`, etc.
### `telemetry/`
**Purpose:** Handles telemetry, logging, monitoring, and bootup routines for the framework.
**Highlights:**
- Centralized logging and execution tracking.
- Bootup routines for initializing the framework.
- Utilities for monitoring agent and swarm performance.
- **Example:**
- `bootup.py`, `log_executions.py`, `main.py`.
### `schemas/`
**Purpose:** Defines data schemas for agents, tools, completions, and communication protocols.
**Highlights:**
- Ensures type safety and consistency across the framework.
- Pydantic-based schemas for validation and serialization.
- Schemas for agent classes, tool calls, completions, and more.
**Example:**
- `agent_class_schema.py`, `tool_schema_base_model.py`, `agent_completion_response.py`, etc.
### `prompts/`
**Purpose:** Contains prompt templates, system prompts, and agent-specific prompts for LLM-based agents.
**Highlights:**
- Modular prompt design for easy customization.
- Support for multi-modal, collaborative, and domain-specific prompts.
- Templates for system, task, and conversational prompts.
**Example:**
- `prompt.py`, `reasoning_prompt.py`, `multi_agent_collab_prompt.py`, etc.
- [Prompts Management](https://docs.swarms.world/en/latest/swarms/prompts/main/)
### `artifacts/`
**Purpose:** Manages the creation, storage, and retrieval of artifacts (outputs, files, logs) generated by agents and swarms.
**Highlights:**
- Artifact management for reproducibility and traceability.
- Support for various output types and formats.
**Example:**
- `main_artifact.py`.
### `communication/`
**Purpose:** Provides wrappers for inter-agent communication, database access, message passing, and integration with external systems.
**Highlights:**
- Support for Redis, DuckDB, Pulsar, Supabase, and more.
- Abstractions for message passing and data exchange between agents.
**Example:**
- `redis_wrap.py`, `duckdb_wrap.py`, `base_communication.py`, etc.
- [Communication Structure](https://docs.swarms.world/en/latest/swarms/structs/conversation/)
### `cli/`
**Purpose:** Command-line utilities for agent creation, management, and orchestration.
**Highlights:**
- Scripts for onboarding, agent creation, and management.
- CLI entry points for interacting with the framework.
**Example:**
- `main.py`, `create_agent.py`, `onboarding_process.py`.
- [CLI Documentation](https://docs.swarms.world/en/latest/swarms/cli/main/)
---
## How the System Works Together
The Swarms protocol is designed for composability. Agents can be created and configured independently, then composed into larger structures (swarms) for collaborative or competitive workflows. Tools and memory modules are injected into agents as needed, enabling them to perform complex tasks and retain context. Multi-agent structures orchestrate the flow of information and decision-making, while supporting components (communication, telemetry, artifacts, etc.) ensure robustness, observability, and extensibility.
For example, a typical workflow might involve:
- Creating a set of specialized agents (e.g., data analyst, summarizer, judge).
- Registering tools (e.g., LLM API, database access, web search) and memory modules.
- Composing agents into a `MajorityVotingSwarm` for collaborative decision-making.
- Using communication wrappers to exchange data between agents and external systems.
- Logging all actions and outputs for traceability and debugging.
For more advanced examples, see the [Examples Overview](https://docs.swarms.world/en/latest/examples/index/).
---
## Swarms Framework Philosophy
Swarms is built on the following principles:
- **Modularity:** Every component (agent, tool, prompt, schema) is a module that can be extended or replaced.
- **Composability:** Agents and tools can be composed into larger structures for complex workflows.
- **Observability:** Telemetry and artifact management ensure that all actions are traceable and debuggable.
- **Extensibility:** New agents, tools, and workflows can be added with minimal friction.
- **Production-Readiness:** The framework is designed for reliability, scalability, and real-world deployment.
For more on the philosophy and architecture, see [Development Philosophy & Principles](https://docs.swarms.world/en/latest/swarms/concept/philosophy/) and [Understanding Swarms Architecture](https://docs.swarms.world/en/latest/swarms/concept/framework_architecture/).
---
## Further Reading & References
- [Swarms Docs Home](https://docs.swarms.world/en/latest/)
- [Quickstart for Agents](https://docs.swarms.world/en/latest/swarms/agents/)
- [Agent API Reference](https://docs.swarms.world/en/latest/swarms/structs/agent/)
- [Tools Overview](https://docs.swarms.world/en/latest/swarms_tools/overview/)
- [BaseTool Reference](https://docs.swarms.world/en/latest/swarms/tools/base_tool/)
- [Reasoning Agents Overview](https://docs.swarms.world/en/latest/swarms/agents/reasoning_agents_overview/)
- [Multi-Agent Architectures Overview](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/)
- [Examples Overview](https://docs.swarms.world/en/latest/examples/index/)
- [CLI Documentation](https://docs.swarms.world/en/latest/swarms/cli/main/)
- [Prompts Management](https://docs.swarms.world/en/latest/swarms/prompts/main/)
- [Development Philosophy & Principles](https://docs.swarms.world/en/latest/swarms/concept/philosophy/)
- [Understanding Swarms Architecture](https://docs.swarms.world/en/latest/swarms/concept/framework_architecture/)
- [SIP Guidelines and Template](https://docs.swarms.world/en/latest/protocol/sip/)
# Conclusion
The Swarms protocol provides a robust foundation for building intelligent, collaborative, and autonomous systems. By organizing the codebase into clear, modular folders and defining a logical flow from agents to multi-agent structures, Swarms enables rapid development and deployment of advanced AI solutions. Whether you are building a simple automation or a complex multi-agent application, the Swarms architecture provides the tools and abstractions you need to succeed.

@ -0,0 +1,159 @@
# Swarms Improvement Proposal (SIP) Guidelines
A simplified process for proposing new functionality and enhancements to the Swarms framework.
## What is a SIP?
A **Swarms Improvement Proposal (SIP)** is a design document that describes a new feature, enhancement, or change to the Swarms framework. SIPs serve as the primary mechanism for proposing significant changes, collecting community feedback, and documenting design decisions.
The SIP author is responsible for building consensus within the community and documenting the proposal clearly and concisely.
## When to Submit a SIP
Consider submitting a SIP for:
- **New Agent Types or Behaviors**: Adding new agent architectures, swarm patterns, or coordination mechanisms
- **Core Framework Changes**: Modifications to the Swarms API, core classes, or fundamental behaviors
- **New Integrations**: Adding support for new LLM providers, tools, or external services
- **Breaking Changes**: Any change that affects backward compatibility
- **Complex Features**: Multi-component features that require community discussion and design review
For simple bug fixes, minor enhancements, or straightforward additions, use regular GitHub issues and pull requests instead.
## SIP Types
**Standard SIP**: Describes a new feature or change to the Swarms framework
**Process SIP**: Describes changes to development processes, governance, or community guidelines
**Informational SIP**: Provides information or guidelines to the community without proposing changes
## Submitting a SIP
1. **Discuss First**: Post your idea in [GitHub Discussions](https://github.com/kyegomez/swarms/discussions) to gauge community interest
2. **Create Issue**: Submit your SIP as a GitHub Issue with the `SIP` and `proposal` labels
3. **Follow Format**: Use the SIP template format below
4. **Engage Community**: Respond to feedback and iterate on your proposal
## SIP Format
### Required Sections
#### **SIP Header**
```
Title: [Descriptive title]
Author: [Your name and contact]
Type: [Standard/Process/Informational]
Status: Proposal
Created: [Date]
```
#### **Abstract** (200 words max)
A brief summary of what you're proposing and why.
#### **Motivation**
- What problem does this solve?
- Why can't the current framework handle this?
- What are the benefits to the Swarms ecosystem?
#### **Specification**
- Detailed technical description
- API changes or new interfaces
- Code examples showing usage
- Integration points with existing framework
#### **Implementation Plan**
- High-level implementation approach
- Breaking changes (if any)
- Migration path for existing users
- Testing strategy
#### **Alternatives Considered**
- Other approaches you evaluated
- Why you chose this solution
- Trade-offs and limitations
### Optional Sections
#### **Reference Implementation**
Link to prototype code or proof-of-concept (can be added later)
#### **Security Considerations**
Any security implications or requirements
## SIP Workflow
```
Proposal → Draft → Review → Accepted/Rejected → Final
```
1. **Proposal**: Initial submission as GitHub Issue
2. **Draft**: Maintainer assigns SIP number and `draft` label
3. **Review**: Community and maintainer review period
4. **Decision**: Accepted, rejected, or needs revision
5. **Final**: Implementation completed and merged
## SIP Status
- **Proposal**: Newly submitted, awaiting initial review
- **Draft**: Under active discussion and refinement
- **Review**: Formal review by maintainers
- **Accepted**: Approved for implementation
- **Rejected**: Not accepted (with reasons)
- **Final**: Implementation completed and merged
- **Withdrawn**: Author withdrew the proposal
## Review Process
- SIPs are reviewed during regular maintainer meetings
- Community feedback is collected via GitHub comments
- Acceptance requires:
- Clear benefit to the Swarms ecosystem
- Technical feasibility
- Community support
- Working prototype (for complex features)
## Getting Help
- **Discussions**: Use [GitHub Discussions](https://github.com/kyegomez/swarms/discussions) for questions
- **Documentation**: Check [docs.swarms.world](https://docs.swarms.world) for framework details
- **Examples**: Look at existing SIPs for reference
## SIP Template
When creating your SIP, copy this template:
```markdown
# SIP-XXX: [Title]
**Author**: [Your name] <[email]>
**Type**: Standard
**Status**: Proposal
**Created**: [Date]
## Abstract
[Brief 200-word summary]
## Motivation
[Why is this needed? What problem does it solve?]
## Specification
[Detailed technical description with code examples]
## Implementation Plan
[How will this be built? Any breaking changes?]
## Alternatives Considered
[Other approaches and why you chose this one]
## Reference Implementation
[Link to prototype code if available]
```
---
**Note**: This process is designed to be lightweight while ensuring important changes get proper community review. For questions about whether your idea needs a SIP, start a discussion in the GitHub Discussions forum.

@ -1,4 +1,3 @@
import json
import os import os
from swarms_client import SwarmsClient from swarms_client import SwarmsClient
from swarms_client.types import AgentSpecParam from swarms_client.types import AgentSpecParam
@ -12,7 +11,7 @@ agent_spec = AgentSpecParam(
agent_name="doctor_agent", agent_name="doctor_agent",
description="A virtual doctor agent that provides evidence-based, safe, and empathetic medical advice for common health questions. Always reminds users to consult a healthcare professional for diagnoses or prescriptions.", description="A virtual doctor agent that provides evidence-based, safe, and empathetic medical advice for common health questions. Always reminds users to consult a healthcare professional for diagnoses or prescriptions.",
task="What is the best medicine for a cold?", task="What is the best medicine for a cold?",
model_name="claude-3-5-sonnet-20241022", model_name="claude-4-sonnet-20250514",
system_prompt=( system_prompt=(
"You are a highly knowledgeable, ethical, and empathetic virtual doctor. " "You are a highly knowledgeable, ethical, and empathetic virtual doctor. "
"Always provide evidence-based, safe, and practical medical advice. " "Always provide evidence-based, safe, and practical medical advice. "
@ -26,15 +25,15 @@ agent_spec = AgentSpecParam(
role="doctor", role="doctor",
) )
# response = client.agent.run( response = client.agent.run(
# agent_config=agent_spec, agent_config=agent_spec,
# task="What is the best medicine for a cold?", task="What is the best medicine for a cold?",
# ) )
# print(response) print(response)
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.swarms.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,26 @@
from swarms.tools.mcp_client_call import (
execute_tool_call_simple,
get_mcp_tools_sync,
)
async def main():
# Prepare the tool call in OpenAI-compatible format
response = {
"function": {"name": "greet", "arguments": {"name": "Alice"}}
}
result = await execute_tool_call_simple(
server_path="http://localhost:8000/mcp",
response=response,
# transport="streamable_http",
)
print("Tool call result:", result)
return result
if __name__ == "__main__":
print(get_mcp_tools_sync(server_path="http://localhost:8000/mcp"))
import asyncio
asyncio.run(main())

@ -0,0 +1,28 @@
"""
Run from the repository root:
uv run examples/snippets/servers/streamable_config.py
"""
from mcp.server.fastmcp import FastMCP
# Stateful server (maintains session state)
mcp = FastMCP("StatefulServer", json_response=True)
# Other configuration options:
# Stateless server (no session persistence)
# mcp = FastMCP("StatelessServer", stateless_http=True)
# Stateless server (no session persistence, no sse stream with supported client)
# mcp = FastMCP("StatelessServer", stateless_http=True, json_response=True)
# Add a simple tool to demonstrate the server
@mcp.tool()
def greet(name: str = "World") -> str:
"""Greet someone by name."""
return f"Hello, {name}!"
# Run server with streamable_http transport
if __name__ == "__main__":
mcp.run(transport="streamable-http")

@ -0,0 +1,62 @@
from swarms import Agent, ConcurrentWorkflow, SwarmRouter
# Initialize market research agent
market_researcher = Agent(
agent_name="Market-Researcher",
system_prompt="""You are a market research specialist. Your tasks include:
1. Analyzing market trends and patterns
2. Identifying market opportunities and threats
3. Evaluating competitor strategies
4. Assessing customer needs and preferences
5. Providing actionable market insights""",
model_name="claude-3-5-sonnet-20240620",
max_loops=1,
streaming_on=True,
print_on=False,
)
# Initialize financial analyst agent
financial_analyst = Agent(
agent_name="Financial-Analyst",
system_prompt="""You are a financial analysis expert. Your responsibilities include:
1. Analyzing financial statements
2. Evaluating investment opportunities
3. Assessing risk factors
4. Providing financial forecasts
5. Recommending financial strategies""",
model_name="claude-3-5-sonnet-20240620",
max_loops=1,
streaming_on=True,
print_on=False,
)
# Initialize technical analyst agent
technical_analyst = Agent(
agent_name="Technical-Analyst",
system_prompt="""You are a technical analysis specialist. Your focus areas include:
1. Analyzing price patterns and trends
2. Evaluating technical indicators
3. Identifying support and resistance levels
4. Assessing market momentum
5. Providing trading recommendations""",
model_name="claude-3-5-sonnet-20240620",
max_loops=1,
streaming_on=True,
print_on=False,
)
# Create list of agents
agents = [market_researcher, financial_analyst, technical_analyst]
# Initialize the concurrent workflow
workflow = ConcurrentWorkflow(
name="market-analysis-workflow",
agents=agents,
max_loops=1,
show_dashboard=True,
)
# Run the workflow
result = workflow.run(
"Analyze Tesla (TSLA) stock from market, financial, and technical perspectives"
)

@ -78,6 +78,7 @@ litellm = "*"
torch = "*" torch = "*"
httpx = "*" httpx = "*"
mcp = "*" mcp = "*"
openai = "*"
aiohttp = "*" aiohttp = "*"
[tool.poetry.scripts] [tool.poetry.scripts]
@ -86,7 +87,7 @@ swarms = "swarms.cli.main:main"
[tool.poetry.group.lint.dependencies] [tool.poetry.group.lint.dependencies]
black = ">=23.1,<26.0" black = ">=23.1,<26.0"
ruff = ">=0.5.1,<0.12.4" ruff = ">=0.5.1,<0.12.5"
types-toml = "^0.10.8.1" types-toml = "^0.10.8.1"
types-pytz = ">=2023.3,<2026.0" types-pytz = ">=2023.3,<2026.0"
types-chardet = "^5.0.4.6" types-chardet = "^5.0.4.6"

@ -26,3 +26,4 @@ httpx
aiohttp aiohttp
mcp mcp
numpy numpy
openai

@ -8,7 +8,7 @@ class MCPConnection(BaseModel):
description="The type of connection, defaults to 'mcp'", description="The type of connection, defaults to 'mcp'",
) )
url: Optional[str] = Field( url: Optional[str] = Field(
default="localhost:8000/sse", default="http://localhost:8000/mcp",
description="The URL endpoint for the MCP server", description="The URL endpoint for the MCP server",
) )
tool_configurations: Optional[Dict[Any, Any]] = Field( tool_configurations: Optional[Dict[Any, Any]] = Field(
@ -20,18 +20,19 @@ class MCPConnection(BaseModel):
description="Authentication token for accessing the MCP server", description="Authentication token for accessing the MCP server",
) )
transport: Optional[str] = Field( transport: Optional[str] = Field(
default="sse", default="streamable_http",
description="The transport protocol to use for the MCP server", description="The transport protocol to use for the MCP server",
) )
headers: Optional[Dict[str, str]] = Field( headers: Optional[Dict[str, str]] = Field(
default=None, description="Headers to send to the MCP server" default=None, description="Headers to send to the MCP server"
) )
timeout: Optional[int] = Field( timeout: Optional[int] = Field(
default=5, description="Timeout for the MCP server" default=10, description="Timeout for the MCP server"
) )
class Config: class Config:
arbitrary_types_allowed = True arbitrary_types_allowed = True
extra = "allow"
class MultipleMCPConnections(BaseModel): class MultipleMCPConnections(BaseModel):

@ -996,6 +996,7 @@ class Agent:
self, self,
task: Optional[Union[str, Any]] = None, task: Optional[Union[str, Any]] = None,
img: Optional[str] = None, img: Optional[str] = None,
streaming_callback: Optional[Callable[[str], None]] = None,
*args, *args,
**kwargs, **kwargs,
) -> Any: ) -> Any:
@ -1077,6 +1078,7 @@ class Agent:
task=task_prompt, task=task_prompt,
img=img, img=img,
current_loop=loop_count, current_loop=loop_count,
streaming_callback=streaming_callback,
*args, *args,
**kwargs, **kwargs,
) )
@ -1084,6 +1086,7 @@ class Agent:
response = self.call_llm( response = self.call_llm(
task=task_prompt, task=task_prompt,
current_loop=loop_count, current_loop=loop_count,
streaming_callback=streaming_callback,
*args, *args,
**kwargs, **kwargs,
) )
@ -2470,6 +2473,7 @@ class Agent:
task: str, task: str,
img: Optional[str] = None, img: Optional[str] = None,
current_loop: int = 0, current_loop: int = 0,
streaming_callback: Optional[Callable[[str], None]] = None,
*args, *args,
**kwargs, **kwargs,
) -> str: ) -> str:
@ -2480,6 +2484,7 @@ class Agent:
task (str): The task to be performed by the `llm` object. task (str): The task to be performed by the `llm` object.
img (str, optional): Path or URL to an image file. img (str, optional): Path or URL to an image file.
audio (str, optional): Path or URL to an audio file. audio (str, optional): Path or URL to an audio file.
streaming_callback (Optional[Callable[[str], None]]): Callback function to receive streaming tokens in real-time.
*args: Variable length argument list. *args: Variable length argument list.
**kwargs: Arbitrary keyword arguments. **kwargs: Arbitrary keyword arguments.
@ -2515,8 +2520,24 @@ class Agent:
if hasattr( if hasattr(
streaming_response, "__iter__" streaming_response, "__iter__"
) and not isinstance(streaming_response, str): ) and not isinstance(streaming_response, str):
# Check if streaming_callback is provided (for ConcurrentWorkflow dashboard integration)
if streaming_callback is not None:
# Real-time callback streaming for dashboard integration
chunks = []
for chunk in streaming_response:
if (
hasattr(chunk, "choices")
and chunk.choices[0].delta.content
):
content = chunk.choices[
0
].delta.content
chunks.append(content)
# Call the streaming callback with the new chunk
streaming_callback(content)
complete_response = "".join(chunks)
# Check print_on parameter for different streaming behaviors # Check print_on parameter for different streaming behaviors
if self.print_on is False: elif self.print_on is False:
# Silent streaming - no printing, just collect chunks # Silent streaming - no printing, just collect chunks
chunks = [] chunks = []
for chunk in streaming_response: for chunk in streaming_response:
@ -2599,6 +2620,7 @@ class Agent:
img: Optional[str] = None, img: Optional[str] = None,
imgs: Optional[List[str]] = None, imgs: Optional[List[str]] = None,
correct_answer: Optional[str] = None, correct_answer: Optional[str] = None,
streaming_callback: Optional[Callable[[str], None]] = None,
*args, *args,
**kwargs, **kwargs,
) -> Any: ) -> Any:
@ -2613,6 +2635,7 @@ class Agent:
task (Optional[str], optional): The task to be executed. Defaults to None. task (Optional[str], optional): The task to be executed. Defaults to None.
img (Optional[str], optional): The image to be processed. Defaults to None. img (Optional[str], optional): The image to be processed. Defaults to None.
imgs (Optional[List[str]], optional): The list of images to be processed. Defaults to None. imgs (Optional[List[str]], optional): The list of images to be processed. Defaults to None.
streaming_callback (Optional[Callable[[str], None]], optional): Callback function to receive streaming tokens in real-time. Defaults to None.
*args: Additional positional arguments to be passed to the execution method. *args: Additional positional arguments to be passed to the execution method.
**kwargs: Additional keyword arguments to be passed to the execution method. **kwargs: Additional keyword arguments to be passed to the execution method.
@ -2644,6 +2667,7 @@ class Agent:
output = self._run( output = self._run(
task=task, task=task,
img=img, img=img,
streaming_callback=streaming_callback,
*args, *args,
**kwargs, **kwargs,
) )

@ -1,5 +1,6 @@
import concurrent.futures import concurrent.futures
import os import os
import time
from typing import Callable, List, Optional, Union from typing import Callable, List, Optional, Union
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
@ -138,7 +139,7 @@ class ConcurrentWorkflow(BaseSwarm):
self, self,
name: str = "ConcurrentWorkflow", name: str = "ConcurrentWorkflow",
description: str = "Execution of multiple agents concurrently", description: str = "Execution of multiple agents concurrently",
agents: List[Union[Agent, Callable]] = [], agents: List[Union[Agent, Callable]] = None,
metadata_output_path: str = "agent_metadata.json", metadata_output_path: str = "agent_metadata.json",
auto_save: bool = True, auto_save: bool = True,
output_type: str = "dict-all-except-first", output_type: str = "dict-all-except-first",
@ -450,8 +451,25 @@ class ConcurrentWorkflow(BaseSwarm):
if self.show_dashboard: if self.show_dashboard:
self.display_agent_dashboard() self.display_agent_dashboard()
# Run the agent # Create a streaming callback for this agent with throttling
output = agent.run(task=task, img=img, imgs=imgs) last_update_time = [0] # Use list to allow modification in nested function
update_interval = 0.1 # Update dashboard every 100ms for smooth streaming
def streaming_callback(chunk: str):
"""Update dashboard with streaming content"""
if self.show_dashboard:
# Append the chunk to the agent's current output
current_output = self.agent_statuses[agent.agent_name]["output"]
self.agent_statuses[agent.agent_name]["output"] = current_output + chunk
# Throttle dashboard updates for better performance
current_time = time.time()
if current_time - last_update_time[0] >= update_interval:
self.display_agent_dashboard()
last_update_time[0] = current_time
# Run the agent with streaming callback
output = agent.run(task=task, img=img, imgs=imgs, streaming_callback=streaming_callback)
# Update status to completed # Update status to completed
self.agent_statuses[agent.agent_name][ self.agent_statuses[agent.agent_name][

@ -1,6 +1,7 @@
import re
import random import random
from typing import Callable, List, Union, Optional import re
import traceback
from typing import Callable, List, Optional, Union
from loguru import logger from loguru import logger
@ -183,60 +184,33 @@ speaker_functions = {
class InteractiveGroupChat: class InteractiveGroupChat:
""" """
An interactive group chat system that enables conversations with multiple agents using @mentions. InteractiveGroupChat enables collaborative conversations among multiple agents (or callables)
with flexible speaker selection strategies, conversation history, and interactive terminal sessions.
This class allows users to interact with multiple agents by mentioning them using @agent_name syntax. Features:
When multiple agents are mentioned, they can see and respond to each other's tasks. - Supports multiple agents (LLMs or callable functions)
- Customizable speaker selection (round robin, random, priority, dynamic, or custom)
- Maintains conversation history with time stamps
- Interactive REPL session for human-in-the-loop group chat
- Agents can @mention each other to request input or delegate tasks
- Automatic prompt augmentation to teach agents collaborative protocols
Attributes: Args:
id (str): Unique identifier for the group chat (default: generated)
name (str): Name of the group chat name (str): Name of the group chat
description (str): Description of the group chat's purpose description (str): Description of the group chat's purpose
agents (List[Union[Agent, Callable]]): List of Agent instances or callable functions agents (List[Union[Agent, Callable]]): List of agent objects or callables
max_loops (int): Maximum number of conversation turns max_loops (int): Maximum number of conversation loops per run
conversation (Conversation): Stores the chat history output_type (str): Output format for conversation history ("dict", "str", etc.)
agent_map (Dict[str, Union[Agent, Callable]]): Mapping of agent names to their instances interactive (bool): If True, enables interactive terminal session
speaker_function (Callable): Function to determine speaking order speaker_function (Optional[Union[str, Callable]]): Speaker selection strategy
speaker_state (dict): State for speaker functions that need it speaker_state (Optional[dict]): State/config for the speaker function
Args:
name (str, optional): Name of the group chat. Defaults to "InteractiveGroupChat".
description (str, optional): Description of the chat. Defaults to "An interactive group chat for multiple agents".
agents (List[Union[Agent, Callable]], optional): List of participating agents or callables. Defaults to empty list.
max_loops (int, optional): Maximum conversation turns. Defaults to 1.
output_type (str, optional): Type of output format. Defaults to "string".
interactive (bool, optional): Whether to enable interactive terminal mode. Defaults to False.
speaker_function (Union[str, Callable], optional): Function to determine speaking order. Can be:
- A string name: "round-robin-speaker", "random-speaker", "priority-speaker", "random-dynamic-speaker"
- A custom callable function
- None (defaults to round_robin_speaker)
speaker_state (dict, optional): Initial state for speaker function. Defaults to empty dict.
Raises: Raises:
ValueError: If invalid initialization parameters are provided ValueError: If required arguments are missing or invalid
InvalidSpeakerFunctionError: If the speaker function is invalid InvalidSpeakerFunctionError: If an invalid speaker function is provided
InteractiveGroupChatError: For interactive session errors
Examples: AgentNotFoundError: If an agent is not found by name
# Initialize with string-based speaker function
group_chat = InteractiveGroupChat(
agents=[agent1, agent2, agent3],
speaker_function="random-speaker"
)
# Initialize with priority speaker function
group_chat = InteractiveGroupChat(
agents=[agent1, agent2, agent3],
speaker_function="priority-speaker",
speaker_state={"priorities": {"agent1": 3, "agent2": 2, "agent3": 1}}
)
# Initialize with dynamic speaker function (agents mention each other)
group_chat = InteractiveGroupChat(
agents=[agent1, agent2, agent3],
speaker_function="random-dynamic-speaker"
)
# Change speaker function during runtime
group_chat.set_speaker_function("round-robin-speaker")
""" """
def __init__( def __init__(
@ -246,11 +220,25 @@ class InteractiveGroupChat:
description: str = "An interactive group chat for multiple agents", description: str = "An interactive group chat for multiple agents",
agents: List[Union[Agent, Callable]] = [], agents: List[Union[Agent, Callable]] = [],
max_loops: int = 1, max_loops: int = 1,
output_type: str = "string", output_type: str = "dict",
interactive: bool = False, interactive: bool = False,
speaker_function: Optional[Union[str, Callable]] = None, speaker_function: Optional[Union[str, Callable]] = None,
speaker_state: Optional[dict] = None, speaker_state: Optional[dict] = None,
): ):
"""
Initialize the InteractiveGroupChat.
Args:
id (str): Unique identifier for the group chat.
name (str): Name of the group chat.
description (str): Description of the group chat.
agents (List[Union[Agent, Callable]]): List of agent objects or callables.
max_loops (int): Maximum number of conversation loops per run.
output_type (str): Output format for conversation history.
interactive (bool): If True, enables interactive terminal session.
speaker_function (Optional[Union[str, Callable]]): Speaker selection strategy.
speaker_state (Optional[dict]): State/config for the speaker function.
"""
self.id = id self.id = id
self.name = name self.name = name
self.description = description self.description = description
@ -258,37 +246,49 @@ class InteractiveGroupChat:
self.max_loops = max_loops self.max_loops = max_loops
self.output_type = output_type self.output_type = output_type
self.interactive = interactive self.interactive = interactive
self.speaker_function = speaker_function
self.speaker_state = speaker_state
self.setup()
def _setup_speaker_function(self):
# Speaker function configuration # Speaker function configuration
if speaker_function is None: if self.speaker_function is None:
self.speaker_function = round_robin_speaker self.speaker_function = round_robin_speaker
elif isinstance(speaker_function, str): elif isinstance(self.speaker_function, str):
if speaker_function not in speaker_functions: if self.speaker_function not in speaker_functions:
available_functions = ", ".join( available_functions = ", ".join(
speaker_functions.keys() speaker_functions.keys()
) )
raise InvalidSpeakerFunctionError( raise InvalidSpeakerFunctionError(
f"Invalid speaker function: '{speaker_function}'. " f"Invalid speaker function: '{self.speaker_function}'. "
f"Available functions: {available_functions}" f"Available functions: {available_functions}"
) )
self.speaker_function = speaker_functions[ self.speaker_function = speaker_functions[
speaker_function self.speaker_function
] ]
elif callable(speaker_function): elif callable(self.speaker_function):
self.speaker_function = speaker_function self.speaker_function = self.speaker_function
else: else:
raise InvalidSpeakerFunctionError( raise InvalidSpeakerFunctionError(
"Speaker function must be either a string, callable, or None" "Speaker function must be either a string, callable, or None"
) )
self.speaker_state = speaker_state or {"current_index": 0} self.speaker_state = self.speaker_state or {
"current_index": 0
}
# Validate speaker function def setup(self):
self._validate_speaker_function() """
Set up the group chat, including speaker function, conversation history,
agent mapping, and prompt augmentation.
"""
# Initialize conversation history # Initialize conversation history
self.conversation = Conversation(time_enabled=True) self.conversation = Conversation(time_enabled=True)
self._setup_speaker_function()
self.agent_map = create_agent_map(self.agents) self.agent_map = create_agent_map(self.agents)
self._validate_initialization() self._validate_initialization()
@ -350,16 +350,6 @@ class InteractiveGroupChat:
# Validate the speaker function # Validate the speaker function
self._validate_speaker_function() self._validate_speaker_function()
def set_priorities(self, priorities: dict) -> None:
"""
Set agent priorities for priority-based speaking order.
Args:
priorities: Dictionary mapping agent names to priority weights
"""
self.speaker_state["priorities"] = priorities
logger.info(f"Agent priorities set: {priorities}")
def get_available_speaker_functions(self) -> List[str]: def get_available_speaker_functions(self) -> List[str]:
""" """
Get a list of available speaker function names. Get a list of available speaker function names.
@ -519,32 +509,6 @@ 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 _validate_speaker_function(self) -> None:
"""
Validates the speaker function.
Raises:
InvalidSpeakerFunctionError: If the speaker function is invalid
"""
if not callable(self.speaker_function):
raise InvalidSpeakerFunctionError(
"Speaker function must be callable"
)
# Test the speaker function with a dummy list
try:
test_result = self.speaker_function(
["test_agent"], **self.speaker_state
)
if not isinstance(test_result, str):
raise InvalidSpeakerFunctionError(
"Speaker function must return a string"
)
except Exception as e:
raise InvalidSpeakerFunctionError(
f"Speaker function validation failed: {e}"
)
def _validate_initialization(self) -> None: def _validate_initialization(self) -> None:
""" """
Validates the group chat configuration. Validates the group chat configuration.
@ -561,7 +525,10 @@ class InteractiveGroupChat:
raise ValueError("Max loops must be greater than 0") raise ValueError("Max loops must be greater than 0")
def _setup_conversation_context(self) -> None: def _setup_conversation_context(self) -> None:
"""Sets up the initial conversation context with group chat information.""" """
Sets up the initial conversation context with group chat information.
Adds a system message describing the group and its agents.
"""
agent_info = [] agent_info = []
for agent in self.agents: for agent in self.agents:
if isinstance(agent, Agent): if isinstance(agent, Agent):
@ -581,7 +548,10 @@ class InteractiveGroupChat:
self.conversation.add(role="System", content=context) self.conversation.add(role="System", content=context)
def _update_agent_prompts(self) -> None: def _update_agent_prompts(self) -> None:
"""Updates each agent's system prompt with information about other agents and the group chat.""" """
Updates each agent's system prompt with information about other agents and the group chat.
This includes collaborative instructions and @mention usage guidelines.
"""
agent_info = [] agent_info = []
for agent in self.agents: for agent in self.agents:
if isinstance(agent, Agent): if isinstance(agent, Agent):
@ -696,7 +666,7 @@ Remember: You are part of a team. Your response should reflect that you've read,
List[str]: List of mentioned agent names or all agent names if no mentions List[str]: List of mentioned agent names or all agent names if no mentions
Raises: Raises:
InvalidtaskFormatError: If the task format is invalid InvalidTaskFormatError: If the task format is invalid
""" """
try: try:
# Find all @mentions using regex # Find all @mentions using regex
@ -812,6 +782,14 @@ Remember: You are part of a team. Your response should reflect that you've read,
) -> None: ) -> None:
""" """
Process responses using the dynamic speaker function. Process responses using the dynamic speaker function.
Args:
mentioned_agents (List[str]): List of agent names to consider for speaking.
img (Optional[str]): Optional image input for the agents.
imgs (Optional[List[str]]): Optional list of images for the agents.
Returns:
None
""" """
# Get strategy from speaker state (default to sequential) # Get strategy from speaker state (default to sequential)
strategy = self.speaker_state.get("strategy", "sequential") strategy = self.speaker_state.get("strategy", "sequential")
@ -882,6 +860,15 @@ Remember: You are part of a team. Your response should reflect that you've read,
) -> None: ) -> None:
""" """
Process speakers sequentially. Process speakers sequentially.
Args:
speakers (List[str]): List of agent names to process in order.
spoken_agents (set): Set of agent names that have already spoken.
img (Optional[str]): Optional image input for the agents.
imgs (Optional[List[str]]): Optional list of images for the agents.
Returns:
None
""" """
for next_speaker in speakers: for next_speaker in speakers:
if next_speaker in spoken_agents: if next_speaker in spoken_agents:
@ -903,6 +890,15 @@ Remember: You are part of a team. Your response should reflect that you've read,
) -> None: ) -> None:
""" """
Process speakers in parallel. Process speakers in parallel.
Args:
speakers (List[str]): List of agent names to process in parallel.
spoken_agents (set): Set of agent names that have already spoken.
img (Optional[str]): Optional image input for the agents.
imgs (Optional[List[str]]): Optional list of images for the agents.
Returns:
None
""" """
import concurrent.futures import concurrent.futures
@ -939,6 +935,14 @@ Remember: You are part of a team. Your response should reflect that you've read,
) -> None: ) -> None:
""" """
Process responses using a static speaker function. Process responses using a static speaker function.
Args:
mentioned_agents (List[str]): List of agent names to process.
img (Optional[str]): Optional image input for the agents.
imgs (Optional[List[str]]): Optional list of images for the agents.
Returns:
None
""" """
speaking_order = self._get_speaking_order(mentioned_agents) speaking_order = self._get_speaking_order(mentioned_agents)
logger.info(f"Speaking order determined: {speaking_order}") logger.info(f"Speaking order determined: {speaking_order}")
@ -947,6 +951,36 @@ Remember: You are part of a team. Your response should reflect that you've read,
for agent_name in speaking_order: for agent_name in speaking_order:
self._get_agent_response(agent_name, img, imgs) self._get_agent_response(agent_name, img, imgs)
def _process_random_speaker(
self,
mentioned_agents: List[str],
img: Optional[str],
imgs: Optional[List[str]],
) -> None:
"""
Process responses using the random speaker function.
This function randomly selects a single agent from the mentioned agents
to respond to the user query.
"""
# Filter out invalid agents
valid_agents = [
name
for name in mentioned_agents
if name in self.agent_map
]
if not valid_agents:
raise AgentNotFoundError(
"No valid agents found in the conversation"
)
# Randomly select exactly one agent to respond
random_agent = random.choice(valid_agents)
logger.info(f"Random speaker selected: {random_agent}")
# Get response from the randomly selected agent
self._get_agent_response(random_agent, img, imgs)
def run( def run(
self, self,
task: str, task: str,
@ -956,6 +990,17 @@ Remember: You are part of a team. Your response should reflect that you've read,
""" """
Process a task and get responses from agents. If no agents are mentioned, Process a task and get responses from agents. If no agents are mentioned,
randomly selects agents to participate. randomly selects agents to participate.
Args:
task (str): The user input or task to process.
img (Optional[str]): Optional image input for the agents.
imgs (Optional[List[str]]): Optional list of images for the agents.
Returns:
str: The formatted conversation history (format depends on output_type).
Raises:
InteractiveGroupChatError: If an unexpected error occurs.
""" """
try: try:
# Extract mentioned agents (or all agents if none mentioned) # Extract mentioned agents (or all agents if none mentioned)
@ -972,6 +1017,11 @@ Remember: You are part of a team. Your response should reflect that you've read,
self._process_dynamic_speakers( self._process_dynamic_speakers(
mentioned_agents, img, imgs mentioned_agents, img, imgs
) )
elif self.speaker_function == random_speaker:
# Use the specialized function for random_speaker
self._process_random_speaker(
mentioned_agents, img, imgs
)
else: else:
self._process_static_speakers( self._process_static_speakers(
mentioned_agents, img, imgs mentioned_agents, img, imgs
@ -982,11 +1032,21 @@ Remember: You are part of a team. Your response should reflect that you've read,
) )
except Exception as e: except Exception as e:
logger.error(f"Unexpected error: {e}") logger.error(
f"InteractiveGroupChat: Unexpected error: {e} Traceback: {traceback.format_exc()}"
)
raise InteractiveGroupChatError( raise InteractiveGroupChatError(
f"Unexpected error occurred: {str(e)}" f"InteractiveGroupChat: Unexpected error occurred: {str(e)} Traceback: {traceback.format_exc()}"
) )
def __call__(
self,
task: str,
img: Optional[str] = None,
imgs: Optional[List[str]] = None,
):
return self.run(task=task, img=img, imgs=imgs)
def _get_agent_response( def _get_agent_response(
self, self,
agent_name: str, agent_name: str,
@ -997,12 +1057,15 @@ Remember: You are part of a team. Your response should reflect that you've read,
Get response from a specific agent. Get response from a specific agent.
Args: Args:
agent_name: Name of the agent to get response from agent_name (str): Name of the agent to get response from.
img: Optional image for the task img (Optional[str]): Optional image for the task.
imgs: Optional list of images for the task imgs (Optional[List[str]]): Optional list of images for the task.
Returns: Returns:
The agent's response or None if error Optional[str]: The agent's response or None if error.
Raises:
AgentNotFoundError: If the agent is not found.
""" """
agent = self.agent_map.get(agent_name) agent = self.agent_map.get(agent_name)
if not agent: if not agent:
@ -1063,20 +1126,3 @@ Remember: You are part of a collaborative team. Your response should demonstrate
return f"Error: Unable to generate response - {str(e)}" return f"Error: Unable to generate response - {str(e)}"
return None return None
def set_dynamic_strategy(self, strategy: str) -> None:
"""
Set the strategy for the random-dynamic-speaker function.
Args:
strategy: Either "sequential" or "parallel"
- "sequential": Process one agent at a time based on @mentions
- "parallel": Process all mentioned agents simultaneously
"""
if strategy not in ["sequential", "parallel"]:
raise ValueError(
"Strategy must be either 'sequential' or 'parallel'"
)
self.speaker_state["strategy"] = strategy
logger.info(f"Dynamic speaker strategy set to: {strategy}")

File diff suppressed because it is too large Load Diff

@ -1,23 +1,11 @@
import os import os
import subprocess
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from typing import List from typing import List
from loguru import logger
from pydantic import BaseModel from pydantic import BaseModel
try: from openai import OpenAI
from openai import OpenAI
except ImportError:
logger.error(
"OpenAI library not found. Please install the OpenAI library by running 'pip install openai'"
)
import sys
subprocess.run([sys.executable, "-m", "pip", "install", "openai"])
from openai import OpenAI
SUPPORTED_MODELS = [ SUPPORTED_MODELS = [
"o3-mini-2025-1-31", "o3-mini-2025-1-31",

Loading…
Cancel
Save