Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

base openai_assistant #630

Merged
merged 4 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
docs_dir: '.' # replace with the correct path if your documentation files are not in the same directory as mkdocs.yml

Check warning on line 1 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

1:1 [document-start] missing document start "---"

Check failure on line 1 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

1:81 [line-length] line too long (118 > 80 characters)
site_name: Swarms
site_url: https://docs.swarms.world
site_author: Swarms
site_description: The Enterprise-Grade Production-Ready Multi-Agent Orchestration Framework

Check failure on line 5 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

5:81 [line-length] line too long (91 > 80 characters)
repo_name: kyegomez/swarms
repo_url: https://github.com/kyegomez/swarms
edit_uri: https://github.com/kyegomez/swarms/tree/main/docs
Expand All @@ -13,9 +13,9 @@
- search
- git-authors
- mkdocs-jupyter:
kernel_name: python3

Check failure on line 16 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

16:9 [indentation] wrong indentation: expected 6 but found 8
execute: false
include_source: True

Check warning on line 18 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

18:25 [truthy] truthy value should be one of [false, true]
include_requirejs: true
- mkdocstrings:
default_handler: python
Expand Down Expand Up @@ -137,10 +137,10 @@
- pymdownx.tilde
nav:
- Home:
- Overview: "index.md"

Check failure on line 140 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

140:5 [indentation] wrong indentation: expected 6 but found 4
# - The Vision: "swarms/framework/vision.md"
# - Docker Setup: "swarms/install/docker_setup.md"
- Our Goal; The Ultimate Multi-Agent LLM Framework for Developers: "swarms/concept/vision.md"

Check failure on line 143 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

143:81 [line-length] line too long (97 > 80 characters)
- Swarm Ecosystem: "swarms/concept/swarm_ecosystem.md"
- Onboarding:
- Installation: "swarms/install/install.md"
Expand All @@ -149,7 +149,7 @@
- Swarms CLI: "swarms/cli/main.md"
# - Swarms + Docker:
- Swarms Framework Architecture: "swarms/concept/framework_architecture.md"
# - Prelimary:

Check warning on line 152 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

152:5 [comments-indentation] comment not indented like content
# - 80/20 Rule For Agents: "swarms/prompting/8020.md"
- Managing Prompts in Production: "swarms/prompts/main.md"
- Agents:
Expand All @@ -157,6 +157,7 @@
# - Build Custom Agents: "swarms/structs/diy_your_own_agent.md"
- Agent Architecture: "swarms/framework/agents_explained.md"
- Complete Agent API: "swarms/structs/agent.md"
- OpenAI Assistant: "swarms/agents/openai_assistant.md"
- Create and Run Agents from YAML: "swarms/agents/create_agents_yaml.md"
- Integrating External Agents from Griptape, Langchain, etc: "swarms/agents/external_party_agents.md"
- Tools:
Expand Down Expand Up @@ -250,7 +251,7 @@
- Edit Agents: "swarms_platform/agents/edit_agent.md"
- Telemetry API:
- PUT: "swarms_platform/telemetry/index.md"
# - Tools API:

Check warning on line 254 in docs/mkdocs.yml

View workflow job for this annotation

GitHub Actions / yaml-lint

254:5 [comments-indentation] comment not indented like content
# - Overview: "swarms_platform/tools_api.md"
# - Add Tools: "swarms_platform/fetch_tools.md"
- Guides:
Expand Down
135 changes: 135 additions & 0 deletions docs/swarms/agents/openai_assistant.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# OpenAI Assistant

The OpenAI Assistant class provides a wrapper around OpenAI's Assistants API, integrating it with the swarms framework.

## Overview

The `OpenAIAssistant` class allows you to create and interact with OpenAI Assistants, providing a simple interface for:

- Creating assistants with specific roles and capabilities
- Adding custom functions that the assistant can call
- Managing conversation threads
- Handling tool calls and function execution
- Getting responses from the assistant

## Insstallation

```bash
pip install swarms
```
## Basic Usage

```python

from swarms import OpenAIAssistant

#Create an assistant
assistant = OpenAIAssistant(
name="Math Tutor",
instructions="You are a helpful math tutor.",
model="gpt-4o",
tools=[{"type": "code_interpreter"}]
)

#Run a Task
response = assistant.run("Solve the equation: 3x + 11 = 14")
print(response)

# Continue the conversation in the same thread
follow_up = assistant.run("Now explain how you solved it")
print(follow_up)
```

## Function Calling

The assistant supports custom function integration:

```python

def get_weather(location: str, unit: str = "celsius") -> str:
# Mock weather function
return f"The weather in {location} is 22 degrees {unit}"

# Add function to assistant
assistant.add_function(
description="Get the current weather in a location",
parameters={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"default": "celsius"
}
},
"required": ["location"]
}
)
```

## API Reference

### Constructor

```python
OpenAIAssistant(
name: str,
instructions: Optional[str] = None,
model: str = "gpt-4o",
tools: Optional[List[Dict[str, Any]]] = None,
file_ids: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
functions: Optional[List[Dict[str, Any]]] = None,
)
```

### Methods

#### run(task: str) -> str
Sends a task to the assistant and returns its response. The conversation thread is maintained between calls.

#### add_function(func: Callable, description: str, parameters: Dict[str, Any]) -> None
Adds a callable function that the assistant can use during conversations.

#### add_message(content: str, file_ids: Optional[List[str]] = None) -> None
Adds a message to the current conversation thread.

## Error Handling

The assistant implements robust error handling:
- Retries on rate limits
- Graceful handling of API errors
- Clear error messages for debugging
- Status monitoring for runs and completions

## Best Practices

1. Thread Management
- Use the same assistant instance for related conversations
- Create new instances for unrelated tasks
- Monitor thread status during long-running operations

2. Function Integration
- Keep functions simple and focused
- Provide clear descriptions and parameter schemas
- Handle errors gracefully in custom functions
- Test functions independently before integration

3. Performance
- Reuse assistant instances when possible
- Monitor and handle rate limits appropriately
- Use appropriate polling intervals for status checks
- Consider implementing timeouts for long-running operations

## References

- [OpenAI Assistants API Documentation](https://platform.openai.com/docs/assistants/overview)
- [OpenAI Function Calling Guide](https://platform.openai.com/docs/guides/function-calling)
- [OpenAI Rate Limits](https://platform.openai.com/docs/guides/rate-limits)



62 changes: 61 additions & 1 deletion docs/swarms/structs/async_workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,4 +203,64 @@ await workflow.add(tasks=[task_1, task_2])
# Running the workflow
results = await workflow.run()
print(results) # Output: ["Task 1 Completed", "Task 2 Completed"]
```
```

# Async Workflow

The AsyncWorkflow allows multiple agents to process tasks concurrently using Python's asyncio framework.

## Usage Example

```python
import asyncio
from swarms import Agent, AsyncWorkflow
from swarm_models import OpenAIChat

# Initialize model
model = OpenAIChat(
openai_api_key="your-api-key",
model_name="gpt-4",
temperature=0.7
)

# Create agents
agents = [
Agent(
agent_name=f"Analysis-Agent-{i}",
llm=model,
max_loops=1,
dashboard=False,
verbose=True,
)
for i in range(3)
]

# Initialize workflow
workflow = AsyncWorkflow(
name="Analysis-Workflow",
agents=agents,
max_workers=3,
verbose=True
)

# Run workflow
async def main():
task = "Analyze the potential impact of AI on healthcare"
results = await workflow.run(task)
for i, result in enumerate(results):
print(f"Agent {i} result: {result}")

# Execute
asyncio.run(main())
```

## Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `name` | str | "AsyncWorkflow" | Name of the workflow |
| `agents` | List[Agent] | None | List of agents to execute tasks |
| `max_workers` | int | 5 | Maximum number of concurrent workers |
| `dashboard` | bool | False | Enable/disable dashboard |
| `autosave` | bool | False | Enable/disable autosaving results |
| `verbose` | bool | False | Enable/disable verbose logging |
Loading
Loading