この書籍を購入しました。
gihyo.jp
第4章に「Structured Output」が出てきます。
書籍ではOpenAIを使っていますがOllamaを使ってみました。
Pythonスクリプト
「qwen2.5」というモデルにカレーの作り方を聞いてみました。from langchain_core.prompts import ChatPromptTemplate from langchain_ollama import ChatOllama from pydantic import BaseModel, Field class Recipe(BaseModel): ingredients: list[str] = Field(description="ingredients of the dish") steps: list[str] = Field(description="steps to make the dish") prompt = ChatPromptTemplate( [ ("system", "ユーザーが入力した料理のレシピを考えてください。"), ("human", "{dish}"), ] ) model = ChatOllama(model="qwen2.5:latest", temperature=0) chain = prompt | model.with_structured_output(Recipe) recipe = chain.invoke({"dish": "カレー"}) print(recipe)
結果
ingredients=['牛肉', '玉ねぎ', 'にんじん', 'じゃがいも', 'カレールー'] steps=['牛肉を一口大に切ります。', '熱したフライ パンで玉ねぎを炒めます。', 'にんじんとじゃがいもも加えて炒めます。', 'カレールーを加え、すべての材料をよく混ぜ合わせます。', '弱火で15分ほど煮込みます。']
使用したライブラリのバージョン
langchain-core==0.3.29 langchain-ollama==0.2.2 ollama==0.4.5 pydantic==2.10.4