LangChain 構造化出力
ほとんどの場合、必要なのは自由なテキストではなく、構造化されたデータ——例えば JSON オブジェクト——です。
LangChain の構造化出力(Structured Output) は、Agent が指定した形式で結果を返すようにし、プログラムが直接使用しやすくします。
なぜ構造化出力が必要か
ユーザーの説明文から名前、年齢、職業を抽出する必要があるとしましょう:
| 方法 | 出力形式 | 後続処理 |
|---|---|---|
| 通常の返信 | "張三は今年28歳で、エンジニアです" | 正規表現やモデルの再呼び出しによる解析が必要 |
| 構造化出力 | {name: "张三", age: 28, job: "工程师"} | Python オブジェクトとして直接使用可能 |
構造化出力は「テキストからデータを解析する」という手順を省き、AI の出力をプログラムが直接使用できるようにします。
最も簡単な使い方——Pydantic モデルを渡す
Pydantic モデルを response_format パラメータに渡すだけです:
実例
from dotenv import load_dotenv
load_dotenv()
from pydantic import BaseModel, Field
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
# 期待する出力構造を定義
class CourseInfo(BaseModel):
"""サンプル コース抽出結果"""
course_name: str = Field(description="コース名")
difficulty: str = Field(description="難易度:入門/中級/上級")
estimated_hours: int = Field(description="予想学習時間(時間)")
is_free: bool = Field(description="無料かどうか")
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
agent = create_agent(
model=model,
response_format=CourseInfo, # Pydantic モデルを渡す
system_prompt="あなたはサンプル のコースアシスタントです。ユーザーの説明からコース情報を抽出してください。",
)
# ユーザーが非構造化の説明を入力
result = agent.invoke({
"messages": [HumanMessage(
content="最近 Python3 基礎チュートリアルを勉強しています。入門レベルで、"
"約20時間かかり、しかも完全に無料です"
)]
})
# structured_response から構造化結果を取得
if "structured_response" in result:
course = result["structured_response"]
print(f"コース名: {course.course_name}")
print(f"難易度: {course.difficulty}")
print(f"予想時間: {course.estimated_hours} 時間")
print(f無料: {'はい' if course.is_free else 'いいえ'})
print(f"オブジェクト型: {type(course)}")
load_dotenv()
from pydantic import BaseModel, Field
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
# 期待する出力構造を定義
class CourseInfo(BaseModel):
"""サンプル コース抽出結果"""
course_name: str = Field(description="コース名")
difficulty: str = Field(description="難易度:入門/中級/上級")
estimated_hours: int = Field(description="予想学習時間(時間)")
is_free: bool = Field(description="無料かどうか")
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
agent = create_agent(
model=model,
response_format=CourseInfo, # Pydantic モデルを渡す
system_prompt="あなたはサンプル のコースアシスタントです。ユーザーの説明からコース情報を抽出してください。",
)
# ユーザーが非構造化の説明を入力
result = agent.invoke({
"messages": [HumanMessage(
content="最近 Python3 基礎チュートリアルを勉強しています。入門レベルで、"
"約20時間かかり、しかも完全に無料です"
)]
})
# structured_response から構造化結果を取得
if "structured_response" in result:
course = result["structured_response"]
print(f"コース名: {course.course_name}")
print(f"難易度: {course.difficulty}")
print(f"予想時間: {course.estimated_hours} 時間")
print(f無料: {'はい' if course.is_free else 'いいえ'})
print(f"オブジェクト型: {type(course)}")
実行結果:
コース名: Python3 基础教程 難易度: 入门 所要時間: 20 小时 無料: 是 オブジェクトタイプ: <class '__main__.CourseInfo'>
返される structured_response は通常の辞書ではなく、Pydantic モデルのインスタンスです。つまり、.course_name などの属性でアクセスでき、IDE も自動補完を提供できます。
ツールと共存する Structured Output
response_format と tools は同時に使用できます——Agent は必要に応じてツールを呼び出し、最終的に構造化データを出力します:
実例
from pydantic import BaseModel, Field
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langchain.tools import tool
@tool
def search_course(keyword: str) -> str:
"""サンプル でコース情報を検索"""
courses = {
"python": "Python3 基礎チュートリアル | 入門 | 無料 | 30章 | 約20時間",
"java": "Java 基礎チュートリアル | 入門 | 無料 | 35章 | 約25時間",
"データ分析": "Python データ分析 | 中級 | 会員 | 25章 | 約30時間",
}
return courses.get(keyword.lower(), f"'{keyword}' に関連するコースが見つかりません")
class CourseRecommendation(BaseModel):
"""コース推薦結果"""
course_name: str = Field(description="推薦コース名")
reason: str = Field(description="推薦理由")
difficulty: str = Field(description="難易度:入門/中級/上級")
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
agent = create_agent(
model=model,
tools=[search_course],
response_format=CourseRecommendation,
system_prompt="あなたはサンプル のコースアドバイザーです。コースを検索してから推薦を提示してください。",
)
result = agent.invoke({
"messages": [HumanMessage(content="Python を学びたいのですが、おすすめはありますか?")]
})
rec = result["structured_response"]
print(f"推薦コース: {rec.course_name}")
print(f"推薦理由: {rec.reason}")
print(f"難易度: {rec.difficulty}")
# 完全なプロセスを確認
print("\n=== 実行プロセス ===")
for msg in result["messages"]:
if msg.type == "tool":
print(f" 呼び出し {msg.name}: {msg.content}")
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langchain.tools import tool
@tool
def search_course(keyword: str) -> str:
"""サンプル でコース情報を検索"""
courses = {
"python": "Python3 基礎チュートリアル | 入門 | 無料 | 30章 | 約20時間",
"java": "Java 基礎チュートリアル | 入門 | 無料 | 35章 | 約25時間",
"データ分析": "Python データ分析 | 中級 | 会員 | 25章 | 約30時間",
}
return courses.get(keyword.lower(), f"'{keyword}' に関連するコースが見つかりません")
class CourseRecommendation(BaseModel):
"""コース推薦結果"""
course_name: str = Field(description="推薦コース名")
reason: str = Field(description="推薦理由")
difficulty: str = Field(description="難易度:入門/中級/上級")
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
agent = create_agent(
model=model,
tools=[search_course],
response_format=CourseRecommendation,
system_prompt="あなたはサンプル のコースアドバイザーです。コースを検索してから推薦を提示してください。",
)
result = agent.invoke({
"messages": [HumanMessage(content="Python を学びたいのですが、おすすめはありますか?")]
})
rec = result["structured_response"]
print(f"推薦コース: {rec.course_name}")
print(f"推薦理由: {rec.reason}")
print(f"難易度: {rec.difficulty}")
# 完全なプロセスを確認
print("\n=== 実行プロセス ===")
for msg in result["messages"]:
if msg.type == "tool":
print(f" 呼び出し {msg.name}: {msg.content}")
実行結果:
おすすめコース: Python3 基础教程 理由: 该课程免费且适合Python初学者,学习时长约20小时 難易度: 入门 === 执行过程 === 调用 search_course: Python3 基础教程 | 入门 | 免费 | 30章 | 约20小时
複雑なネスト構造
Pydantic はネスト、リスト、列挙型などの複雑な構造をサポートしています:
実例
from pydantic import BaseModel, Field
from typing import Literal
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
class Topic(BaseModel):
"""知識ポイント"""
name: str = Field(description="知識ポイント名")
order: int = Field(description="学習順序、1 から始まる")
minutes: int = Field(description="推奨学習時間(分)")
class LearningPlan(BaseModel):
"""学習計画"""
goal: str = Field(description="学習目標の概要")
level: Literal["入門", "中級", "上級"] = Field(description="難易度レベル")
total_hours: float = Field(description="合計時間(時間)")
topics: list[Topic] = Field(description="知識ポイントリスト")
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
agent = create_agent(
model=model,
response_format=LearningPlan,
system_prompt="あなたはサンプル の学習プランナーです。",
)
result = agent.invoke({
"messages": [HumanMessage(
content="Python 入門の学習計画を立ててください。合計時間は10時間以内に抑えてください"
)]
})
plan = result["structured_response"]
print(f"目標: {plan.goal}")
print(f"難易度: {plan.level}")
print(f"合計時間: {plan.total_hours} 時間")
print(f"\n"知識ポイントリスト ({len(plan.topics)} 個):")
for topic in plan.topics:
print(f" {topic.order}. {topic.name} ({topic.minutes}分)")
from typing import Literal
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
class Topic(BaseModel):
"""知識ポイント"""
name: str = Field(description="知識ポイント名")
order: int = Field(description="学習順序、1 から始まる")
minutes: int = Field(description="推奨学習時間(分)")
class LearningPlan(BaseModel):
"""学習計画"""
goal: str = Field(description="学習目標の概要")
level: Literal["入門", "中級", "上級"] = Field(description="難易度レベル")
total_hours: float = Field(description="合計時間(時間)")
topics: list[Topic] = Field(description="知識ポイントリスト")
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
agent = create_agent(
model=model,
response_format=LearningPlan,
system_prompt="あなたはサンプル の学習プランナーです。",
)
result = agent.invoke({
"messages": [HumanMessage(
content="Python 入門の学習計画を立ててください。合計時間は10時間以内に抑えてください"
)]
})
plan = result["structured_response"]
print(f"目標: {plan.goal}")
print(f"難易度: {plan.level}")
print(f"合計時間: {plan.total_hours} 時間")
print(f"\n"知識ポイントリスト ({len(plan.topics)} 個):")
for topic in plan.topics:
print(f" {topic.order}. {topic.name} ({topic.minutes}分)")
実行結果:
目标: 掌握 Python 基础语法,能够独立编写简单的 Python 程序 難易度: 入门 总时长: 9.5 小时 知识点列表 (6 个): 1. 环境搭建与基础语法 (60分钟) 2. 数据类型与变量 (90分钟) 3. 条件判断与循环 (120分钟) 4. 函数与模块 (120分钟) 5. 列表与字典 (90分钟) 6. 综合练习 (90分钟)
メッセージから構造化出力を取得する
Agent のツール呼び出し機能が不要で、テキストから構造化情報を抽出したいだけの場合は、モデルを直接使用できます:
実例
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
class SentimentResult(BaseModel):
"""感情分析結果"""
sentiment: str = Field(description="ポジティブ/ネガティブ/ニュートラル")
score: float = Field(description="感情強度 0~1")
keywords: list[str] = Field(description="主要な感情語")
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
# モデルで直接 with_structured_output() を使用
# Agent は不要
structured_model = model.with_structured_output(SentimentResult)
texts = [
"サンプル は本当に使いやすく、強くおすすめします!",
"このチュートリアルは内容が少なすぎて、あまり価値がありません。",
"今日は天気がいいですね。",
]
for text in texts:
result = structured_model.invoke(text)
print(f"テキスト: {text[:30]}...")
print(f" 感情: {result.sentiment}, 強度: {result.score}, キーワード: {result.keywords}")
from langchain.chat_models import init_chat_model
class SentimentResult(BaseModel):
"""感情分析結果"""
sentiment: str = Field(description="ポジティブ/ネガティブ/ニュートラル")
score: float = Field(description="感情強度 0~1")
keywords: list[str] = Field(description="主要な感情語")
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)
# モデルで直接 with_structured_output() を使用
# Agent は不要
structured_model = model.with_structured_output(SentimentResult)
texts = [
"サンプル は本当に使いやすく、強くおすすめします!",
"このチュートリアルは内容が少なすぎて、あまり価値がありません。",
"今日は天気がいいですね。",
]
for text in texts:
result = structured_model.invoke(text)
print(f"テキスト: {text[:30]}...")
print(f" 感情: {result.sentiment}, 強度: {result.score}, キーワード: {result.keywords}")
実行結果:
テキスト: サンプル 真的太好用了,强烈推荐!... 感情: 积极, 强度: 0.95, 关键词: ['好用', '推荐'] テキスト: 这个教程内容太少了,不太值。... 感情: 消极, 强度: 0.7, 关键词: ['内容太少', '不太值'] テキスト: 今天天气不错。... 感情: 中性, 强度: 0.1, 关键词: ['不错']
その他の拡張with_structured_output() は model のメソッドで、Agent なしで使用できます。シナリオが「多段階推論」ではなく「情報抽出」の場合は、with_structured_output() を直接使う方が簡潔で効率的です。