OpenAI Agents SDK — CodeInterpreterTool でコード実行を Streamlit に組み込む
OpenAI Agents SDK の Hosted tool である CodeInterpreterTool を Streamlit に組み込み、サンドボックス内での Python 実行と UI 表示を実装します。
この記事では、Agent へのツール追加、ストリーミング中の status / コード表示(response.code_interpreter_call.delta)をまとめます。
CodeInterpreterTool とは
CodeInterpreterTool は OpenAI 側の サンドボックス環境 で Python コードを実行する Hosted tool です。Agent の tools=[...] に渡すと、モデルが必要と判断したときにコードを生成・実行できます。
| コンポーネント | 役割 |
|---|---|
CodeInterpreterTool |
サンドボックス内で Python を実行 |
response.code_interpreter_call.* |
実行進行のストリームイベント |
st.code |
UI へのコード表示 |
テキスト回答だけでは難しい 数値計算・データ変換・ファイル処理 を、モデルがコードで解きます。
Agent に CodeInterpreterTool を載せる
CodeInterpreterTool は tool_config が必須 です。引数なしの CodeInterpreterTool() だけでは起動時に次のエラーになります。
TypeError: CodeInterpreterTool.__init__() missing 1 required positional argument: 'tool_config'
最小構成は次のとおりです。
from agents import Agent, CodeInterpreterTool
agent = Agent(
name="ChatGPT Clone Agent",
instructions="""
あなたはChatGPTのようなAIアシスタントです。
あなたは以下のツールにアクセスできます:
- CodeInterpreterTool: ユーザーの質問に答えるためにコードを作成して実行するために使用してください。
""",
tools=[
CodeInterpreterTool(
tool_config={
"type": "code_interpreter",
"container": {"type": "auto"},
}
),
],
)
| 設定 | 意味 |
|---|---|
type: "code_interpreter" |
ツール種別(必須) |
container.type: "auto" |
OpenAI がコンテナを自動管理 |
container には file_ids を指定して、あらかじめアップロードしたファイルをサンドボックスに渡すこともできます(Excel → PDF 変換など)。
CodeInterpreterTool(
tool_config={
"type": "code_interpreter",
"container": {
"type": "auto",
"file_ids": ["file-abc123"],
},
}
)
instructions に いつコード実行を使うか を書いておくと、モデルが tool を選びやすくなります。
ストリーミング — status とコードの delta 表示
status 表示
コード実行中も raw_response_event の event.data.type で進行状況が流れてきます。
def update_status(status_container, event: str) -> None:
status_messages = {
"response.code_interpreter_call.in_progress": ("💻 Running code...", "running"),
"response.code_interpreter_call.interpreting": ("💻 Running code...", "running"),
"response.code_interpreter_call.completed": ("💻 Ran code...", "complete"),
"response.code_interpreter_call.done": ("💻 Ran code...", "complete"),
"response.completed": ("✅ Response Completed", "complete"),
}
if event in status_messages:
label, state = status_messages[event]
status_container.update(label=label, state=state)
| イベント | UI |
|---|---|
response.code_interpreter_call.in_progress |
コード実行開始 |
response.code_interpreter_call.interpreting |
実行中 |
response.code_interpreter_call.completed / .done
|
実行完了 |
response.code_interpreter_call.delta |
コード本文のストリーム |
response.output_text.delta |
テキスト回答 |
response.code_interpreter_call.delta — コードをリアルタイム表示
画像生成の partial_image と同様、コードインタープリタも delta イベント で本文が少しずつ届きます。
async def run_agent(message: str) -> str:
with st.chat_message("assistant"):
status_container = st.status("⏳", expanded=False)
text_placeholder = st.empty()
code_placeholder = st.empty()
response = ""
code_response = ""
stream = Runner.run_streamed(agent, message, session=session)
async for event in stream.stream_events():
if event.type == "raw_response_event":
update_status(status_container, event.data.type)
if event.data.type == "response.output_text.delta":
response += event.data.delta
text_placeholder.write(response.replace("$", "\\$"))
# コード実行結果を表示
if event.data.type == "response.code_interpreter_call.delta":
code_response += event.data.delta
# code() は Markdown のコードブロックを表示するための関数
code_placeholder.code(code_response)
return response
ポイント
-
event.data.deltaに Python コードの断片が入る -
code_responseに追記しながらst.code()で更新する - テキスト回答(
output_text.delta)と 別 placeholder に分けると、コードと説明文が同時に見える
st.code() はシンタックスハイライト付きのコードブロックを描画します。st.write() や st.markdown() でも表示できますが、実行中の Python コードには st.code() が読みやすいです。
実演 — 数値計算をコードで解く
プロンプト:
273 × 312821 + 1782 の平方根を計算して。実行した Python コードも見せて。
流れ:
- モデルが
CodeInterpreterToolを選択 - status が「💻 Running code...」に更新
-
response.code_interpreter_call.deltaでコードがst.codeに流れる - 実行結果をもとに assistant がテキストで回答
🎬 ここに実演動画を添付してください(プロンプト入力 → Running code → コード表示 → 回答までの画面録画)
ハマりどころ
1. tool_config 忘れ
TypeError: CodeInterpreterTool.__init__() missing 1 required positional argument: 'tool_config'
→ tool_config={"type": "code_interpreter", "container": {"type": "auto"}} を必ず渡す。
2. delta と completed の使い分け
| 用途 | イベント |
|---|---|
| 実行中のコードをリアルタイム表示 | response.code_interpreter_call.delta |
| 進行 status の更新 |
response.code_interpreter_call.in_progress など |
3. 他 Hosted tool との共存
WebSearchTool / FileSearchTool / ImageGenerationTool と同じ Agent に載せられます。update_status の辞書に各 tool のイベントを足すだけです。
まとめ
-
CodeInterpreterToolは Hosted tool。tool_configにtypeとcontainerが必須 - ストリームでは
response.code_interpreter_call.deltaでコード本文をst.code()にリアルタイム表示
テキスト生成だけでなく コード実行というアクション まで Agent に任せる一歩として、CodeInterpreterTool は実用的な入口です。
