Skip to content

Commit

Permalink
docs update
Browse files Browse the repository at this point in the history
  • Loading branch information
Occupying-Mars committed Dec 6, 2024
1 parent 570f8a2 commit 776aafc
Show file tree
Hide file tree
Showing 3 changed files with 279 additions and 1 deletion.
35 changes: 34 additions & 1 deletion docs/swarms/structs/agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ graph TD
| `all_cores` | Boolean indicating whether to use all CPU cores |
| `device_id` | ID of the GPU device to use if running on GPU |
| `scheduled_run_date` | Optional datetime for scheduling future agent runs |
| `expertise_areas` | List of areas the agent specializes in |
| `importance_threshold` | Minimum importance threshold for notifications |
| `notification_profile` | Profile containing notification preferences |


## `Agent` Methods
Expand Down Expand Up @@ -212,6 +215,8 @@ graph TD
| `check_if_no_prompt_then_autogenerate(task)` | Checks if a system prompt is not set and auto-generates one if needed. | `task` (str): The task to use for generating a prompt. | `agent.check_if_no_prompt_then_autogenerate("Analyze data")` |
| `check_if_no_prompt_then_autogenerate(task)` | Checks if auto_generate_prompt is enabled and generates a prompt by combining agent name, description and system prompt | `task` (str, optional): Task to use as fallback | `agent.check_if_no_prompt_then_autogenerate("Analyze data")` |
| `handle_artifacts(response, output_path, extension)` | Handles saving artifacts from agent execution | `response` (str): Agent response<br>`output_path` (str): Output path<br>`extension` (str): File extension | `agent.handle_artifacts(response, "outputs/", ".txt")` |
| `update_notification_preferences` | Update agent's notification preferences | `expertise_areas`: List[str]<br>`importance_threshold`: float | `agent.update_notification_preferences(expertise_areas=["finance"])` |
| `handle_vector_db_update` | Handle notification of vector DB update | `update_metadata`: UpdateMetadata | `agent.handle_vector_db_update(update)` |



Expand Down Expand Up @@ -567,4 +572,32 @@ print(agent.system_prompt)
13. Enable `rag_every_loop` when continuous context from long-term memory is needed
14. Use `scheduled_run_date` for automated task scheduling

By following these guidelines and leveraging the Swarm Agent's extensive features, you can create powerful, flexible, and efficient autonomous agents for a wide range of applications.
By following these guidelines and leveraging the Swarm Agent's extensive features, you can create powerful, flexible, and efficient autonomous agents for a wide range of applications.

## Notification Example
```python
from swarms import Agent
from swarms.structs.notification_manager import UpdateMetadata
from datetime import datetime

# Create agent with notification preferences
agent = Agent(
agent_name="FinancialAgent",
expertise_areas=["finance", "stocks", "trading"],
importance_threshold=0.6
)

# Update notification preferences
agent.update_notification_preferences(
expertise_areas=["finance", "cryptocurrency"],
importance_threshold=0.7
)

# Handle vector DB update
update = UpdateMetadata(
topic="crypto_market",
importance=0.8,
timestamp=datetime.now(),
affected_areas=["cryptocurrency", "trading"]
)
agent.handle_vector_db_update(update) ```
117 changes: 117 additions & 0 deletions docs/swarms/structs/notification_manager.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Notification Manager

The `NotificationManager` is responsible for managing selective notifications for vector DB updates between agents. It determines which agents should be notified of specific updates based on their expertise areas and notification preferences.

## Overview

The notification system uses relevance scoring and importance thresholds to determine which agents should receive updates. This prevents overwhelming agents with irrelevant notifications and ensures efficient information flow.

## Classes

### UpdateMetadata

Metadata for vector DB updates.

```python
class UpdateMetadata(BaseModel):
topic: str # Topic of the update
importance: float # Importance score (0-1)
timestamp: datetime # When update occurred
embedding: Optional[List[float]] = None # Vector embedding
affected_areas: List[str] = [] # Areas affected by update
```

### AgentProfile

Profile containing agent notification preferences.

```python
class AgentProfile(BaseModel):
agent_id: str # Unique agent identifier
expertise_areas: List[str] # Areas of expertise
importance_threshold: float = 0.5 # Min importance threshold
current_task_context: Optional[str] # Current task being worked on
embedding: Optional[List[float]] # Vector embedding of expertise
```

### NotificationManager

Main class for managing notifications.

```python
class NotificationManager:
def __init__(self):
self.agent_profiles: Dict[str, AgentProfile] = {}
```

## Key Methods

| Method | Description |
|--------|-------------|
| `register_agent(profile: AgentProfile)` | Register an agent's notification preferences |
| `unregister_agent(agent_id: str)` | Remove an agent's notification preferences |
| `calculate_relevance(update_metadata: UpdateMetadata, agent_profile: AgentProfile) -> float` | Calculate relevance score between update and agent |
| `should_notify_agent(update_metadata: UpdateMetadata, agent_profile: AgentProfile) -> bool` | Determine if agent should be notified |
| `get_agents_to_notify(update_metadata: UpdateMetadata) -> List[str]` | Get list of agents to notify |

## Usage Example

```python
from swarms.structs.notification_manager import NotificationManager, UpdateMetadata, AgentProfile
from datetime import datetime

# Create notification manager
manager = NotificationManager()

# Register an agent
profile = AgentProfile(
agent_id="financial_agent",
expertise_areas=["finance", "stocks", "trading"],
importance_threshold=0.6
)
manager.register_agent(profile)

# Create an update
update = UpdateMetadata(
topic="stock_market",
importance=0.8,
timestamp=datetime.now(),
affected_areas=["finance", "trading"]
)

# Get agents to notify
agents_to_notify = manager.get_agents_to_notify(update)
print(f"Agents to notify: {agents_to_notify}")
```

## Relevance Calculation

The relevance score between an update and an agent is calculated using:

1. Topic/expertise overlap score (70% weight)
- Measures overlap between agent's expertise areas and update's affected areas

2. Embedding similarity score (30% weight)
- Cosine similarity between update and agent embeddings if available

The final relevance score determines if an agent should be notified based on:
- Relevance score > 0.5
- Update importance > agent's importance threshold

## Best Practices

1. Set appropriate importance thresholds
- Higher thresholds (e.g. 0.8) for critical updates only
- Lower thresholds (e.g. 0.3) for broader awareness

2. Define focused expertise areas
- Use specific areas rather than broad categories
- Include related areas for better matching

3. Update task context
- Keep current_task_context updated for better relevance
- Clear context when task complete

4. Monitor notification patterns
- Adjust thresholds if agents receive too many/few updates
- Refine expertise areas based on relevance scores
128 changes: 128 additions & 0 deletions docs/swarms/structs/orchestrator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# Orchestrator

The `Orchestrator` manages communication and coordination between multiple agents, particularly for selective vector DB update notifications. It acts as a central hub for registering agents and routing notifications.

## Overview

The orchestrator maintains a list of agents and their notification preferences, using the `NotificationManager` to determine which agents should receive specific updates.

```mermaid
graph TD
A[Orchestrator] --> B[NotificationManager]
A --> C[Agent List]
B --> D[Calculate Relevance]
B --> E[Determine Recipients]
C --> F[Handle Updates]
F --> G[Notify Agents]
```

## Class Definition

```python
class Orchestrator:
def __init__(self):
self.notification_manager = NotificationManager()
self.agents: List[Agent] = []
```

## Key Methods

| Method | Description |
|--------|-------------|
| `register_agent(agent: Agent)` | Register an agent with the orchestrator |
| `handle_vector_db_update(update_metadata: UpdateMetadata)` | Process a vector DB update and notify relevant agents |
| `update_agent_task_context(agent_name: str, task_context: str)` | Update an agent's current task context |

## Usage Example

```python
from swarms import Agent, Orchestrator
from swarms.structs.notification_manager import UpdateMetadata
from datetime import datetime

# Create orchestrator
orchestrator = Orchestrator()

# Create and register agents
agent1 = Agent(
agent_name="FinancialAgent",
expertise_areas=["finance", "stocks", "trading"],
importance_threshold=0.6
)

agent2 = Agent(
agent_name="TechAgent",
expertise_areas=["technology", "software", "AI"],
importance_threshold=0.4
)

orchestrator.register_agent(agent1)
orchestrator.register_agent(agent2)

# Example vector DB update
update = UpdateMetadata(
topic="stock_market",
importance=0.8,
timestamp=datetime.now(),
affected_areas=["finance", "trading"]
)

# Handle update - only FinancialAgent will be notified
orchestrator.handle_vector_db_update(update)
```

## Best Practices

1. Agent Registration
- Register all agents at initialization
- Update agent profiles when expertise changes
- Remove inactive agents

2. Update Handling
- Include relevant metadata in updates
- Set appropriate importance levels
- Consider update timing

3. Task Context
- Keep task contexts current
- Clear contexts when tasks complete
- Use contexts to improve notification relevance

4. Monitoring
- Track notification patterns
- Adjust thresholds as needed
- Monitor agent responses to notifications

## Integration with Vector Databases

The orchestrator can be integrated with various vector databases:

```python
from swarms_memory import ChromaDB
from swarms import Agent, Orchestrator

# Initialize vector DB
vector_db = ChromaDB(
metric="cosine",
output_dir="agent_knowledge"
)

# Create agents with vector DB
agent = Agent(
agent_name="ResearchAgent",
expertise_areas=["research", "analysis"],
long_term_memory=vector_db
)

# Register with orchestrator
orchestrator = Orchestrator()
orchestrator.register_agent(agent)
```

## Error Handling

The orchestrator includes error handling for:
- Invalid agent registrations
- Malformed updates
- Failed notifications
- Missing agent profiles

0 comments on commit 776aafc

Please sign in to comment.