Responses APIについて
- テキスト・画像・動画などを1つのAPIに渡せる
- Web検索を内部で呼び出せる
- Pydanticで構造化出力できる
- 内部で複数のツールを循環できる
このあたりが便利かなと思います。
急いで開発したいとかには一度試してみるといいと思います。
なぜ書いたか
Web検索ツール(Web.run)を使うためにResponses APIを使う選択をしました。
Langchain/Langgraphで組んでいるフローの中にWeb.runのツールを組み込むためにLangchainでの実装が必要でした。
その備忘です。
公式のやり方
参考: https://platform.openai.com/docs/guides/tools-web-search?api-mode=responses
前提としてopenai>=1.53.0が必須です。
pip install "openai>=1.53.0"
環境変数OPENAI_API_KEYの設定も忘れず。api_keyから渡せますが念のため。
あとはドキュメント通り。Chat Completions APIとはちょっと違うので注意。
import os
from openai import OpenAI
from pprint import pprint
API_KEY = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key=API_KEY)
# Chat Completions APIを使用してWeb検索を実行する
response = client.responses.create(
model="gpt-5", # Web検索をサポートするモデル
tools=[{ "type": "web_search", "external_web_access": True }],
tool_choice="auto",
input=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What was a positive news story from today?"},
],
)
pprint(message.content[0].annotations) # アノテーション
print(response.output_text) # output_textを呼ぶ
アノテーションには出典と引用の情報が入っています。
参考: https://platform.openai.com/docs/guides/tools-web-search#output-and-citations
Langchainで使う
本題です。Langchain公式には書いてあるのですが、日本語での情報が無かったのでこちらの記事を書くことにしました。
Langchain公式: https://docs.langchain.com/oss/python/integrations/chat/openai
langchain-openaiのバージョン0.3.29以上でResponseAPIがサポートされています。
pip install " langchain-openai>=0.3.29
簡単な例
公式と同じようなことをやってみます。
import os
from langchain_openai import ChatOpenAI
from pprint import pprint
API_KEY = os.getenv("OPENAI_API_KEY")
llm = ChatOpenAI(
model="gpt-4.1-mini",
api_key=API_KEY,
use_responses_api=True # こいつをTrueにしてResponseAPIを呼び出す
)
tool = {"type": "web_search_preview"} # web searchのツールを渡す
llm_with_tools = llm.bind_tools([tool])
response = llm_with_tools.invoke("What was a positive news story from today?")
pprint(response.content_blocks) # 出力テキスト+注釈が含まれたcontent_blocks
print(response.text) # 純粋な出力テキスト
content_blocksには、先ほど取得したannotationsや出力テキストも一緒に入っています。
参考:https://docs.langchain.com/oss/python/integrations/chat/openai#web-search
Pydanticで構造化出力
BaseModelを継承したクラスをツールに渡すと、Structured Outputしてくれます。
with_structured_outputを使う必要はないです。
import os
import json
from pprint import pprint
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
API_KEY = os.getenv("OPENAI_API_KEY")
class NewsModel(BaseModel):
title: str = Field(..., description="tile of the news article")
summary: str = Field(..., description="summary of the news article")
date: str = Field(..., description="publication date of the news article")
llm = ChatOpenAI(
model="gpt-4.1-mini",
api_key=API_KEY,
use_responses_api=True
)
web_search_tool = {"type": "web_search_preview"}
llm_with_tools = llm.bind_tools(
[
web_search_tool, # Web searchを渡す
NewsModel, # Pydanticモデルを渡す -> 構造化データとして受け取れる
]
)
response = llm_with_tools.invoke("What was a positive news story from today?")
tool_call = response.tool_calls[0] # 最初のツール(構造化出力)呼び出しを取得
news = NewsModel(**tool_call["args"])
print(json.dumps(
news.model_dump(),
ensure_ascii=False,
indent=2
))
pprint(response.content_blocks)
出力:
{
"title": "China Ratifies High Seas Treaty for Ocean Conservation",
"summary": "China, the world's largest fishing nation, ratified the High Seas Treaty, joining over 60 countries to protect marine life, create marine protected areas, share genetic resources, and curb illegal fishing across two-thirds of the ocean.",
"date": "2025-11-19"
}
ちゃんと検索して取れてますね
[{'args': {'query': 'positive news stories today', 'type': 'search'},
'id': 'ws_046b1d74da4df09300691e1cbc147081959e425a635816da70',
'name': 'web_search',
'type': 'server_tool_call'},
{'status': 'success',
'tool_call_id': 'ws_046b1d74da4df09300691e1cbc147081959e425a635816da70',
'type': 'server_tool_result'},
{'annotations': [{'end_index': 725,
'start_index': 569,
'title': 'Education News Today in English November 19th '
'2025: BIMSTEC Young Diplomats Programme, ‘YUVA AI '
'for ALL’ Course, and More | Education News - '
'Jagran Josh',
'type': 'citation',
'url': 'https://www.jagranjosh.com/news/today-education-news-in-english-19th-november-2025-latest-updates-and-headlines-181867?utm_source=openai'},
{'end_index': 1307,
'start_index': 1191,
'title': "Today's Good News | OGN Daily",
'type': 'citation',
'url': 'https://www.onlygoodnewsdaily.com/post/good-news-of-the-day-19-nov-2025?utm_source=openai'},
{'end_index': 1743,
'start_index': 1624,
'title': "Today's biggest science news: U.S. measles status "
'| NASA comet 3I/ATLAS images | Leaking spy '
'satellites | Live Science',
'type': 'citation',
'url': 'https://www.livescience.com/space/live/latest-science-news-wednesday-nov-19-2025?utm_source=openai'},
{'end_index': 2288,
'start_index': 2085,
'title': 'School Assembly News Headlines Today (19 '
'November): Hornbill Festival, 2026 FIFA World '
'Cup,and Other News in English',
'type': 'citation',
'url': 'https://www.jagranjosh.com/articles/school-assembly-news-headlines-today-19-november-2025-hornbill-festival-2026-fifa-world-cup-and-other-important-news-1800005373-1?utm_source=openai'},
{'end_index': 2766,
'start_index': 2677,
'title': 'Headlines for November 19, 2025 | Democracy Now!',
'type': 'citation',
'url': 'https://www.democracynow.org/2025/11/19/headlines?utm_source=openai'}],
'id': 'msg_046b1d74da4df09300691e1cbcf3548195b1faef4448f2758c',
'text': 'Here are some positive news stories from today, November 19, 2025:\n'
'\n'
'**1. India Hosts BIMSTEC Young Diplomats Programme**\n'
'\n'
'India has launched the annual BIMSTEC Young Diplomats Interaction '
'Programme at the Sushma Swaraj Institute of Foreign Service in New '
'Delhi. Fourteen young diplomats from Bangladesh, Bhutan, Myanmar, '
'Nepal, and Sri Lanka are participating in this week-long event, '
'aiming to enhance cooperation among young diplomats in the Bay of '
"Bengal region. This initiative reflects India's commitment to "
'fostering regional collaboration and capacity-building. '
'([jagranjosh.com](https://www.jagranjosh.com/news/today-education-news-in-english-19th-november-2025-latest-updates-and-headlines-181867?utm_source=openai))\n'
'\n'
'**2. China Ratifies High Seas Treaty**\n'
'\n'
"China, the world's largest fishing nation, has ratified the High "
'Seas Treaty, joining over 60 countries in establishing a framework '
'for creating marine protected areas, sharing genetic resources, and '
'curbing illegal fishing across two-thirds of the ocean. This '
'legally binding global legislation aims to protect marine life in '
'areas beyond national jurisdiction, marking a significant step '
'toward global ocean conservation. '
'([onlygoodnewsdaily.com](https://www.onlygoodnewsdaily.com/post/good-news-of-the-day-19-nov-2025?utm_source=openai))\n'
'\n'
'**3. U.S. Measles Status Declared**\n'
'\n'
'The United States has been declared measles-free, with no reported '
'cases in the past year. This achievement is attributed to '
'widespread vaccination efforts and public health initiatives, '
'highlighting the effectiveness of immunization programs in '
'preventing infectious diseases. '
'([livescience.com](https://www.livescience.com/space/live/latest-science-news-wednesday-nov-19-2025?utm_source=openai))\n'
'\n'
'**4. NASA and SpaceX Launch Sentinel 6 Satellite**\n'
'\n'
'NASA and SpaceX have successfully launched the Sentinel 6 '
'satellite, a joint U.S.-European mission designed to monitor '
"Earth's oceans. The satellite will provide critical data on "
'sea-level rise and ocean health, contributing to our understanding '
'of climate change and its global impacts. '
'([jagranjosh.com](https://www.jagranjosh.com/articles/school-assembly-news-headlines-today-19-november-2025-hornbill-festival-2026-fifa-world-cup-and-other-important-news-1800005373-1?utm_source=openai))\n'
'\n'
'**5. U.S. Federal Judge Rules in Favor of Meta in Antitrust Case**\n'
'\n'
'A federal judge ruled in favor of Meta (formerly Facebook) in an '
'antitrust lawsuit filed by the Federal Trade Commission. The judge '
"determined that Meta's acquisitions of Instagram and WhatsApp did "
'not constitute anti-competitive behavior, allowing the company to '
'continue its business operations without restrictions. '
'([democracynow.org](https://www.democracynow.org/2025/11/19/headlines?utm_source=openai))\n'
'\n'
'These stories highlight positive developments in international '
'cooperation, environmental conservation, public health, space '
'exploration, and business law. ',
'type': 'text'},
{'args': {'date': '2025-11-19',
'summary': "China, the world's largest fishing nation, ratified the "
'High Seas Treaty, joining over 60 countries to protect '
'marine life, create marine protected areas, share '
'genetic resources, and curb illegal fishing across '
'two-thirds of the ocean.',
'title': 'China Ratifies High Seas Treaty for Ocean Conservation'},
'extras': {'item_id': 'fc_046b1d74da4df09300691e1cc115f4819596de92c826c8f7c9'},
'id': 'call_pv5oqiPZUoWZCXqovYst19so',
'name': 'NewsModel',
'type': 'tool_call'}]
まとめ
正直もっと賢い方法があったら教えてほしい