scaffolding-openai-agents
Builds AI agents using OpenAI Agents SDK with async/await patterns and multi-agent orchestration. Use when creating tutoring agents, building agent handoffs, implementing tool-calling agents, or orchestrating multiple specialists. Covers Agent class, Runner patterns, function tools, guardrails, and streaming responses. NOT when using raw OpenAI API without SDK or other agent frameworks like LangChain.
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o scaffolding-openai-agents.zip https://jpskill.com/download/17316.zip && unzip -o scaffolding-openai-agents.zip && rm scaffolding-openai-agents.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17316.zip -OutFile "$d\scaffolding-openai-agents.zip"; Expand-Archive "$d\scaffolding-openai-agents.zip" -DestinationPath $d -Force; ri "$d\scaffolding-openai-agents.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
scaffolding-openai-agents.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
scaffolding-openai-agentsフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 2
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
OpenAI Agents のスキャフォールディング
ネイティブな async/await パターンで OpenAI Agents SDK を使用して、本番環境向けの AI エージェントを構築します。
クイックスタート
# プロジェクトのセットアップ
mkdir my-agent && cd my-agent
python -m venv .venv && source .venv/bin/activate
pip install openai-agents
# API キーの設定
export OPENAI_API_KEY=sk-...
# main.py
import asyncio
from agents import Agent, Runner
agent = Agent(
name="Python Tutor",
instructions="Python を学ぶ学生を支援します。概念を例を挙げて明確に説明します。"
)
async def main():
result = await Runner.run(agent, "リスト内包表記について説明してください")
print(result.final_output)
asyncio.run(main())
エージェントの設定
基本的なエージェント
from agents import Agent
tutor = Agent(
name="Python Tutor",
instructions="""あなたは Python のエキスパートチューターです。
概念を例を挙げて明確に説明します。
必要に応じて明確にするための質問をします。
説明の後に練習問題を提供します。""",
model="gpt-4o"
)
モデル設定あり
from agents import Agent, ModelSettings
agent = Agent(
name="Creative Writer",
instructions="プロンプトに基づいて創造的な物語を書きます。",
model="gpt-4o",
model_settings=ModelSettings(
temperature=0.9,
max_tokens=2000
)
)
構造化された出力あり
from pydantic import BaseModel
from agents import Agent
class CodeReview(BaseModel):
issues: list[str]
suggestions: list[str]
score: int
reviewer = Agent(
name="Code Reviewer",
instructions="Python コードの問題点と改善点をレビューします。",
output_type=CodeReview # 構造化された JSON 出力を強制します
)
Runner パターン
Async Run (プライマリ)
import asyncio
from agents import Agent, Runner
async def main():
agent = Agent(name="Helper", instructions="役に立ちます")
# 単一のクエリ
result = await Runner.run(agent, "Python とは何ですか?")
print(result.final_output)
# 会話履歴あり
messages = [
{"role": "user", "content": "私の名前は Alex です"},
{"role": "assistant", "content": "はじめまして、Alex さん!"},
{"role": "user", "content": "私の名前は何ですか?"}
]
result = await Runner.run(agent, messages)
print(result.final_output) # "あなたの名前は Alex です"
asyncio.run(main())
Sync Run (シンプルなスクリプト)
from agents import Agent, Runner
agent = Agent(name="Helper", instructions="役に立ちます")
result = Runner.run_sync(agent, "こんにちは!")
print(result.final_output)
Streaming Run
import asyncio
from agents import Agent, Runner
async def main():
agent = Agent(name="Storyteller", instructions="魅力的な物語を語ります")
result = Runner.run_streamed(agent, "短い物語を教えてください")
async for event in result.stream_events():
if hasattr(event, 'delta'):
print(event.delta, end='', flush=True)
print() # 最後に改行
asyncio.run(main())
会話の継続
async def chat_session():
agent = Agent(name="Tutor", instructions="あなたは Python チューターです")
# 最初のターン
result1 = await Runner.run(agent, "デコレータについて説明してください")
print(f"Tutor: {result1.final_output}")
# 会話を続ける
messages = result1.to_input_list() + [
{"role": "user", "content": "例を見せてください"}
]
result2 = await Runner.run(agent, messages)
print(f"Tutor: {result2.final_output}")
Function Tools
基本的なツール
from agents import Agent, function_tool
@function_tool
def get_current_time() -> str:
"""現在の時刻を取得します。"""
from datetime import datetime
return datetime.now().strftime("%H:%M:%S")
@function_tool
def calculate(expression: str) -> float:
"""数式を計算します。
Args:
expression: "2 + 2" や "10 * 5" のような有効な Python 数式
"""
return eval(expression) # 本番環境では safe_eval を使用してください
agent = Agent(
name="Assistant",
instructions="計算と時間の問い合わせを支援します。",
tools=[get_current_time, calculate]
)
Async Tool
import httpx
from agents import Agent, function_tool
@function_tool
async def fetch_weather(city: str) -> str:
"""都市の現在の天気を取得します。
Args:
city: 天気を取得する都市名
"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://wttr.in/{city}?format=3"
)
return response.text
agent = Agent(
name="Weather Bot",
instructions="天気情報を提供します。",
tools=[fetch_weather]
)
Pydantic 型のツール
from pydantic import BaseModel
from agents import Agent, function_tool
class SearchQuery(BaseModel):
query: str
max_results: int = 10
class SearchResult(BaseModel):
title: str
url: str
snippet: str
@function_tool
async def search_docs(params: SearchQuery) -> list[SearchResult]:
"""クエリのドキュメントを検索します。"""
# 実装
return [SearchResult(
title="Python Tutorial",
url="https://docs.python.org",
snippet="Official Python documentation..."
)]
agent = Agent(
name="Doc Search",
instructions="Python ドキュメントを検索します。",
tools=[search_docs]
)
Multi-Agent パターン
Handoffs (ルーティングに推奨)
from agents import Agent, Runner
# スペシャリストエージェント
concepts_agent = Agent(
name="Concepts Tutor",
handoff_description="Python の概念と基礎を説明します",
instructions="Python の概念を例を挙げて明確に説明します。"
)
debug_agent = Agent(
name="Debug Helper",
handoff_description="Python コードのエラーのデバッグを支援します",
instruction
(原文がここで切り詰められています) 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Scaffolding OpenAI Agents
Build production AI agents using OpenAI Agents SDK with native async/await patterns.
Quick Start
# Project setup
mkdir my-agent && cd my-agent
python -m venv .venv && source .venv/bin/activate
pip install openai-agents
# Set API key
export OPENAI_API_KEY=sk-...
# main.py
import asyncio
from agents import Agent, Runner
agent = Agent(
name="Python Tutor",
instructions="You help students learn Python. Explain concepts clearly with examples."
)
async def main():
result = await Runner.run(agent, "Explain list comprehensions")
print(result.final_output)
asyncio.run(main())
Agent Configuration
Basic Agent
from agents import Agent
tutor = Agent(
name="Python Tutor",
instructions="""You are an expert Python tutor.
Explain concepts clearly with examples.
Ask clarifying questions when needed.
Provide practice exercises after explanations.""",
model="gpt-4o"
)
With Model Settings
from agents import Agent, ModelSettings
agent = Agent(
name="Creative Writer",
instructions="Write creative stories based on prompts.",
model="gpt-4o",
model_settings=ModelSettings(
temperature=0.9,
max_tokens=2000
)
)
With Structured Output
from pydantic import BaseModel
from agents import Agent
class CodeReview(BaseModel):
issues: list[str]
suggestions: list[str]
score: int
reviewer = Agent(
name="Code Reviewer",
instructions="Review Python code for issues and improvements.",
output_type=CodeReview # Forces structured JSON output
)
Runner Patterns
Async Run (Primary)
import asyncio
from agents import Agent, Runner
async def main():
agent = Agent(name="Helper", instructions="Be helpful")
# Single query
result = await Runner.run(agent, "What is Python?")
print(result.final_output)
# With conversation history
messages = [
{"role": "user", "content": "My name is Alex"},
{"role": "assistant", "content": "Nice to meet you, Alex!"},
{"role": "user", "content": "What's my name?"}
]
result = await Runner.run(agent, messages)
print(result.final_output) # "Your name is Alex"
asyncio.run(main())
Sync Run (Simple Scripts)
from agents import Agent, Runner
agent = Agent(name="Helper", instructions="Be helpful")
result = Runner.run_sync(agent, "Hello!")
print(result.final_output)
Streaming Run
import asyncio
from agents import Agent, Runner
async def main():
agent = Agent(name="Storyteller", instructions="Tell engaging stories")
result = Runner.run_streamed(agent, "Tell me a short story")
async for event in result.stream_events():
if hasattr(event, 'delta'):
print(event.delta, end='', flush=True)
print() # Newline at end
asyncio.run(main())
Conversation Continuation
async def chat_session():
agent = Agent(name="Tutor", instructions="You are a Python tutor")
# First turn
result1 = await Runner.run(agent, "Explain decorators")
print(f"Tutor: {result1.final_output}")
# Continue conversation
messages = result1.to_input_list() + [
{"role": "user", "content": "Show me an example"}
]
result2 = await Runner.run(agent, messages)
print(f"Tutor: {result2.final_output}")
Function Tools
Basic Tool
from agents import Agent, function_tool
@function_tool
def get_current_time() -> str:
"""Get the current time."""
from datetime import datetime
return datetime.now().strftime("%H:%M:%S")
@function_tool
def calculate(expression: str) -> float:
"""Calculate a mathematical expression.
Args:
expression: A valid Python math expression like "2 + 2" or "10 * 5"
"""
return eval(expression) # Use safe_eval in production
agent = Agent(
name="Assistant",
instructions="Help with calculations and time queries.",
tools=[get_current_time, calculate]
)
Async Tool
import httpx
from agents import Agent, function_tool
@function_tool
async def fetch_weather(city: str) -> str:
"""Fetch current weather for a city.
Args:
city: The city name to get weather for
"""
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://wttr.in/{city}?format=3"
)
return response.text
agent = Agent(
name="Weather Bot",
instructions="Provide weather information.",
tools=[fetch_weather]
)
Tool with Pydantic Types
from pydantic import BaseModel
from agents import Agent, function_tool
class SearchQuery(BaseModel):
query: str
max_results: int = 10
class SearchResult(BaseModel):
title: str
url: str
snippet: str
@function_tool
async def search_docs(params: SearchQuery) -> list[SearchResult]:
"""Search documentation for a query."""
# Implementation
return [SearchResult(
title="Python Tutorial",
url="https://docs.python.org",
snippet="Official Python documentation..."
)]
agent = Agent(
name="Doc Search",
instructions="Search Python documentation.",
tools=[search_docs]
)
Multi-Agent Patterns
Handoffs (Recommended for Routing)
from agents import Agent, Runner
# Specialist agents
concepts_agent = Agent(
name="Concepts Tutor",
handoff_description="Explains Python concepts and fundamentals",
instructions="Explain Python concepts clearly with examples."
)
debug_agent = Agent(
name="Debug Helper",
handoff_description="Helps debug Python code errors",
instructions="Help diagnose and fix Python errors."
)
exercise_agent = Agent(
name="Exercise Generator",
handoff_description="Creates practice problems and exercises",
instructions="Generate practice problems with solutions."
)
# Triage agent with handoffs
triage_agent = Agent(
name="Triage",
instructions="""Route student questions to the right specialist:
- Concepts questions → Concepts Tutor
- Error/bug questions → Debug Helper
- Practice requests → Exercise Generator
Analyze the question and hand off to the appropriate agent.""",
handoffs=[concepts_agent, debug_agent, exercise_agent]
)
async def main():
# Question gets routed automatically
result = await Runner.run(
triage_agent,
"I'm getting a KeyError in my dictionary code"
)
print(result.final_output) # Handled by debug_agent
Agents as Tools (Orchestration)
from agents import Agent, Runner
# Create specialist agents
researcher = Agent(
name="Researcher",
instructions="Research topics thoroughly."
)
writer = Agent(
name="Writer",
instructions="Write clear, engaging content."
)
# Manager uses agents as tools
manager = Agent(
name="Content Manager",
instructions="""Coordinate research and writing:
1. Use researcher tool to gather information
2. Use writer tool to create content""",
tools=[
researcher.as_tool(
tool_name="research",
tool_description="Research a topic"
),
writer.as_tool(
tool_name="write",
tool_description="Write content about a topic"
)
]
)
async def main():
result = await Runner.run(
manager,
"Create a blog post about async Python"
)
print(result.final_output)
Guardrails
Input Validation
from agents import Agent, input_guardrail, GuardrailFunctionOutput
@input_guardrail
async def check_homework_topic(context, agent, input_text: str) -> GuardrailFunctionOutput:
"""Ensure questions are homework-related."""
keywords = ["python", "code", "programming", "function", "class", "error"]
if not any(kw in input_text.lower() for kw in keywords):
return GuardrailFunctionOutput(
output_info="Not a programming question",
tripwire_triggered=True
)
return GuardrailFunctionOutput(
output_info="Valid programming question",
tripwire_triggered=False
)
tutor = Agent(
name="Python Tutor",
instructions="Help with Python homework.",
input_guardrails=[check_homework_topic]
)
Output Validation
from agents import Agent, output_guardrail, GuardrailFunctionOutput
@output_guardrail
async def check_no_solutions(context, agent, output: str) -> GuardrailFunctionOutput:
"""Ensure we don't give complete homework solutions."""
solution_indicators = ["here's the complete", "full solution", "copy this code"]
if any(ind in output.lower() for ind in solution_indicators):
return GuardrailFunctionOutput(
output_info="Contains complete solution",
tripwire_triggered=True
)
return GuardrailFunctionOutput(
output_info="Output is appropriate",
tripwire_triggered=False
)
tutor = Agent(
name="Python Tutor",
instructions="Guide students without giving full solutions.",
output_guardrails=[check_no_solutions]
)
Context Injection
Shared State Across Agents
from dataclasses import dataclass
from agents import Agent, Runner, function_tool, RunContextWrapper
@dataclass
class TutoringContext:
student_id: str
session_id: str
topics_covered: list[str]
difficulty_level: str = "beginner"
@function_tool
def log_topic(wrapper: RunContextWrapper[TutoringContext], topic: str) -> str:
"""Log a topic as covered in this session."""
wrapper.context.topics_covered.append(topic)
return f"Logged: {topic}"
tutor = Agent(
name="Python Tutor",
instructions="Teach Python, tracking topics covered.",
tools=[log_topic]
)
async def main():
ctx = TutoringContext(
student_id="student-123",
session_id="session-456",
topics_covered=[]
)
result = await Runner.run(
tutor,
"Teach me about loops",
context=ctx
)
print(f"Topics covered: {ctx.topics_covered}")
Project Structure
learnflow-agents/
├── agents/
│ ├── __init__.py
│ ├── triage.py # Routing agent
│ ├── concepts.py # Concepts specialist
│ ├── debug.py # Debug specialist
│ └── exercise.py # Exercise generator
├── tools/
│ ├── __init__.py
│ ├── code_runner.py # Execute Python safely
│ └── search.py # Search documentation
├── guardrails/
│ ├── __init__.py
│ ├── input.py # Input validation
│ └── output.py # Output validation
├── main.py # FastAPI integration
└── pyproject.toml
FastAPI Integration
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from agents import Agent, Runner
app = FastAPI()
# Initialize agents
triage = Agent(
name="Triage",
instructions="Route questions to specialists",
handoffs=[concepts_agent, debug_agent]
)
class Question(BaseModel):
text: str
session_id: str
class Answer(BaseModel):
response: str
agent_used: str
@app.post("/ask", response_model=Answer)
async def ask_question(question: Question):
try:
result = await Runner.run(triage, question.text)
return Answer(
response=result.final_output,
agent_used=result.last_agent.name
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/ask/stream")
async def ask_stream(question: Question):
from fastapi.responses import StreamingResponse
async def generate():
result = Runner.run_streamed(triage, question.text)
async for event in result.stream_events():
if hasattr(event, 'delta'):
yield event.delta
return StreamingResponse(generate(), media_type="text/plain")
Tracing & Debugging
View Traces
Traces available at: https://platform.openai.com/traces
Custom Tracing
from agents import Runner, RunConfig
config = RunConfig(
workflow_name="tutoring-session",
trace_id="custom-trace-123"
)
result = await Runner.run(agent, "Hello", run_config=config)
Verification
Run: python scripts/verify.py
Related Skills
configuring-dapr-pubsub- Agent-to-agent messagingscaffolding-fastapi-dapr- FastAPI backend integrationstreaming-llm-responses- Response streaming patternsbuilding-chat-interfaces- Frontend chat UI
同梱ファイル
※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。
- 📄 SKILL.md (13,700 bytes)
- 📎 scripts/verify.py (1,170 bytes)