docs: OpenAI Agents integration update (#1608)

Signed-off-by: Anush008 <anushshetty90@gmail.com>
This commit is contained in:
Anush
2025-04-30 14:10:48 +05:30
committed by GitHub
parent f7f47f0a6b
commit a93078c628
3 changed files with 130 additions and 172 deletions
@@ -34,6 +34,7 @@ aliases: ["/documentation/frameworks/memgpt/"]
| [Mirror Security](/documentation/frameworks/mirror-security/) | Python framework for vector encryption and access control. |
| [Mem0](/documentation/frameworks/mem0/) | Self-improving memory layer for LLM applications, enabling personalized AI experiences. |
| [Neo4j GraphRAG](/documentation/frameworks/neo4j-graphrag/) | Package to build graph retrieval augmented generation (GraphRAG) applications using Neo4j and Python. |
| [OpenAI Agents](/documentation/frameworks/openai-agents/) | Python framework for managing multiple AI agents that can work together. |
| [Pandas-AI](/documentation/frameworks/pandas-ai/) | Python library to query/visualize your data (CSV, XLSX, PostgreSQL, etc.) in natural language |
| [Ragbits](/documentation/frameworks/ragbits/) | Python package that offers essential "bits" for building powerful Retrieval-Augmented Generation (RAG) applications. |
| [Rig-rs](/documentation/frameworks/rig-rs/) | Rust library for building scalable, modular, and ergonomic LLM-powered applications. |
@@ -42,7 +43,6 @@ aliases: ["/documentation/frameworks/memgpt/"]
| [Solon](/documentation/frameworks/solon/) | A lightweight, high-performance Java enterprise framework |
| [Spring AI](/documentation/frameworks/spring-ai/) | Java AI framework for building with Spring design principles such as portability and modular design. |
| [Superduper](/documentation/frameworks/superduper/) | Framework for building flexible, compositional AI apps which may be applied directly to databases. |
| [Swarm](/documentation/frameworks/swarm/) | Python framework for managing multiple AI agents that can work together. |
| [Sycamore](/documentation/frameworks/sycamore/) | Document processing engine for ETL, RAG, LLM-based applications, and analytics on unstructured data. |
| [Testcontainers](/documentation/frameworks/testcontainers/) | Framework for providing throwaway, lightweight instances of systems for testing |
| [txtai](/documentation/frameworks/txtai/) | Python library for semantic search, LLM orchestration and language model workflows. |
@@ -0,0 +1,129 @@
---
title: OpenAI Agents
aliases: [ /documentation/frameworks/swarm/ ]
---
# OpenAI Agents
[OpenAI Agents](https://github.com/openai/openai-agents-python) is a Python framework to build agentic AI apps in a lightweight, easy-to-use package with very few abstractions. It's a production-ready upgrade of the experimental framework, [Swarm](https://github.com/openai/swarm).
## Getting Started
To start using OpenAI Agents, follow these steps:
- Install the package
```bash
pip install openai-agents
```
- Set up your OpenAI API key
```bash
export OPENAI_API_KEY="<YOUR_KEY>"
```
## How It Works
The Agents SDK has a very small set of primitives:
- `Agents`, which are LLMs equipped with instructions and tools
- `Handoffs`, which allow agents to delegate to other agents for specific tasks
- `Guardrails`, which enable the inputs to agents to be validated
Used with Python, these building blocks make it easy to create real-world apps with tool-agent interactions and minimal learning curve. Plus, the SDK also includes tracing to help you debug, evaluate, and fine-tune your agent workflows.
## Creating Your First Agents
Here’s a basic example of three agents:
- Triage Agent: Acts as the initial point of contact. It analyzes the user's question and decides whether to route it to a specialized agent.
- Math Tutor: A specialist agent designed to help with math-related questions.
- History Tutor: A specialist agent focused on historical topics.
```python
from agents import Agent, Runner
math_tutor_agent = Agent(
name="Math Tutor",
handoff_description="Specialist agent for math questions",
instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)
history_tutor_agent = Agent(
name="History Tutor",
handoff_description="Specialist agent for historical questions",
instructions="You provide assistance with historical queries. Explain important events and context clearly.",
)
triage_agent = Agent(
name="Triage Agent",
instructions="You determine which agent to use based on the user's homework question",
handoffs=[history_tutor_agent, math_tutor_agent],
)
# Run the interaction
result = Runner.run_sync(triage_agent, "I want some help with WW1.")
print(result.final_output)
```
## Integrating with Qdrant
You can connect agents to retrieve or ingest data into a Qdrant collection. Thereby building your knowledge base. Here’s how to enable an agent to retrieve information from Qdrant.
Assume you have a Qdrant [collection created](https://qdrant.tech/documentation/concepts/collections/#create-a-collection) using the `"text-embedding-3-small"` model. The payload structure includes a `text` field for knowledge storage.
```python
import qdrant_client
from openai import OpenAI
from agents import Agent, function_tool
# Initialize clients
openai_client = OpenAI()
qdrant = qdrant_client.QdrantClient(host="localhost")
# Configuration
EMBEDDING_MODEL = "text-embedding-3-small"
COLLECTION_NAME = "help_center"
LIMIT = 5
SCORE_THRESHOLD = 0.7
@function_tool
def query_qdrant(query: str) -> str:
"""Retrieve semantically relevant content from Qdrant.
Args:
query: The query to search.
"""
embedded_query = openai_client.embeddings.create(
input=query,
model=EMBEDDING_MODEL,
).data[0].embedding
results = qdrant.query_points(
collection_name=COLLECTION_NAME,
query=embedded_query,
limit=LIMIT,
score_threshold=SCORE_THRESHOLD,
).points
if results:
return "\n".join([point.payload["text"] for point in results])
else:
return "No results found."
qdrant_agent = Agent(
name="Qdrant searcher",
handoff_description="Specialist agent for retrieving info from a Qdrant collection",
instructions="You help find answers for user queries using Qdrant. Do not make up any info on your own.",
tools=[query_qdrant],
)
```
Our `qdrant_agent` can now query a Qdrant collection whenever deemed necessary to answer a user query.
## Further Reading
- [Agents Documentation](https://openai.github.io/openai-agents-python/)
- [Agents Examples](https://github.com/openai/openai-agents-python/tree/main/examples)
@@ -1,171 +0,0 @@
---
title: OpenAI Swarm
---
# Swarm
[OpenAI Swarm](https://github.com/openai/swarm) is a Python framework for managing multiple AI agents that can work together. Instead of relying on a single LLM instance to perform all tasks, Swarm allows you to build specialized agents that communicate and collaborate, like a team of experts with unique skills.
## Getting Started
To start using Swarm, follow these steps:
- Install Swarm
```bash
pip install git+https://github.com/openai/swarm.git
```
- Set up your OpenAI API key
```bash
export OPENAI_API_KEY="<YOUR_KEY>"
```
## How Swarm Works
In Swarm, agents represent individual team members with specific roles and instructions. Each agent can execute tasks or hand off the conversation to another agent, depending on the situation.
An `Agent` instance simply encapsulates a set of instructions with a set of functions, and has the capability to hand off execution to another Agent.
These simple building blocks allow you to create complex workflows with a simple mental model.
## Creating Your First Agents
Here’s a basic example of two agents:
- **Agent A**: A helpful assistant.
- **Agent B**: An arithmetric specialist.
Agent A transfers the conversation to Agent B when requested.
```python
from swarm import Swarm, Agent
client = Swarm()
# Define Agent B
agent_b = Agent(
name="Agent B",
instructions="Arithmetic solving expertise holder.",
)
def transfer_to_agent_b():
return agent_b
# Define Agent A
agent_a = Agent(
name="Agent A",
instructions="You are a helpful agent.",
functions=[transfer_to_agent_b],
)
# Run the interaction
response = client.run(
agent=agent_a,
messages=[{"role": "user", "content": "I want some help with numbers."}],
)
print(response)
```
In this example, Agent A passes the conversation to Agent B when deemed necessary.
## Features of an agent
### 1. **Instructions**
Agent instructions define their behavior. These are translated into system prompts for conversations. Only the active agent's instructions are used during an interaction.
### 2. **Functions**
Agents can execute Python functions, enabling them to perform tasks like processing data or querying databases. Swarm automatically converts functions into a JSON Schema that is passed into Chat Completions tools.
Example:
```python
def greet(context_variables, language):
user_name = context_variables["user_name"]
greeting = "Hola" if language.lower() == "spanish" else "Hello"
print(f"{greeting}, {user_name}!")
return "Done"
agent = Agent(
name="Greeter Agent",
functions=[greet],
)
client.run(
agent=agent,
messages=[{"role": "user", "content": "Greet me in Spanish."}],
context_variables={"user_name": "John"},
)
```
Errors are handled gracefully by appending an error response to the conversation.
### 3. **Handoffs**
If a function returns another agent, the system transfers control to that agent.
## Integrating Swarm with Qdrant
You can connect you Swarm agents to retrieve or ingest data into a Qdrant collection. Thereby building you knowledge base. Here’s how to enable an agent to retrieve information from Qdrant.
Assume you have a Qdrant [collection created](https://qdrant.tech/documentation/concepts/collections/#create-a-collection) using the `"text-embedding-3-small"` model. The payload structure includes a `text` field for knowledge storage.
```python
import qdrant_client
from openai import OpenAI
# Initialize clients
openai_client = OpenAI()
qdrant = qdrant_client.QdrantClient(host="localhost")
# Configuration
EMBEDDING_MODEL = "text-embedding-3-small"
COLLECTION_NAME = "help_center"
LIMIT = 5
SCORE_THRESHOLD = 0.7
# Function to query Qdrant
def query_qdrant(query):
"""Retrieve semantically relevant content from Qdrant."""
embedded_query = openai_client.embeddings.create(
input=query,
model=EMBEDDING_MODEL,
).data[0].embedding
results = qdrant.query_points(
collection_name=COLLECTION_NAME,
query=embedded_query,
limit=LIMIT,
score_threshold=SCORE_THRESHOLD,
).points
if results:
return {"response": "\n".join([point.payload["text"] for point in results])}
else:
return {"response": "No results found."}
# Define agents
qdrant_agent = Agent(
name="Qdrant Agent",
instructions="Retrieve relevant info from a knowledge base stored in Qdrant.",
functions=[query_qdrant],
)
def transfer_to_qdrant():
return qdrant_agent
main_agent = Agent(
name="Main Agent",
instructions="Handle user queries and delegate searches to Qdrant.",
functions=[transfer_to_qdrant],
)
```
Our `qdrant_agent` can now query a Qdrant collection whenever deemed necessary to answer a user query.
## Further Reading
You can find more usage examples in the [Swarm repo](https://github.com/openai/swarm/blob/main/examples/) that further describe its capabilities.