Логотип Openai Agents Sdk

Openai Agents Sdk

Спільнота
peterbamuhigire
openai-agents-sdk

Використовуйте під час створення агентів Python за допомогою OpenAI Agents SDK, зокрема для налаштування виконавців, інструментів, передавання керування, засобів контролю, трасування, пам’яті, топології мультиагентних систем і детермінованої оркестрації.

Add to TypingMind

Огляд

Видавецьpeterbamuhigire
Репозиторійchwezi-dev-engine
Назва навичкиopenai-agents-sdk
Зірки
29
Форки
6
Файли в пакеті
Лише інструкції
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Видавець на GitHub: peterbamuhigire. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Openai Agents Sdk у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/peterbamuhigire/chwezi-dev-engine/tree/main/skills/ai/openai-agents-sdk
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/peterbamuhigire/chwezi-dev-engine.git /tmp/chwezi-dev-engine
mkdir -p .claude/skills
cp -r /tmp/chwezi-dev-engine/skills/ai/openai-agents-sdk .claude/skills/openai-agents-sdk
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Openai Agents Sdk в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Openai Agents Sdk, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Openai Agents Sdk не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

OpenAI Agents SDK

Operating contract

Inputs

InputRequiredPurpose
Domain evidenceyesagent goal, SDK/runtime version, tool and handoff inventory, authority limits, data classification, and evaluation cases

Outputs

  • Produce: agent topology, tool schemas, guardrails, handoff rules, tracing configuration, and runnable validation plan.

Capability and permission boundaries

Default to read-only analysis. Read only scoped records; redact secrets and regulated data. Writes, execution, network calls, production configuration, customer communication, billing changes, and delegation require explicit authority and an identified owner. Never widen tenant, time-window, or system scope implicitly.

Degraded mode

When required telemetry, evidence, execution, network access, or write authority is unavailable, return a partial result with each unassessed item labelled, preserve the safest existing state, and state the evidence or approval needed to continue. Never convert missing evidence into a pass.

Decision rules

ConditionAction
Scope, owner, or threshold is missingStop the affected decision and request it
Evidence is incomplete but read-only analysis is safeProduce a qualified partial result and gap list
A mutation exceeds authority or tenant boundaryBlock it and route for approval
Evidence meets the stated thresholdIssue the output with provenance and owner

Anti-Patterns

  • Treating absent evidence as success. Fix: mark the check unassessed and name the missing source.
  • Expanding one tenant or workflow to all tenants. Fix: enforce supplied scope at every query and action.
  • Performing a production write during analysis. Fix: emit a reviewed change plan until authority is explicit.
  • Reporting a metric without population, window, or source. Fix: attach all three.
  • Hiding a failed threshold inside an average. Fix: report failure slices and the remediation owner.

Acknowledgement: Shared by Peter Bamuhigire, techguypeter.com, +256 784 464178.

Use When

  • Build production AI agents with the OpenAI Agents SDK (Python) — 6 core primitives (Agent, Runner, Tools, Handoff, Guardrails, Tracing), multi-agent patterns (Centralized, Hierarchical, Decentralized, Swarm), dynamic/deterministic orchestration...

Evidence Produced

CategoryArtifactFormatExample
CorrectnessOpenAI Agents SDK contract test planMarkdown doc covering Agent, Runner, Tools, Handoff, and Guardrails primitive testsdocs/ai/openai-agents-tests.md
SecurityAgent guardrail and key handling noteMarkdown doc covering tool whitelisting, output filtering, and API key rotationdocs/ai/openai-agents-security.md

References

  • Use the links and companion skills already referenced in this file when deeper context is needed.

Minimal Python SDK for building AI agents. Six primitives: Agent, Runner, Tools, Handoff, Guardrails, Tracing.

bash
pip install openai-agents
export OPENAI_API_KEY="sk-..."

1. Agent — The Core Primitive

A configurable wrapper around an LLM that can take actions.

python
from agents import Agent

customer_service_agent = Agent(
    name="Customer Service Agent",
    model="gpt-4o",                    # or any OpenAI-compatible model
    instructions="""
        You are a helpful customer service agent.
        Handle returns, orders, and billing queries.
        Escalate complex issues to a human.
    """,
    tools=[get_order_status, process_refund, track_shipment],
    handoffs=[billing_agent, technical_agent],    # agents to delegate to
)

Agent parameters: name, instructions (system prompt), model, tools, handoffs, guardrails, output_type


2. Runner — The Agent Loop

Runs the agent's reasoning loop (think → act → observe → repeat).

python
from agents import Agent, Runner

agent = Agent(name="Assistant", instructions="You are a helpful assistant.", model="gpt-4o")

# Synchronous (simple scripts, testing)
result = Runner.run_sync(agent, "What is the capital of France?")
print(result.final_output)

# Asynchronous (web apps, FastAPI)
import asyncio
result = await Runner.run(agent, "Summarise this document.", max_turns=10)
print(result.final_output)

Key parameter: max_turns — safety valve against infinite loops. Always set it.

python
result = Runner.run_sync(agent, user_message, max_turns=15)

3. Tools — Extending Agent Capabilities

Custom Tools (Python Functions)

Any Python function becomes a tool with @function_tool. The SDK reads the name, docstring, and type hints automatically.

python
from agents import function_tool

@function_tool
def get_order_status(order_id: str) -> str:
    """Gets the current status of a customer order.
    
    Args:
        order_id: The unique order identifier (e.g. ORD-12345)
    """
    order = db.query("SELECT status FROM orders WHERE id = ?", [order_id])
    return f"Order {order_id} is: {order['status']}"

@function_tool
def calculate_refund(order_id: str, reason: str) -> dict:
    """Calculate and process a refund for an order.
    
    Args:
        order_id: The order to refund
        reason: Customer-provided reason for return
    """
    amount = get_order_total(order_id)
    return {"refund_amount": amount, "processing_days": 3}

Hosted Tools (Built-in OpenAI)

python
from agents import Agent
from agents.tools import WebSearchTool, FileSearchTool, CodeInterpreterTool

research_agent = Agent(
    name="Research Agent",
    model="gpt-4o",
    instructions="Research topics thoroughly and provide cited summaries.",
    tools=[
        WebSearchTool(),          # search the web
        FileSearchTool(            # search vector store
            vector_store_ids=["vs_abc123"]
        ),
        CodeInterpreterTool(),    # run Python code
    ],
)

Agent as Tool

python
# When you need a sub-agent but the calling agent retains control
analysis_tool = analysis_agent.as_tool(
    tool_name="RunAnalysis",
    tool_description="Run deep financial analysis on the provided data."
)

orchestrator = Agent(
    name="Orchestrator",
    tools=[analysis_tool, data_fetcher],
)

Handoff vs as_tool:

  • handoff — complete transfer of control, caller stops
  • as_tool — caller delegates subtask, caller resumes after

4. Handoffs — Multi-Agent Delegation

python
from agents import Agent, Runner

# Specialized agents
billing_agent = Agent(
    name="Billing Agent",
    instructions="Handle all billing, payment, and invoice queries.",
    tools=[lookup_invoice, process_payment],
)
technical_agent = Agent(
    name="Technical Agent",
    instructions="Resolve technical issues, bugs, and connectivity problems.",
    tools=[check_system_status, reset_connection],
)

# Triage agent with handoffs
triage_agent = Agent(
    name="Triage Agent",
    instructions="""
        Triage the user's request. If billing-related, route to Billing Agent.
        If technical, route to Technical Agent. Otherwise, answer directly.
    """,
    handoffs=[billing_agent, technical_agent],
)

result = Runner.run_sync(triage_agent, "My invoice shows the wrong amount")
print(result.final_output)

Handoff prompt best practices:

  • Explicitly name which conditions trigger a handoff in each agent's instructions
  • Each specialist agent must clearly state its purpose and domain
  • Use result.last_agent to track which agent handled the final response

5. Multi-Agent Patterns

Centralized (Most Common)

One triage/orchestrator routes to specialists. Best for: customer support, internal assistants, helpdesks.

python
# One central agent → N specialized agents
triage_agent = Agent(
    name="Triage",
    handoffs=[billing_agent, technical_agent, sales_agent],
)

Hierarchical

Multi-tier routing: triage → managers → specialists. Best for: deep research, complex enterprise workflows.

python
# Triage → Domain Manager → Domain Specialists
science_manager = Agent(name="Science Manager",
    handoffs=[physics_agent, chemistry_agent])
history_manager = Agent(name="History Manager",
    handoffs=[politics_agent, warfare_agent])
triage = Agent(name="Research Triage",
    handoffs=[science_manager, history_manager])

Dynamic vs Deterministic Orchestration

python
# Deterministic — hardcoded routing (predictable, inflexible)
def orchestrate(message: str):
    if "complaint" in message.lower():
        return Runner.run_sync(complaints_agent, message)
    return Runner.run_sync(inquiry_agent, message)

# Dynamic — LLM decides routing (flexible, less predictable)
triage_agent = Agent(
    name="Triage",
    instructions="Route requests to the most appropriate specialized agent.",
    handoffs=[complaints_agent, inquiry_agent],  # LLM picks at runtime
)

Decentralized (Debate / Brainstorm)

No central agent; agents exchange turns. Best for: ideation, debate, negotiation.

python
agents = [Agent(name=f"{role}", instructions=f"You are a {role}...") for role in roles]
# Manual round-robin loop — SDK does not auto-manage decentralized flow
for i in range(rounds):
    result = Runner.run_sync(agents[i % len(agents)], history, session=session)

Swarm (Parallel Exploration)

Many simple agents in parallel, results aggregated. Best for: creative generation, optimization.

python
import concurrent.futures

def run_agent(agent, prompt):
    return Runner.run_sync(agent, prompt).final_output

with concurrent.futures.ThreadPoolExecutor() as executor:
    results = list(executor.map(lambda a: run_agent(a, prompt), specialist_agents))

summary = Runner.run_sync(aggregator_agent, "\n".join(results))

6. Memory Management

python
from agents import SQLiteSession

# Persistent conversation memory (survives restarts)
session = SQLiteSession("my_app_db")
last_agent = triage_agent

while True:
    user_input = input("You: ")
    result = Runner.run_sync(last_agent, user_input, session=session)
    print("Agent:", result.final_output)
    last_agent = result.last_agent  # continue with whoever last responded

Sliding window for long conversations:

python
# Summarize old messages when context grows too large
if len(messages) > 20:
    summary = Runner.run_sync(summarizer_agent, "\n".join(messages[-20:]))
    messages = [{"role": "system", "content": f"Conversation so far: {summary.final_output}"}]

7. Guardrails — Safety Validation

python
from agents import Agent, Runner, GuardrailFunctionOutput, RunContextWrapper
from agents import input_guardrail, output_guardrail, InputGuardrailTripwireTriggered
from agents.types import TResponseInputItem

@input_guardrail
async def scope_guardrail(
    ctx: RunContextWrapper[None],
    agent: Agent,
    input: str | list[TResponseInputItem]
) -> GuardrailFunctionOutput:
    """Only allow customer service queries."""
    is_valid = any(kw in str(input).lower()
                   for kw in ['order', 'refund', 'account', 'billing', 'payment', 'delivery'])
    return GuardrailFunctionOutput(
        output_info="valid" if is_valid else "out of scope",
        tripwire_triggered=not is_valid,
    )

agent = Agent(
    name="CS Agent",
    instructions="Handle customer service queries.",
    input_guardrails=[scope_guardrail],
)

try:
    result = Runner.run_sync(agent, "What's the meaning of life?")
except InputGuardrailTripwireTriggered:
    print("Sorry, I can only help with customer service queries.")

8. Third-Party Models (OpenAI-Compatible)

python
from agents.extensions.models.litellm_model import LitellmModel

# Use DeepSeek, Anthropic, Gemini, Llama — anything via LiteLLM
agent = Agent(
    name="Multi-Model Agent",
    model=LitellmModel(model="deepseek/deepseek-chat", api_key="..."),
    instructions="You are a helpful assistant.",
)

# Or set globally
import agents
agents.set_default_openai_api("chat_completions")
agents.set_default_openai_client(AsyncOpenAI(
    base_url="https://api.deepseek.com/v1",
    api_key=os.environ["DEEPSEEK_API_KEY"],
))

Anti-Patterns

Anti-PatternFix
No max_turns limitAlways set max_turns — prevents runaway agent loops
Vague agent instructionsExplicitly name routing conditions and domain boundaries
Too many tools per agentKeep 5–8 tools max per agent — too many confuses the model
Write actions without approvalAdd human approval gate before any irreversible action
No session managementUse SQLiteSession for multi-turn conversations
Missing error handlingWrap Runner.run_sync() in try/except for guardrail errors

Source: Habib — Building Agents with OpenAI Agents SDK (Packt, 2025)

Поширені запитання

Що робить навичка ШІ Openai Agents Sdk?

Використовуйте під час створення агентів Python за допомогою OpenAI Agents SDK, зокрема для налаштування виконавців, інструментів, передавання керування, засобів контролю, трасування, пам’яті, топології мультиагентних систем і детермінованої оркестрації.

Навіщо використовувати Openai Agents Sdk у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Openai Agents Sdk — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Openai Agents Sdk у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/peterbamuhigire/chwezi-dev-engine/tree/main/skills/ai/openai-agents-sdk. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Openai Agents Sdk?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Openai Agents Sdk?

Зі скількома забажаєте. У TypingMind ви можете використовувати Openai Agents Sdk із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Openai Agents Sdk?

Так. На GitHub цю навичку публікує peterbamuhigire за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі
Логотип openclaw

Openclaw Changelog Update

openclaw
ОрганізаціяПопулярне

Повторно створюйте розділи журналу змін релізу OpenClaw на основі історії git перед випусками beta, stable або extended-stable.

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Openclaw Ci Limits

openclaw
ОрганізаціяПопулярне

Керуйте GitHub Actions для OpenClaw і пропускною здатністю CI у Blacksmith, бюджетами реєстрації раннерів, обмеженнями fanout, одночасним запуском лише одного завдання для кожного push у main, розміром шард, перенесенням завдань на хостовані раннери, станом черги та безпечним…

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Openclaw Debugging

openclaw
ОрганізаціяПопулярне

Діагностуйте проблеми з моделями, провайдерами, інтерфейсом інструментів, режимом коду, потоковою передачею та роботою OpenClaw у реальному часі/Crabbox. Перш ніж змінювати код, добирайте потрібні журнали, перевірки та спосіб підтвердження, зокрема отримуйте збережені…

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Openclaw Live Updater

openclaw
ОрганізаціяПопулярне

Підтримуйте канонічну активну копію репозиторію OpenClaw main, Gateway під керуванням macOS LaunchAgent, локальну програму macOS, CI для точного коміту main і регулярну повну перевірку релізу. Використовуйте для швидкого оновлення…

82.2K
391K
Файлів: 2
Відкрити

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇