#Python Agents Swarm

1 messages · Page 1 of 1 (latest)

placid igloo
#

Tell me about the agents python libs.

shy magnetBOT
#

Hi @placid igloo. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The main Python library for building agentic AI applications from OpenAI is the OpenAI Agents SDK (openai-agents). This SDK is a lightweight, production-ready upgrade of OpenAI's earlier experimental project called Swarm. While Swarm was a proof-of-concept and not intended for production use, the Agents SDK is designed for real-world applications and offers a minimal set of powerful primitives:

  • Agents: LLMs equipped with instructions and tools.
  • Handoffs: Allow agents to delegate tasks to other agents.
  • Guardrails: Validate agent inputs and outputs.
  • Sessions: Automatically manage conversation history across agent runs.
  • Tracing: Visualize, debug, and monitor agent workflows, and support evaluation and fine-tuning.

The SDK is Python-first, meaning you can orchestrate and chain agents using standard Python features, without needing to learn new abstractions. It also supports turning any Python function into a tool, with automatic schema generation and Pydantic-based validation. The SDK is easy to install and use:

pip install openai-agents

Example usage:

from agents import Agent, Runner

agent = Agent(name="Assistant", instructions="You are a helpful assistant")

result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

(Make sure to set your OPENAI_API_KEY environment variable before running this code.)

#

Swarm, on the other hand, is now considered a sample library and is not recommended for production. You can still explore its ideas and code for learning purposes, but for building robust agentic applications, the OpenAI Agents SDK is the recommended path OpenAI Agents SDK Swarm example.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@placid igloo Kapa.ai is still learning and improving, please let me know how I did by reacting below.

placid igloo
#

@shy magnet okay give me a run down of each item you listed working and how to use them. Here was your list for your reminder

Agents: LLMs equipped with instructions and tools.
Handoffs: Allow agents to delegate tasks to other agents.
Guardrails: Validate agent inputs and outputs.
Sessions: Automatically manage conversation history across agent runs.
Tracing: Visualize, debug, and monitor agent workflows, and support evaluation and fine-tuning.

shy magnetBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Certainly! Here’s a concise rundown of each core component of the OpenAI Agents SDK, with examples and usage patterns based strictly on the provided knowledge sources:


1. Agents

Agents are the core building blocks—LLMs configured with instructions and (optionally) tools. You define their behavior via a name, instructions, and can specify a model or tools.

How to use:

from agents import Agent

agent = Agent(
    name="Math Tutor",
    instructions="You provide help with math problems. Explain your reasoning at each step and include examples",
)

You can also add tools (Python functions) and specify output types for structured responses Agents.


2. Handoffs

Handoffs let one agent delegate a task to another agent, useful for specialization (e.g., triage agent routing to math or history tutor).

How to use:

from agents import Agent

history_tutor_agent = Agent(name="History Tutor", ...)
math_tutor_agent = Agent(name="Math Tutor", ...)

triage_agent = Agent(
    name="Triage Agent",
    instructions="Route to the appropriate specialist.",
    handoffs=[history_tutor_agent, math_tutor_agent]
)

You can also customize handoffs using the handoff() function for more control, such as custom tool names or input types Handoffs.


3. Guardrails

Guardrails are custom validation checks that run on agent input or output. If a guardrail fails, it can block the agent from proceeding.

How to use:

from agents import GuardrailFunctionOutput, Agent, Runner
from pydantic import BaseModel

class HomeworkOutput(BaseModel):
    is_homework: bool
    reasoning: str
#

guardrail_agent = Agent(
name="Guardrail check",
instructions="Check if the user is asking about homework.",
output_type=HomeworkOutput,
)

async def homework_guardrail(ctx, agent, input_data):
result = await Runner.run(guardrail_agent, input_data, context=ctx.context)
final_output = result.final_output_as(HomeworkOutput)
return GuardrailFunctionOutput(
output_info=final_output,
tripwire_triggered=not final_output.is_homework,
)

You attach guardrails to agents using the `input_guardrails` or `output_guardrails` parameters [Quickstart: Guardrails](<https://openai.github.io/openai-agents-python/quickstart/#put-it-all-together>).

---

### 4. **Sessions**
Sessions automatically manage conversation history, so agents remember previous turns without manual state handling.

**How to use:**
```python
from agents import Agent, Runner, SQLiteSession

agent = Agent(name="Assistant", instructions="Reply concisely.")
session = SQLiteSession("conversation_123")

result = await Runner.run(agent, "What city is the Golden Gate Bridge in?", session=session)
print(result.final_output)  # "San Francisco"

result = await Runner.run(agent, "What state is it in?", session=session)
print(result.final_output)  # "California"

Sessions store and retrieve conversation history for each session ID Sessions.


5. Tracing

Tracing records all events during agent runs (LLM calls, tool invocations, handoffs, guardrails, etc.) for debugging and monitoring. Traces can be visualized in the Traces dashboard.

How to use:
Tracing is enabled by default. To group multiple runs into a single trace:

from agents import Agent, Runner, trace
#

async def main():
agent = Agent(name="Joke generator", instructions="Tell funny jokes.")

with trace("Joke workflow"):
    first_result = await Runner.run(agent, "Tell me a joke")
    second_result = await Runner.run(agent, f"Rate this joke: {first_result.final_output}")
    print(f"Joke: {first_result.final_output}")
    print(f"Rating: {second_result.final_output}")
You can disable tracing globally or per-run if needed [Tracing](<https://openai.github.io/openai-agents-python/tracing/#tracing>).

---

If you need more detailed code for any specific component, let me know!
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@placid igloo Kapa.ai is still learning and improving, please let me know how I did by reacting below.

placid igloo
#

How does this link to codex @shy magnet, Can I have a agent call codex and use agents in agents systems? can I have this system be ready to be called from a mcp server?

shy magnetBOT
#

Let me check the knowledge base for you again. One moment! :books:

#

Yes, you can integrate Codex with the OpenAI Agents SDK and have agents call Codex as part of agentic systems. This is achieved by exposing Codex CLI as an MCP (Model Context Protocol) server, which allows agents to use Codex as a tool within their workflows.

How does this link to Codex?

  • Codex CLI as MCP Server: You run Codex CLI in MCP mode (e.g., with npx codex mcp), which exposes Codex as a tool accessible via the MCP protocol. The Agents SDK can then connect to this MCP server and use Codex for code generation or editing tasks Building Consistent Workflows with Codex CLI & Agents SDK.
  • Agent Calls Codex: You define agents in Python and provide them access to the Codex MCP server by including it in their mcp_servers parameter. When the agent needs to perform a code-related task, it can call Codex through this server.

Example:

from agents import Agent, Runner
from agents.mcp import MCPServerStdio

async with MCPServerStdio(
    name="Codex CLI",
    params={"command": "npx", "args": ["-y", "codex", "mcp"]},
    client_session_timeout_seconds=360000,
) as codex_mcp_server:
    developer_agent = Agent(
        name="Game Developer",
        instructions="You are an expert in building simple games...",
        mcp_servers=[codex_mcp_server],
    )
    # ... define other agents and run workflows

This setup allows your agent to call Codex for code generation, file creation, etc. Building Single Agent Systems.

Can I have agents in agent systems (multi-agent orchestration)?

#

Yes, you can orchestrate multiple agents, each with specialized roles (e.g., Designer, Frontend Developer, Backend Developer, Tester), and have them collaborate by handing off tasks and sharing context. Each agent can access the Codex MCP server as needed. The Project Manager agent coordinates the workflow, and agents can call Codex for their respective tasks Define each specialized agent.

Can this system be ready to be called from an MCP server?

Yes, the system is designed to both call out to MCP servers (like Codex CLI) and expose tools via MCP. The Agents SDK supports multiple MCP transports, so you can connect to Codex MCP servers or other MCP-compatible tools. You can also use hosted MCP tools if you want OpenAI’s infrastructure to manage the tool invocation Model context protocol (MCP).

Summary:

  • Agents can call Codex via MCP.
  • You can build multi-agent systems where agents collaborate and delegate.
  • The system is MCP-ready, both for calling Codex and for integrating with other MCP-compatible tools.

If you need a specific code example for multi-agent orchestration with Codex MCP, let me know!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: