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?

ImageGenerationToolで画像生成をStreamlitに組み込む

0
Posted at

OpenAI Agents SDK — ImageGenerationTool で画像生成を Streamlit に組み込む

ChatGPT のように 「〇〇を描いて」 と言うと画像が生成される体験を、OpenAI Agents SDK の Hosted tool である ImageGenerationTool で再現します。

この記事では、Agent へのツール追加、ストリーミング中の status / 部分画像表示、セッション履歴からの再表示、そして FileSearchTool で読んだ内容をもとに画像を描く 実演までをまとめます。


ImageGenerationTool とは

ImageGenerationTool は OpenAI 側で動く Hosted tools のひとつです。Agent の tools=[...] に渡すと、モデルが必要と判断したときに画像生成を呼び出せます。

コンポーネント 役割
ImageGenerationTool テキスト(+文脈)から画像を生成
response.image_generation_call.* 生成進行のストリームイベント
image_generation_call(session item) 履歴に残る生成結果(base64)
st.image UI への表示

テキストだけの回答と違い、ツール結果は 画像バイナリ(base64) として返ってきます。


Agent に ImageGenerationTool を載せる

from agents import Agent, ImageGenerationTool

agent = Agent(
    name="Assistant",
    instructions="""
    あなたはChatGPTのようなAIアシスタントです。
    画像の生成を求められたときは ImageGenerationTool を使ってください。
    """,
    tools=[
        ImageGenerationTool(
            tool_config={
                "type": "image_generation",
                "quality": "low",
                "output_format": "jpeg",
                "moderation": "low",
                "partial_images": 1,
            }
        ),
    ],
)
設定 意味(この実演での使い方)
quality: "low" コスト・待ち時間を抑える
output_format: "jpeg" 結果形式
partial_images: 1 生成途中のプレビューを受け取る

partial_images を有効にすると、完成前の中間画像イベントをストリームで受け取れます。


ストリーミング — status と部分画像

status 表示

def update_status(status_container, event: str) -> None:
    status_messages = {
        "response.image_generation_call.generating": ("🎨 Drawing image...", "running"),
        "response.image_generation_call.in_progress": ("🎨 Drawing image...", "running"),
        "response.completed": ("✅ Response Completed", "complete"),
    }
    if event in status_messages:
        label, state = status_messages[event]
        status_container.update(label=label, state=state)
イベント UI
response.image_generation_call.in_progress 生成開始
response.image_generation_call.generating 描画中
response.image_generation_call.partial_image 途中プレビュー
response.output_text.delta テキスト回答

部分画像の表示

async def run_agent(message: str) -> str:
    with st.chat_message("assistant"):
        status_container = st.status("", expanded=False)
        text_placeholder = st.empty()
        image_placeholder = st.empty()
        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("$", "\\$"))
                elif event.data.type == "response.image_generation_call.partial_image":
                    image = base64.b64decode(event.data.partial_image_b64)
                    image_placeholder.image(image)

    return response

テキストは delta、画像は base64 → バイト列 → st.image で更新します。


履歴表示 — image_generation_call

セッションには次のような item が残ります。

{
  "type": "image_generation_call",
  "id": "ig_...",
  "status": "completed",
  "result": "/9j/4AAQ..." 
}

result が生成画像の base64 です。履歴再生時は次のようにデコードします。

if message.get("type") == "image_generation_call":
    result = message.get("result")
    if result:
        image = base64.b64decode(result)
        with st.chat_message("assistant"):
            st.image(image)
    continue

Streamlit は rerun のたびに画面を作り直すので、セッションに残した画像を履歴から再描画する 必要があります。


実演 1 — テキストだけで画像を描く

プロンプト:

シュナウザーを描いて

流れ:

  1. モデルが ImageGenerationTool を選択
  2. status が「🎨 Drawing image...」に更新
  3. partial_image → 完成画像が表示
  4. セッションに image_generation_call が保存される

2026-08-1123.01.05-ezgif.com-video-to-gif-converter.gif


実演 2 — FileSearch + ImageGeneration(ポートフォリオ → インフォグラフィック)

手元の資産メモ(ポートフォリオ txt)を FileSearch で読み、その内容をもとに Pixar 風インフォグラフィックを描く 流れです。

事前準備

  1. Apple 株・現金・その他資産などが書かれたポートフォリオ用 txt を用意
    (例: 以前 FileSearch の練習で使った資産メモ)
  2. Streamlit の chat_input から txt をアップロードし、Vector Store に載せる
  3. Agent には FileSearchToolImageGenerationTool の両方を渡しておく
tools=[
    FileSearchTool(
        vector_store_ids=[VECTOR_STORE_ID],
        max_num_results=3,
    ),
    ImageGenerationTool(
        tool_config={
            "type": "image_generation",
            "quality": "low",
            "output_format": "jpeg",
            "moderation": "low",
            "partial_images": 1,
        }
    ),
]

プロンプト

私のポートフォリオ、所有しているすべての株式、現金、資産などのインフォグラフィックをピクサースタイルで作って

何が起きるか

ツール 役割
FileSearchTool 「私のポートフォリオ」の中身(株数・現金など)を Vector Store から取得
ImageGenerationTool 取得した事実をもとに Pixar 風インフォグラフィックを生成

履歴には例えば次が並びます。

  1. file_search_call(検索クエリ)
  2. image_generation_call(生成画像)
  3. assistant の短いテキスト(「描きました」など)

image.png


参考リンク

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?