0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CodeInterpreterTool でコード実行を Streamlit に組み込む

0
Posted at

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 を載せる

CodeInterpreterTooltool_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_eventevent.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

ポイント

  1. event.data.delta に Python コードの断片が入る
  2. code_response に追記しながら st.code() で更新する
  3. テキスト回答(output_text.delta)と 別 placeholder に分けると、コードと説明文が同時に見える

st.code() はシンタックスハイライト付きのコードブロックを描画します。st.write()st.markdown() でも表示できますが、実行中の Python コードには st.code() が読みやすいです。


実演 — 数値計算をコードで解く

プロンプト:

273 × 312821 + 1782 の平方根を計算して。実行した Python コードも見せて。

流れ:

  1. モデルが CodeInterpreterTool を選択
  2. status が「💻 Running code...」に更新
  3. response.code_interpreter_call.delta でコードが st.code に流れる
  4. 実行結果をもとに assistant がテキストで回答

image.png

🎬 ここに実演動画を添付してください(プロンプト入力 → 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_configtypecontainer が必須
  • ストリームでは response.code_interpreter_call.delta でコード本文を st.code() にリアルタイム表示

テキスト生成だけでなく コード実行というアクション まで Agent に任せる一歩として、CodeInterpreterTool は実用的な入口です。


参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?