commit
ff7324a7a9
@ -1,13 +0,0 @@
|
||||
1. make agent api - fastapi
|
||||
2. make agent cron job
|
||||
3. agents that listen that could listen to events
|
||||
4. run on startup, every time the machine starts
|
||||
4. docker
|
||||
5. kubernetes
|
||||
6. aws or google cloud etc
|
||||
|
||||
|
||||
|
||||
user -> build agent -> user now need deploy agent
|
||||
|
||||
FAST
|
||||
@ -0,0 +1,57 @@
|
||||
# Advanced Research
|
||||
|
||||
An enhanced implementation of the orchestrator-worker pattern from Anthropic's paper, "How we built our multi-agent research system", built on top of the bleeding-edge multi-agent framework [swarms](https://github.com/kyegomez/swarms). Our implementation of this advanced research system leverages parallel execution, LLM-as-judge evaluation, and professional report generation with export capabilities.
|
||||
|
||||
**Repository**: [AdvancedResearch](https://github.com/The-Swarm-Corporation/AdvancedResearch)
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip3 install -U advanced-research
|
||||
|
||||
# uv pip install -U advanced-research
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```txt
|
||||
# Exa Search API Key (Required for web search functionality)
|
||||
EXA_API_KEY="your_exa_api_key_here"
|
||||
|
||||
# Anthropic API Key (For Claude models)
|
||||
ANTHROPIC_API_KEY="your_anthropic_api_key_here"
|
||||
|
||||
# OpenAI API Key (For GPT models)
|
||||
OPENAI_API_KEY="your_openai_api_key_here"
|
||||
|
||||
# Worker Agent Configuration
|
||||
WORKER_MODEL_NAME="gpt-4.1"
|
||||
WORKER_MAX_TOKENS=8000
|
||||
|
||||
# Exa Search Configuration
|
||||
EXA_SEARCH_NUM_RESULTS=2
|
||||
EXA_SEARCH_MAX_CHARACTERS=100
|
||||
```
|
||||
|
||||
**Note**: At minimum, you need `EXA_API_KEY` for web search functionality. For LLM functionality, you need either `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```python
|
||||
from advanced_research import AdvancedResearch
|
||||
|
||||
# Initialize the research system
|
||||
research_system = AdvancedResearch(
|
||||
name="AI Research Team",
|
||||
description="Specialized AI research system",
|
||||
max_loops=1,
|
||||
)
|
||||
|
||||
# Run research and get results
|
||||
result = research_system.run(
|
||||
"What are the latest developments in quantum computing?"
|
||||
)
|
||||
print(result)
|
||||
```
|
||||
@ -0,0 +1,111 @@
|
||||
# Browser Automation with Swarms
|
||||
|
||||
This example demonstrates how to use browser automation capabilities within the Swarms framework. The `BrowserUseAgent` class provides a powerful interface for web scraping, navigation, and automated browser interactions using the `browser_use` library. This is particularly useful for tasks that require real-time web data extraction, form filling, or web application testing.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms browser-use python-dotenv langchain-openai
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```txt
|
||||
# OpenAI API Key (Required for LLM functionality)
|
||||
OPENAI_API_KEY="your_openai_api_key_here"
|
||||
```
|
||||
|
||||
## Main Code
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
from browser_use import Agent as BrowserAgent
|
||||
from dotenv import load_dotenv
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
from swarms import Agent
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class BrowserUseAgent:
|
||||
def __init__(self, agent_name: str = "BrowserAgent", agent_description: str = "A browser agent that can navigate the web and perform tasks."):
|
||||
"""
|
||||
Initialize a BrowserAgent with a given name.
|
||||
|
||||
Args:
|
||||
agent_name (str): The name of the browser agent.
|
||||
"""
|
||||
self.agent_name = agent_name
|
||||
self.agent_description = agent_description
|
||||
|
||||
async def browser_agent_test(self, task: str):
|
||||
"""
|
||||
Asynchronously run the browser agent on a given task.
|
||||
|
||||
Args:
|
||||
task (str): The task prompt for the agent.
|
||||
|
||||
Returns:
|
||||
Any: The result of the agent's run method.
|
||||
"""
|
||||
agent = BrowserAgent(
|
||||
task=task,
|
||||
llm=ChatOpenAI(model="gpt-4.1"),
|
||||
)
|
||||
result = await agent.run()
|
||||
return result.model_dump_json(indent=4)
|
||||
|
||||
def run(self, task: str):
|
||||
"""
|
||||
Run the browser agent synchronously on a given task.
|
||||
|
||||
Args:
|
||||
task (str): The task prompt for the agent.
|
||||
|
||||
Returns:
|
||||
Any: The result of the agent's run method.
|
||||
"""
|
||||
return asyncio.run(self.browser_agent_test(task))
|
||||
|
||||
|
||||
|
||||
def browser_agent_tool(task: str):
|
||||
"""
|
||||
Executes a browser automation agent as a callable tool.
|
||||
|
||||
This function instantiates a `BrowserAgent` and runs it synchronously on the provided task prompt.
|
||||
The agent will use a language model to interpret the task, control a browser, and return the results
|
||||
as a JSON-formatted string.
|
||||
|
||||
Args:
|
||||
task (str):
|
||||
A detailed instruction or prompt describing the browser-based task to perform.
|
||||
For example, you can instruct the agent to navigate to a website, extract information,
|
||||
or interact with web elements.
|
||||
|
||||
Returns:
|
||||
str:
|
||||
The result of the browser agent's execution, formatted as a JSON string. The output
|
||||
typically includes the agent's findings, extracted data, and any relevant observations
|
||||
from the automated browser session.
|
||||
|
||||
Example:
|
||||
result = browser_agent_tool(
|
||||
"Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours."
|
||||
)
|
||||
print(result)
|
||||
"""
|
||||
return BrowserAgent().run(task)
|
||||
|
||||
|
||||
|
||||
agent = Agent(
|
||||
name = "Browser Agent",
|
||||
model_name = "gpt-4.1",
|
||||
tools = [browser_agent_tool],
|
||||
)
|
||||
|
||||
agent.run("Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours.")
|
||||
```
|
||||
@ -0,0 +1,48 @@
|
||||
# Web Search with Exa
|
||||
|
||||
|
||||
Exa is a powerful web search API that provides real-time access to current web information. It allows AI agents to search the internet and retrieve up-to-date information on any topic, making it an essential tool for agents that need current knowledge beyond their training data.
|
||||
|
||||
Key features of Exa:
|
||||
|
||||
| Feature | Description |
|
||||
|--------------------------|--------------------------------------------------------------------|
|
||||
| **Real-time search** | Access the latest information from the web |
|
||||
| **Semantic search** | Find relevant results using natural language queries |
|
||||
| **Comprehensive coverage** | Search across billions of web pages |
|
||||
| **Structured results** | Get clean, formatted search results for easy processing |
|
||||
| **API integration** | Simple REST API for seamless integration with AI applications |
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip3 install -U swarms swarms-tools
|
||||
```
|
||||
|
||||
## ENV
|
||||
|
||||
```txt
|
||||
# Get your API key from exa
|
||||
EXA_SEARCH_API=""
|
||||
|
||||
OPENAI_API_KEY=""
|
||||
|
||||
WORKSPACE_DIR=""
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```python
|
||||
from swarms import Agent
|
||||
from swarms_tools import exa_search
|
||||
|
||||
|
||||
agent = Agent(
|
||||
name="Exa Search Agent",
|
||||
llm="gpt-4o-mini",
|
||||
tools=[exa_search],
|
||||
)
|
||||
|
||||
out = agent.run("What are the latest experimental treatments for diabetes?")
|
||||
print(out)
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,11 @@
|
||||
from swarms import Agent
|
||||
from swarms_tools import exa_search
|
||||
|
||||
|
||||
agent = Agent(
|
||||
name="Exa Search Agent",
|
||||
llm="gpt-4o-mini",
|
||||
tools=[exa_search],
|
||||
)
|
||||
|
||||
agent.run("What are the latest experimental treatments for diabetes?")
|
||||
@ -1,42 +0,0 @@
|
||||
import asyncio
|
||||
|
||||
from browser_use import Agent
|
||||
from dotenv import load_dotenv
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
from swarms import ConcurrentWorkflow
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class BrowserAgent:
|
||||
def __init__(self, agent_name: str = "BrowserAgent"):
|
||||
self.agent_name = agent_name
|
||||
|
||||
async def browser_agent_test(self, task: str):
|
||||
agent = Agent(
|
||||
task=task,
|
||||
llm=ChatOpenAI(model="gpt-4o"),
|
||||
)
|
||||
result = await agent.run()
|
||||
return result
|
||||
|
||||
def run(self, task: str):
|
||||
return asyncio.run(self.browser_agent_test(task))
|
||||
|
||||
|
||||
swarm = ConcurrentWorkflow(
|
||||
agents=[BrowserAgent() for _ in range(10)],
|
||||
)
|
||||
|
||||
swarm.run(
|
||||
"""Please navigate to chat.com and engage in a detailed technical discussion with ChatGPT about the following specific aspects of future high-energy physics:
|
||||
|
||||
1. The potential discoveries and physics reach of the Future Circular Collider (FCC) compared to the LHC
|
||||
2. Theoretical predictions for supersymmetric particles and dark matter candidates at energy scales above 100 TeV
|
||||
3. Novel detector technologies needed for future collider experiments, particularly for tracking and calorimetry
|
||||
4. The role of machine learning and quantum computing in analyzing high-energy physics data
|
||||
5. Challenges and proposed solutions for beam focusing and acceleration at extremely high energies
|
||||
|
||||
Please document the key insights and technical details from this discussion."""
|
||||
)
|
||||
@ -1,46 +0,0 @@
|
||||
from swarms.utils.vllm_wrapper import VLLMWrapper
|
||||
|
||||
|
||||
def main():
|
||||
# Initialize the vLLM wrapper with a model
|
||||
# Note: You'll need to have the model downloaded or specify a HuggingFace model ID
|
||||
llm = VLLMWrapper(
|
||||
model_name="meta-llama/Llama-2-7b-chat-hf", # Replace with your model path or HF model ID
|
||||
temperature=0.7,
|
||||
max_tokens=1000,
|
||||
)
|
||||
|
||||
# Example task
|
||||
task = "What are the benefits of using vLLM for inference?"
|
||||
|
||||
# Run inference
|
||||
response = llm.run(task)
|
||||
print("Response:", response)
|
||||
|
||||
# Example with system prompt
|
||||
llm_with_system = VLLMWrapper(
|
||||
model_name="meta-llama/Llama-2-7b-chat-hf", # Replace with your model path or HF model ID
|
||||
system_prompt="You are a helpful AI assistant that provides concise answers.",
|
||||
temperature=0.7,
|
||||
)
|
||||
|
||||
# Run inference with system prompt
|
||||
response = llm_with_system.run(task)
|
||||
print("\nResponse with system prompt:", response)
|
||||
|
||||
# Example with batched inference
|
||||
tasks = [
|
||||
"What is vLLM?",
|
||||
"How does vLLM improve inference speed?",
|
||||
"What are the main features of vLLM?",
|
||||
]
|
||||
|
||||
responses = llm.batched_run(tasks, batch_size=2)
|
||||
print("\nBatched responses:")
|
||||
for task, response in zip(tasks, responses):
|
||||
print(f"\nTask: {task}")
|
||||
print(f"Response: {response}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,148 +0,0 @@
|
||||
import concurrent.futures
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
try:
|
||||
from vllm import LLM, SamplingParams
|
||||
except ImportError:
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
print("Installing vllm")
|
||||
subprocess.check_call(
|
||||
[sys.executable, "-m", "pip", "install", "-U", "vllm"]
|
||||
)
|
||||
print("vllm installed")
|
||||
from vllm import LLM, SamplingParams
|
||||
|
||||
|
||||
class VLLMWrapper:
|
||||
"""
|
||||
A wrapper class for vLLM that provides a similar interface to LiteLLM.
|
||||
This class handles model initialization and inference using vLLM.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model_name: str = "meta-llama/Llama-2-7b-chat-hf",
|
||||
system_prompt: str | None = None,
|
||||
stream: bool = False,
|
||||
temperature: float = 0.5,
|
||||
max_tokens: int = 4000,
|
||||
max_completion_tokens: int = 4000,
|
||||
tools_list_dictionary: list[dict[str, Any]] | None = None,
|
||||
tool_choice: str = "auto",
|
||||
parallel_tool_calls: bool = False,
|
||||
*args,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialize the vLLM wrapper with the given parameters.
|
||||
|
||||
Args:
|
||||
model_name (str): The name of the model to use. Defaults to "meta-llama/Llama-2-7b-chat-hf".
|
||||
system_prompt (str, optional): The system prompt to use. Defaults to None.
|
||||
stream (bool): Whether to stream the output. Defaults to False.
|
||||
temperature (float): The temperature for sampling. Defaults to 0.5.
|
||||
max_tokens (int): The maximum number of tokens to generate. Defaults to 4000.
|
||||
max_completion_tokens (int): The maximum number of completion tokens. Defaults to 4000.
|
||||
tools_list_dictionary (List[Dict[str, Any]], optional): List of available tools. Defaults to None.
|
||||
tool_choice (str): How to choose tools. Defaults to "auto".
|
||||
parallel_tool_calls (bool): Whether to allow parallel tool calls. Defaults to False.
|
||||
"""
|
||||
self.model_name = model_name
|
||||
self.system_prompt = system_prompt
|
||||
self.stream = stream
|
||||
self.temperature = temperature
|
||||
self.max_tokens = max_tokens
|
||||
self.max_completion_tokens = max_completion_tokens
|
||||
self.tools_list_dictionary = tools_list_dictionary
|
||||
self.tool_choice = tool_choice
|
||||
self.parallel_tool_calls = parallel_tool_calls
|
||||
|
||||
# Initialize vLLM
|
||||
self.llm = LLM(model=model_name, **kwargs)
|
||||
self.sampling_params = SamplingParams(
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
|
||||
def _prepare_prompt(self, task: str) -> str:
|
||||
"""
|
||||
Prepare the prompt for the given task.
|
||||
|
||||
Args:
|
||||
task (str): The task to prepare the prompt for.
|
||||
|
||||
Returns:
|
||||
str: The prepared prompt.
|
||||
"""
|
||||
if self.system_prompt:
|
||||
return f"{self.system_prompt}\n\nUser: {task}\nAssistant:"
|
||||
return f"User: {task}\nAssistant:"
|
||||
|
||||
def run(self, task: str, *args, **kwargs) -> str:
|
||||
"""
|
||||
Run the model for the given task.
|
||||
|
||||
Args:
|
||||
task (str): The task to run the model for.
|
||||
*args: Additional positional arguments.
|
||||
**kwargs: Additional keyword arguments.
|
||||
|
||||
Returns:
|
||||
str: The model's response.
|
||||
"""
|
||||
try:
|
||||
prompt = self._prepare_prompt(task)
|
||||
|
||||
outputs = self.llm.generate(prompt, self.sampling_params)
|
||||
response = outputs[0].outputs[0].text.strip()
|
||||
|
||||
return response
|
||||
|
||||
except Exception as error:
|
||||
logger.error(f"Error in VLLMWrapper: {error}")
|
||||
raise error
|
||||
|
||||
def __call__(self, task: str, *args, **kwargs) -> str:
|
||||
"""
|
||||
Call the model for the given task.
|
||||
|
||||
Args:
|
||||
task (str): The task to run the model for.
|
||||
*args: Additional positional arguments.
|
||||
**kwargs: Additional keyword arguments.
|
||||
|
||||
Returns:
|
||||
str: The model's response.
|
||||
"""
|
||||
return self.run(task, *args, **kwargs)
|
||||
|
||||
def batched_run(
|
||||
self, tasks: list[str], batch_size: int = 10
|
||||
) -> list[str]:
|
||||
"""
|
||||
Run the model for multiple tasks in batches.
|
||||
|
||||
Args:
|
||||
tasks (List[str]): List of tasks to run.
|
||||
batch_size (int): Size of each batch. Defaults to 10.
|
||||
|
||||
Returns:
|
||||
List[str]: List of model responses.
|
||||
"""
|
||||
# Calculate the worker count based on 95% of available CPU cores
|
||||
num_workers = max(1, int((os.cpu_count() or 1) * 0.95))
|
||||
with concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=num_workers
|
||||
) as executor:
|
||||
futures = [
|
||||
executor.submit(self.run, task) for task in tasks
|
||||
]
|
||||
return [
|
||||
future.result()
|
||||
for future in concurrent.futures.as_completed(futures)
|
||||
]
|
||||
@ -1,114 +0,0 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Swarm imports
|
||||
from swarms.structs.agent import Agent
|
||||
from swarms.structs.hiearchical_swarm import (
|
||||
HierarchicalSwarm,
|
||||
SwarmSpec,
|
||||
OrganizationalUnit,
|
||||
)
|
||||
from swarms.utils.function_caller_model import OpenAIFunctionCaller
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Create the agents first
|
||||
research_manager = Agent(
|
||||
agent_name="Research Manager",
|
||||
agent_description="Manages research operations and coordinates research tasks",
|
||||
system_prompt="You are a research manager responsible for overseeing research projects and coordinating research efforts.",
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
data_analyst = Agent(
|
||||
agent_name="Data Analyst",
|
||||
agent_description="Analyzes data and generates insights",
|
||||
system_prompt="You are a data analyst specializing in processing and analyzing data to extract meaningful insights.",
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
research_assistant = Agent(
|
||||
agent_name="Research Assistant",
|
||||
agent_description="Assists with research tasks and data collection",
|
||||
system_prompt="You are a research assistant who helps gather information and support research activities.",
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
development_manager = Agent(
|
||||
agent_name="Development Manager",
|
||||
agent_description="Manages development projects and coordinates development tasks",
|
||||
system_prompt="You are a development manager responsible for overseeing software development projects and coordinating development efforts.",
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
software_engineer = Agent(
|
||||
agent_name="Software Engineer",
|
||||
agent_description="Develops and implements software solutions",
|
||||
system_prompt="You are a software engineer specializing in building and implementing software solutions.",
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
qa_engineer = Agent(
|
||||
agent_name="QA Engineer",
|
||||
agent_description="Tests and ensures quality of software",
|
||||
system_prompt="You are a QA engineer responsible for testing software and ensuring its quality.",
|
||||
model_name="gpt-4o",
|
||||
)
|
||||
|
||||
# Create organizational units with the agents
|
||||
research_unit = OrganizationalUnit(
|
||||
name="Research Unit",
|
||||
description="Handles research and analysis tasks",
|
||||
manager=research_manager,
|
||||
members=[data_analyst, research_assistant],
|
||||
)
|
||||
|
||||
development_unit = OrganizationalUnit(
|
||||
name="Development Unit",
|
||||
description="Handles development and implementation tasks",
|
||||
manager=development_manager,
|
||||
members=[software_engineer, qa_engineer],
|
||||
)
|
||||
|
||||
# Initialize the director agent
|
||||
director = OpenAIFunctionCaller(
|
||||
model_name="gpt-4o",
|
||||
system_prompt=(
|
||||
"As the Director of this Hierarchical Agent Swarm, you are responsible for:\n"
|
||||
"1. Analyzing tasks and breaking them down into subtasks\n"
|
||||
"2. Assigning tasks to appropriate organizational units\n"
|
||||
"3. Coordinating communication between units\n"
|
||||
"4. Ensuring tasks are completed efficiently and effectively\n"
|
||||
"5. Providing feedback and guidance to units as needed\n\n"
|
||||
"Your decisions should be based on the capabilities of each unit and the requirements of the task."
|
||||
),
|
||||
api_key=os.getenv("OPENAI_API_KEY"),
|
||||
temperature=0.5,
|
||||
base_model=SwarmSpec,
|
||||
max_tokens=10000,
|
||||
)
|
||||
|
||||
# Initialize the hierarchical swarm with the organizational units
|
||||
swarm = HierarchicalSwarm(
|
||||
name="Example Hierarchical Swarm",
|
||||
description="A hierarchical swarm demonstrating multi-unit collaboration",
|
||||
director=director,
|
||||
organizational_units=[research_unit, development_unit],
|
||||
max_loops=2, # Allow for feedback and iteration
|
||||
output_type="dict",
|
||||
)
|
||||
|
||||
# Example task to run through the swarm
|
||||
task = """
|
||||
Develop a comprehensive market analysis for a new AI-powered productivity tool.
|
||||
The analysis should include:
|
||||
1. Market research and competitor analysis
|
||||
2. User needs and pain points
|
||||
3. Technical feasibility assessment
|
||||
4. Implementation recommendations
|
||||
"""
|
||||
|
||||
# Run the task through the swarm
|
||||
result = swarm.run(task)
|
||||
print("Swarm Results:", result)
|
||||
@ -1,118 +0,0 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from swarms import Agent, SequentialWorkflow
|
||||
from swarm_models import OpenAIChat
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
api_key = os.getenv("GROQ_API_KEY")
|
||||
|
||||
# Model
|
||||
model = OpenAIChat(
|
||||
openai_api_base="https://api.groq.com/openai/v1",
|
||||
openai_api_key=api_key,
|
||||
model_name="llama-3.1-70b-versatile",
|
||||
temperature=0.1,
|
||||
)
|
||||
|
||||
|
||||
# Initialize specialized agents
|
||||
data_extractor_agent = Agent(
|
||||
agent_name="Data-Extractor",
|
||||
system_prompt=None,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="data_extractor_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
summarizer_agent = Agent(
|
||||
agent_name="Document-Summarizer",
|
||||
system_prompt=None,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="summarizer_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
financial_analyst_agent = Agent(
|
||||
agent_name="Financial-Analyst",
|
||||
system_prompt=None,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="financial_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
market_analyst_agent = Agent(
|
||||
agent_name="Market-Analyst",
|
||||
system_prompt=None,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="market_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
operational_analyst_agent = Agent(
|
||||
agent_name="Operational-Analyst",
|
||||
system_prompt=None,
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="operational_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
# Initialize the SwarmRouter
|
||||
router = SequentialWorkflow(
|
||||
name="pe-document-analysis-swarm",
|
||||
description="Analyze documents for private equity due diligence and investment decision-making",
|
||||
max_loops=1,
|
||||
agents=[
|
||||
data_extractor_agent,
|
||||
summarizer_agent,
|
||||
financial_analyst_agent,
|
||||
market_analyst_agent,
|
||||
operational_analyst_agent,
|
||||
],
|
||||
output_type="all",
|
||||
)
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
# Run a comprehensive private equity document analysis task
|
||||
result = router.run(
|
||||
"Where is the best place to find template term sheets for series A startups. Provide links and references",
|
||||
img=None,
|
||||
)
|
||||
print(result)
|
||||
@ -1,143 +0,0 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from swarms import Agent, SequentialWorkflow
|
||||
from swarm_models import OpenAIChat
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Get the OpenAI API key from the environment variable
|
||||
api_key = os.getenv("GROQ_API_KEY")
|
||||
|
||||
# Model
|
||||
model = OpenAIChat(
|
||||
openai_api_base="https://api.groq.com/openai/v1",
|
||||
openai_api_key=api_key,
|
||||
model_name="llama-3.1-70b-versatile",
|
||||
temperature=0.1,
|
||||
)
|
||||
|
||||
|
||||
# Initialize specialized agents
|
||||
data_extractor_agent = Agent(
|
||||
agent_name="Data-Extractor",
|
||||
system_prompt="""You are a data extraction specialist. Your role is to:
|
||||
1. Extract key information, data points, and metrics from documents
|
||||
2. Identify and pull out important facts, figures, and statistics
|
||||
3. Structure extracted data in a clear, organized format
|
||||
4. Flag any inconsistencies or missing data
|
||||
5. Ensure accuracy in data extraction while maintaining context""",
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="data_extractor_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
summarizer_agent = Agent(
|
||||
agent_name="Document-Summarizer",
|
||||
system_prompt="""You are a document summarization expert. Your role is to:
|
||||
1. Create concise, comprehensive summaries of documents
|
||||
2. Highlight key points and main takeaways
|
||||
3. Maintain the essential meaning while reducing length
|
||||
4. Structure summaries in a logical, readable format
|
||||
5. Identify and emphasize critical insights""",
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="summarizer_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
financial_analyst_agent = Agent(
|
||||
agent_name="Financial-Analyst",
|
||||
system_prompt="""You are a financial analysis expert. Your role is to:
|
||||
1. Analyze financial statements and metrics
|
||||
2. Evaluate company valuations and financial projections
|
||||
3. Assess financial risks and opportunities
|
||||
4. Provide insights on financial performance and health
|
||||
5. Make recommendations based on financial analysis""",
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="financial_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
market_analyst_agent = Agent(
|
||||
agent_name="Market-Analyst",
|
||||
system_prompt="""You are a market analysis expert. Your role is to:
|
||||
1. Analyze market trends and dynamics
|
||||
2. Evaluate competitive landscape and market positioning
|
||||
3. Identify market opportunities and threats
|
||||
4. Assess market size and growth potential
|
||||
5. Provide strategic market insights and recommendations""",
|
||||
llm=model,
|
||||
max_loops=1,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="market_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
operational_analyst_agent = Agent(
|
||||
agent_name="Operational-Analyst",
|
||||
system_prompt="""You are an operational analysis expert. Your role is to:
|
||||
1. Analyze business operations and processes
|
||||
2. Evaluate operational efficiency and effectiveness
|
||||
3. Identify operational risks and opportunities
|
||||
4. Assess scalability and growth potential
|
||||
5. Provide recommendations for operational improvements""",
|
||||
llm=model,
|
||||
max_loops=2,
|
||||
autosave=True,
|
||||
verbose=True,
|
||||
dynamic_temperature_enabled=True,
|
||||
saved_state_path="operational_analyst_agent.json",
|
||||
user_name="pe_firm",
|
||||
retry_attempts=1,
|
||||
context_length=200000,
|
||||
output_type="string",
|
||||
)
|
||||
|
||||
# Initialize the SwarmRouter
|
||||
router = SequentialWorkflow(
|
||||
name="pe-document-analysis-swarm",
|
||||
description="Analyze documents for private equity due diligence and investment decision-making",
|
||||
max_loops=1,
|
||||
agents=[
|
||||
data_extractor_agent,
|
||||
summarizer_agent,
|
||||
financial_analyst_agent,
|
||||
market_analyst_agent,
|
||||
operational_analyst_agent,
|
||||
],
|
||||
output_type="all",
|
||||
)
|
||||
|
||||
# Example usage
|
||||
if __name__ == "__main__":
|
||||
# Run a comprehensive private equity document analysis task
|
||||
result = router.run(
|
||||
"Where is the best place to find template term sheets for series A startups. Provide links and references",
|
||||
no_use_clusterops=True,
|
||||
)
|
||||
print(result)
|
||||
@ -0,0 +1,90 @@
|
||||
import asyncio
|
||||
|
||||
from browser_use import Agent as BrowserAgent
|
||||
from dotenv import load_dotenv
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
from swarms import Agent
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class BrowserUseAgent:
|
||||
def __init__(self, agent_name: str = "BrowserAgent", agent_description: str = "A browser agent that can navigate the web and perform tasks."):
|
||||
"""
|
||||
Initialize a BrowserAgent with a given name.
|
||||
|
||||
Args:
|
||||
agent_name (str): The name of the browser agent.
|
||||
"""
|
||||
self.agent_name = agent_name
|
||||
self.agent_description = agent_description
|
||||
|
||||
async def browser_agent_test(self, task: str):
|
||||
"""
|
||||
Asynchronously run the browser agent on a given task.
|
||||
|
||||
Args:
|
||||
task (str): The task prompt for the agent.
|
||||
|
||||
Returns:
|
||||
Any: The result of the agent's run method.
|
||||
"""
|
||||
agent = BrowserAgent(
|
||||
task=task,
|
||||
llm=ChatOpenAI(model="gpt-4.1"),
|
||||
)
|
||||
result = await agent.run()
|
||||
return result.model_dump_json(indent=4)
|
||||
|
||||
def run(self, task: str):
|
||||
"""
|
||||
Run the browser agent synchronously on a given task.
|
||||
|
||||
Args:
|
||||
task (str): The task prompt for the agent.
|
||||
|
||||
Returns:
|
||||
Any: The result of the agent's run method.
|
||||
"""
|
||||
return asyncio.run(self.browser_agent_test(task))
|
||||
|
||||
|
||||
|
||||
def browser_agent_tool(task: str):
|
||||
"""
|
||||
Executes a browser automation agent as a callable tool.
|
||||
|
||||
This function instantiates a `BrowserAgent` and runs it synchronously on the provided task prompt.
|
||||
The agent will use a language model to interpret the task, control a browser, and return the results
|
||||
as a JSON-formatted string.
|
||||
|
||||
Args:
|
||||
task (str):
|
||||
A detailed instruction or prompt describing the browser-based task to perform.
|
||||
For example, you can instruct the agent to navigate to a website, extract information,
|
||||
or interact with web elements.
|
||||
|
||||
Returns:
|
||||
str:
|
||||
The result of the browser agent's execution, formatted as a JSON string. The output
|
||||
typically includes the agent's findings, extracted data, and any relevant observations
|
||||
from the automated browser session.
|
||||
|
||||
Example:
|
||||
result = browser_agent_tool(
|
||||
"Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours."
|
||||
)
|
||||
print(result)
|
||||
"""
|
||||
return BrowserAgent().run(task)
|
||||
|
||||
|
||||
|
||||
agent = Agent(
|
||||
name = "Browser Agent",
|
||||
model_name = "gpt-4.1",
|
||||
tools = [browser_agent_tool],
|
||||
)
|
||||
|
||||
agent.run("Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours.")
|
||||
@ -0,0 +1,67 @@
|
||||
import asyncio
|
||||
|
||||
from browser_use import Agent
|
||||
from dotenv import load_dotenv
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
from swarms import ConcurrentWorkflow
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
class BrowserAgent:
|
||||
def __init__(self, agent_name: str = "BrowserAgent"):
|
||||
"""
|
||||
Initialize a BrowserAgent with a given name.
|
||||
|
||||
Args:
|
||||
agent_name (str): The name of the browser agent.
|
||||
"""
|
||||
self.agent_name = agent_name
|
||||
|
||||
async def browser_agent_test(self, task: str):
|
||||
"""
|
||||
Asynchronously run the browser agent on a given task.
|
||||
|
||||
Args:
|
||||
task (str): The task prompt for the agent.
|
||||
|
||||
Returns:
|
||||
Any: The result of the agent's run method.
|
||||
"""
|
||||
agent = Agent(
|
||||
task=task,
|
||||
llm=ChatOpenAI(model="gpt-4.1"),
|
||||
)
|
||||
result = await agent.run()
|
||||
return result.model_dump_json(indent=4)
|
||||
|
||||
def run(self, task: str):
|
||||
"""
|
||||
Run the browser agent synchronously on a given task.
|
||||
|
||||
Args:
|
||||
task (str): The task prompt for the agent.
|
||||
|
||||
Returns:
|
||||
Any: The result of the agent's run method.
|
||||
"""
|
||||
return asyncio.run(self.browser_agent_test(task))
|
||||
|
||||
|
||||
swarm = ConcurrentWorkflow(
|
||||
agents=[BrowserAgent() for _ in range(10)],
|
||||
)
|
||||
|
||||
swarm.run(
|
||||
"""Please navigate to https://www.coingecko.com and identify the best performing cryptocurrency coin over the past 24 hours.
|
||||
|
||||
Your task is to:
|
||||
1. Go to the main page of CoinGecko.
|
||||
2. Locate the list of coins and their performance metrics.
|
||||
3. Determine which coin has the highest positive percentage change in price over the last 24 hours.
|
||||
4. Report the name, symbol, and 24h percentage gain of this top-performing coin.
|
||||
5. Briefly describe any notable trends or observations about this coin's recent performance.
|
||||
|
||||
Please provide your findings in a clear and concise summary."""
|
||||
)
|
||||
@ -0,0 +1,5 @@
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
def swarm_id():
|
||||
return f"swarm-{uuid4().hex}"
|
||||
@ -1,5 +0,0 @@
|
||||
import uuid
|
||||
|
||||
|
||||
def generate_swarm_id():
|
||||
return f"swarm-{uuid.uuid4().hex}"
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,19 @@
|
||||
import os
|
||||
|
||||
|
||||
def check_swarms_api_key():
|
||||
"""
|
||||
Check if the Swarms API key is set.
|
||||
|
||||
Returns:
|
||||
str: The value of the SWARMS_API_KEY environment variable.
|
||||
|
||||
Raises:
|
||||
ValueError: If the SWARMS_API_KEY environment variable is not set.
|
||||
"""
|
||||
if os.getenv("SWARMS_API_KEY") is None:
|
||||
raise ValueError(
|
||||
"Swarms API key is not set. Please set the SWARMS_API_KEY environment variable. "
|
||||
"You can get your key here: https://swarms.world/platform/api-keys"
|
||||
)
|
||||
return os.getenv("SWARMS_API_KEY")
|
||||
@ -0,0 +1,549 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script demonstrating markdown output functionality with a real swarm
|
||||
Uses the current state of formatter.py to show agent markdown output capabilities
|
||||
"""
|
||||
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
from swarms import Agent
|
||||
from swarms.structs import (
|
||||
SequentialWorkflow,
|
||||
ConcurrentWorkflow,
|
||||
GroupChat,
|
||||
)
|
||||
from swarms.utils.formatter import Formatter
|
||||
|
||||
|
||||
class MarkdownTestSwarm:
|
||||
"""A test swarm that demonstrates markdown output capabilities"""
|
||||
|
||||
def __init__(self):
|
||||
self.formatter = Formatter(markdown=True)
|
||||
self.setup_agents()
|
||||
self.setup_swarm()
|
||||
|
||||
def setup_agents(self):
|
||||
"""Setup specialized agents for markdown testing"""
|
||||
|
||||
# Research Agent - Generates structured markdown reports
|
||||
self.research_agent = Agent(
|
||||
agent_name="Research Agent",
|
||||
system_prompt="""You are a research specialist. When given a topic, create a comprehensive markdown report with:
|
||||
- Clear headers and subheaders
|
||||
- Code examples when relevant
|
||||
- Bullet points and numbered lists
|
||||
- Bold and italic text for emphasis
|
||||
- Tables for data comparison
|
||||
- Code blocks with syntax highlighting
|
||||
|
||||
Always format your response as clean markdown with proper structure.""",
|
||||
model_name="gpt-4o-mini", # Use a more capable model
|
||||
temperature=0.7,
|
||||
max_tokens=4000,
|
||||
max_loops=1,
|
||||
context_length=8000, # Limit context to prevent overflow
|
||||
return_history=False, # Don't return history to reduce context
|
||||
)
|
||||
|
||||
# Code Analysis Agent - Generates code-heavy markdown
|
||||
self.code_agent = Agent(
|
||||
agent_name="Code Analysis Agent",
|
||||
system_prompt="""You are a code analysis specialist. When given code or programming concepts, create markdown documentation with:
|
||||
- Syntax-highlighted code blocks
|
||||
- Function documentation
|
||||
- Code examples
|
||||
- Performance analysis
|
||||
- Best practices
|
||||
|
||||
Use proper markdown formatting with code blocks, inline code, and structured content.""",
|
||||
model_name="gpt-4o-mini", # Use a more capable model
|
||||
temperature=0.5,
|
||||
max_tokens=4000,
|
||||
max_loops=1,
|
||||
context_length=8000, # Limit context to prevent overflow
|
||||
return_history=False, # Don't return history to reduce context
|
||||
)
|
||||
|
||||
# Data Visualization Agent - Creates data-focused markdown
|
||||
self.data_agent = Agent(
|
||||
agent_name="Data Visualization Agent",
|
||||
system_prompt="""You are a data visualization specialist. When given data or analysis requests, create markdown reports with:
|
||||
- Data tables
|
||||
- Statistical analysis
|
||||
- Charts and graphs descriptions
|
||||
- Key insights with bold formatting
|
||||
- Recommendations in structured lists
|
||||
|
||||
Format everything as clean, readable markdown.""",
|
||||
model_name="gpt-4o-mini", # Use a more capable model
|
||||
temperature=0.6,
|
||||
max_tokens=4000,
|
||||
max_loops=1,
|
||||
context_length=8000, # Limit context to prevent overflow
|
||||
return_history=False, # Don't return history to reduce context
|
||||
)
|
||||
|
||||
def setup_swarm(self):
|
||||
"""Setup the swarm with the agents"""
|
||||
# Create different swarm types for testing
|
||||
self.sequential_swarm = SequentialWorkflow(
|
||||
name="Markdown Test Sequential",
|
||||
description="Sequential workflow for markdown testing",
|
||||
agents=[
|
||||
self.research_agent,
|
||||
self.code_agent,
|
||||
self.data_agent,
|
||||
],
|
||||
max_loops=1, # Reduce loops to prevent context overflow
|
||||
)
|
||||
|
||||
self.concurrent_swarm = ConcurrentWorkflow(
|
||||
name="Markdown Test Concurrent",
|
||||
description="Concurrent workflow for markdown testing",
|
||||
agents=[
|
||||
self.research_agent,
|
||||
self.code_agent,
|
||||
self.data_agent,
|
||||
],
|
||||
max_loops=1, # Reduce loops to prevent context overflow
|
||||
)
|
||||
|
||||
self.groupchat_swarm = GroupChat(
|
||||
name="Markdown Test Group Chat",
|
||||
description="A group chat for testing markdown output",
|
||||
agents=[
|
||||
self.research_agent,
|
||||
self.code_agent,
|
||||
self.data_agent,
|
||||
],
|
||||
max_loops=1, # Reduce loops to prevent context overflow
|
||||
)
|
||||
|
||||
# Default swarm for main tests
|
||||
self.swarm = self.sequential_swarm
|
||||
|
||||
def test_basic_markdown_output(self):
|
||||
"""Test basic markdown output with a simple topic"""
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 1: Basic Markdown Output")
|
||||
print("=" * 60)
|
||||
|
||||
topic = "Python Web Development with FastAPI"
|
||||
|
||||
self.formatter.print_panel(
|
||||
f"Starting research on: {topic}",
|
||||
title="Research Topic",
|
||||
style="bold blue",
|
||||
)
|
||||
|
||||
# Run the research agent
|
||||
result = self.research_agent.run(topic)
|
||||
|
||||
self.formatter.print_markdown(
|
||||
result, title="Research Report", border_style="green"
|
||||
)
|
||||
|
||||
def test_code_analysis_markdown(self):
|
||||
"""Test markdown output with code analysis"""
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 2: Code Analysis Markdown")
|
||||
print("=" * 60)
|
||||
|
||||
code_sample = """
|
||||
def fibonacci(n):
|
||||
if n <= 1:
|
||||
return n
|
||||
return fibonacci(n-1) + fibonacci(n-2)
|
||||
|
||||
# Test the function
|
||||
for i in range(10):
|
||||
print(fibonacci(i))
|
||||
"""
|
||||
|
||||
self.formatter.print_panel(
|
||||
"Analyzing Python code sample",
|
||||
title="Code Analysis",
|
||||
style="bold cyan",
|
||||
)
|
||||
|
||||
# Run the code analysis agent
|
||||
result = self.code_agent.run(
|
||||
f"Analyze this Python code and provide improvements:\n\n{code_sample}"
|
||||
)
|
||||
|
||||
self.formatter.print_markdown(
|
||||
result,
|
||||
title="Code Analysis Report",
|
||||
border_style="yellow",
|
||||
)
|
||||
|
||||
def test_data_analysis_markdown(self):
|
||||
"""Test markdown output with data analysis"""
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 3: Data Analysis Markdown")
|
||||
print("=" * 60)
|
||||
|
||||
data_request = """
|
||||
Analyze the following dataset:
|
||||
- Sales: $1.2M (Q1), $1.5M (Q2), $1.8M (Q3), $2.1M (Q4)
|
||||
- Growth Rate: 8%, 12%, 15%, 18%
|
||||
- Customer Count: 1000, 1200, 1400, 1600
|
||||
|
||||
Provide insights and recommendations in markdown format.
|
||||
"""
|
||||
|
||||
self.formatter.print_panel(
|
||||
"Analyzing quarterly business data",
|
||||
title="Data Analysis",
|
||||
style="bold magenta",
|
||||
)
|
||||
|
||||
# Run the data analysis agent
|
||||
result = self.data_agent.run(data_request)
|
||||
|
||||
self.formatter.print_markdown(
|
||||
result, title="Data Analysis Report", border_style="red"
|
||||
)
|
||||
|
||||
def test_swarm_collaboration_markdown(self):
|
||||
"""Test markdown output with swarm collaboration"""
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 4: Swarm Collaboration Markdown")
|
||||
print("=" * 60)
|
||||
|
||||
complex_topic = """
|
||||
Create a comprehensive guide on building a machine learning pipeline that includes:
|
||||
1. Data preprocessing techniques
|
||||
2. Model selection strategies
|
||||
3. Performance evaluation metrics
|
||||
4. Deployment considerations
|
||||
|
||||
Each agent should contribute their expertise and the final output should be well-formatted markdown.
|
||||
"""
|
||||
|
||||
self.formatter.print_panel(
|
||||
"Swarm collaboration on ML pipeline guide",
|
||||
title="Swarm Task",
|
||||
style="bold green",
|
||||
)
|
||||
|
||||
# Run the swarm
|
||||
results = self.swarm.run(complex_topic)
|
||||
|
||||
# Display individual agent results
|
||||
# SequentialWorkflow returns a list of results, not a dict
|
||||
for i, result in enumerate(results, 1):
|
||||
agent_name = f"Agent {i}"
|
||||
|
||||
# Handle different result types
|
||||
if isinstance(result, dict):
|
||||
# Extract the output from dict result
|
||||
result_content = result.get("output", str(result))
|
||||
else:
|
||||
result_content = str(result)
|
||||
self.formatter.print_markdown(
|
||||
result_content,
|
||||
title=f"Agent {i}: {agent_name}",
|
||||
border_style="blue",
|
||||
)
|
||||
|
||||
def test_markdown_toggle_functionality(self):
|
||||
"""Test the markdown enable/disable functionality"""
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 5: Markdown Toggle Functionality")
|
||||
print("=" * 60)
|
||||
|
||||
test_content = """
|
||||
# Test Content
|
||||
|
||||
This is a **bold** test with `inline code`.
|
||||
|
||||
## Code Block
|
||||
```python
|
||||
def test_function():
|
||||
return "Hello, World!"
|
||||
```
|
||||
|
||||
## List
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Item 3
|
||||
"""
|
||||
|
||||
# Test with markdown enabled
|
||||
self.formatter.print_panel(
|
||||
"Testing with markdown ENABLED",
|
||||
title="Markdown Enabled",
|
||||
style="bold green",
|
||||
)
|
||||
self.formatter.print_markdown(test_content, "Markdown Output")
|
||||
|
||||
# Disable markdown
|
||||
self.formatter.disable_markdown()
|
||||
self.formatter.print_panel(
|
||||
"Testing with markdown DISABLED",
|
||||
title="Markdown Disabled",
|
||||
style="bold red",
|
||||
)
|
||||
self.formatter.print_panel(test_content, "Plain Text Output")
|
||||
|
||||
# Re-enable markdown
|
||||
self.formatter.enable_markdown()
|
||||
self.formatter.print_panel(
|
||||
"Testing with markdown RE-ENABLED",
|
||||
title="Markdown Re-enabled",
|
||||
style="bold blue",
|
||||
)
|
||||
self.formatter.print_markdown(
|
||||
test_content, "Markdown Output Again"
|
||||
)
|
||||
|
||||
def test_different_swarm_types(self):
|
||||
"""Test markdown output with different swarm types"""
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 6: Different Swarm Types")
|
||||
print("=" * 60)
|
||||
|
||||
simple_topic = (
|
||||
"Explain the benefits of using Python for data science"
|
||||
)
|
||||
|
||||
# Test Sequential Workflow
|
||||
print("\n--- Sequential Workflow ---")
|
||||
self.formatter.print_panel(
|
||||
"Testing Sequential Workflow (agents work in sequence)",
|
||||
title="Swarm Type Test",
|
||||
style="bold blue",
|
||||
)
|
||||
sequential_results = self.sequential_swarm.run(simple_topic)
|
||||
for i, result in enumerate(sequential_results, 1):
|
||||
# Handle different result types
|
||||
if isinstance(result, dict):
|
||||
result_content = result.get("output", str(result))
|
||||
else:
|
||||
result_content = str(result)
|
||||
|
||||
self.formatter.print_markdown(
|
||||
result_content,
|
||||
title=f"Sequential Agent {i}",
|
||||
border_style="blue",
|
||||
)
|
||||
|
||||
# Test Concurrent Workflow
|
||||
print("\n--- Concurrent Workflow ---")
|
||||
self.formatter.print_panel(
|
||||
"Testing Concurrent Workflow (agents work in parallel)",
|
||||
title="Swarm Type Test",
|
||||
style="bold green",
|
||||
)
|
||||
concurrent_results = self.concurrent_swarm.run(simple_topic)
|
||||
for i, result in enumerate(concurrent_results, 1):
|
||||
# Handle different result types
|
||||
if isinstance(result, dict):
|
||||
result_content = result.get("output", str(result))
|
||||
else:
|
||||
result_content = str(result)
|
||||
|
||||
self.formatter.print_markdown(
|
||||
result_content,
|
||||
title=f"Concurrent Agent {i}",
|
||||
border_style="green",
|
||||
)
|
||||
|
||||
# Test Group Chat
|
||||
print("\n--- Group Chat ---")
|
||||
self.formatter.print_panel(
|
||||
"Testing Group Chat (agents collaborate in conversation)",
|
||||
title="Swarm Type Test",
|
||||
style="bold magenta",
|
||||
)
|
||||
groupchat_results = self.groupchat_swarm.run(simple_topic)
|
||||
|
||||
# Handle different result types for GroupChat
|
||||
if isinstance(groupchat_results, dict):
|
||||
result_content = groupchat_results.get(
|
||||
"output", str(groupchat_results)
|
||||
)
|
||||
else:
|
||||
result_content = str(groupchat_results)
|
||||
|
||||
self.formatter.print_markdown(
|
||||
result_content,
|
||||
title="Group Chat Result",
|
||||
border_style="magenta",
|
||||
)
|
||||
|
||||
def test_simple_formatter_only(self):
|
||||
"""Test just the formatter functionality without agents"""
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 7: Simple Formatter Test (No Agents)")
|
||||
print("=" * 60)
|
||||
|
||||
# Test basic markdown rendering
|
||||
simple_markdown = """
|
||||
# Simple Test
|
||||
|
||||
This is a **bold** test with `inline code`.
|
||||
|
||||
## Code Block
|
||||
```python
|
||||
def hello_world():
|
||||
print("Hello, World!")
|
||||
return "Success"
|
||||
```
|
||||
|
||||
## List
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Item 3
|
||||
"""
|
||||
|
||||
self.formatter.print_panel(
|
||||
"Testing formatter without agents",
|
||||
title="Formatter Test",
|
||||
style="bold cyan",
|
||||
)
|
||||
|
||||
self.formatter.print_markdown(
|
||||
simple_markdown,
|
||||
title="Simple Markdown Test",
|
||||
border_style="green",
|
||||
)
|
||||
|
||||
# Test toggle functionality
|
||||
self.formatter.disable_markdown()
|
||||
self.formatter.print_panel(
|
||||
"Markdown disabled - this should be plain text",
|
||||
title="Plain Text Test",
|
||||
style="bold red",
|
||||
)
|
||||
self.formatter.enable_markdown()
|
||||
|
||||
def test_error_handling_markdown(self):
|
||||
"""Test markdown output with error handling"""
|
||||
print("\n" + "=" * 60)
|
||||
print("TEST 8: Error Handling in Markdown")
|
||||
print("=" * 60)
|
||||
|
||||
# Test with malformed markdown
|
||||
malformed_content = """
|
||||
# Incomplete header
|
||||
**Unclosed bold
|
||||
```python
|
||||
def incomplete_code():
|
||||
# Missing closing backticks
|
||||
"""
|
||||
|
||||
self.formatter.print_panel(
|
||||
"Testing error handling with malformed markdown",
|
||||
title="Error Handling Test",
|
||||
style="bold yellow",
|
||||
)
|
||||
|
||||
# This should handle the error gracefully
|
||||
self.formatter.print_markdown(
|
||||
malformed_content,
|
||||
title="Malformed Markdown Test",
|
||||
border_style="yellow",
|
||||
)
|
||||
|
||||
# Test with empty content
|
||||
self.formatter.print_markdown(
|
||||
"", title="Empty Content Test", border_style="cyan"
|
||||
)
|
||||
|
||||
# Test with None content
|
||||
self.formatter.print_markdown(
|
||||
None, title="None Content Test", border_style="magenta"
|
||||
)
|
||||
|
||||
def run_all_tests(self):
|
||||
"""Run all markdown output tests"""
|
||||
print(" Starting Swarm Markdown Output Tests")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
# Test 1: Basic markdown output
|
||||
self.test_basic_markdown_output()
|
||||
|
||||
# Test 2: Code analysis markdown
|
||||
self.test_code_analysis_markdown()
|
||||
|
||||
# Test 3: Data analysis markdown
|
||||
self.test_data_analysis_markdown()
|
||||
|
||||
# Test 4: Swarm collaboration
|
||||
self.test_swarm_collaboration_markdown()
|
||||
|
||||
# Test 5: Markdown toggle functionality
|
||||
self.test_markdown_toggle_functionality()
|
||||
|
||||
# Test 6: Different swarm types
|
||||
self.test_different_swarm_types()
|
||||
|
||||
# Test 7: Simple formatter test (no agents)
|
||||
self.test_simple_formatter_only()
|
||||
|
||||
# Test 8: Error handling
|
||||
self.test_error_handling_markdown()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print(" All tests completed successfully!")
|
||||
print("=" * 60)
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n Test failed with error: {str(e)}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function to run the markdown output tests"""
|
||||
print("Swarms Markdown Output Test Suite")
|
||||
print(
|
||||
"Testing the current state of formatter.py with real swarm agents"
|
||||
)
|
||||
print("=" * 60)
|
||||
|
||||
# Check environment setup
|
||||
api_key = os.getenv("OPENAI_API_KEY") or os.getenv(
|
||||
"SWARMS_API_KEY"
|
||||
)
|
||||
if not api_key:
|
||||
print(
|
||||
"⚠ Warning: No API key found. Please set OPENAI_API_KEY or SWARMS_API_KEY environment variable."
|
||||
)
|
||||
print(
|
||||
" You can create a .env file with: OPENAI_API_KEY=your_api_key_here"
|
||||
)
|
||||
print(
|
||||
" Or set it in your environment: export OPENAI_API_KEY=your_api_key_here"
|
||||
)
|
||||
print()
|
||||
|
||||
try:
|
||||
# Create and run the test swarm
|
||||
test_swarm = MarkdownTestSwarm()
|
||||
test_swarm.run_all_tests()
|
||||
except Exception as e:
|
||||
print(f"\n Test failed with error: {str(e)}")
|
||||
print("\n Troubleshooting tips:")
|
||||
print(
|
||||
"1. Make sure you have set your API key (OPENAI_API_KEY or SWARMS_API_KEY)"
|
||||
)
|
||||
print("2. Check your internet connection")
|
||||
print("3. Verify you have sufficient API credits")
|
||||
print("4. Try running with a simpler test first")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in new issue