本記事ではGoogle Colaboratory上でLangChainのLLMChain使って、LLMで簡単な会話をしていきます。
Google Colaboratoryの使い方がわからない方は、まずこちらの記事をご覧ください。
Modelクラスと組み合わせるってどういうこと?
LangChainには、PythonのModelクラスのFieldに合わせて会話の返答を要求する仕組みがあります。
まずはModelクラスを作っていきましょう。
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")
feeling: str = Field(description="your feelings when you eat the dish")
上記はRecipeクラスです。料理の作り方を管理するModelクラスですね。
Recipeクラスには3つのFieldが用意されています。特に上記のような名前でないといけないということはありません。でも、LLMが理解しやすい名前の方が良いかと思います。
ここで重要なのが、各Fieldの description
です。
それがなんのデータなのかを説明することでより良い返答を期待することができます。
今回は料理の作り方のクラスなので、ingredients(食材)、steps(手順)、そして最後にfeeling(食べたときの感想)というFieldを作りました。
では、このクラスを使ってLLMで会話をしていきましょう!
# !pip install langchain openai
# !pip install pydantic
from langchain.chat_models import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.output_parsers import PydanticOutputParser
from langchain import LLMChain
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")
feeling: str = Field(description="your feelings when you eat the dish")
output_parser = PydanticOutputParser(pydantic_object=Recipe)
template = """料理のレシピを教えてください
{format_instructions}
料理名: {dish}
"""
prompt = PromptTemplate(
template=template,
input_variables=["dish"],
partial_variables={"format_instructions": output_parser.get_format_instructions()}
)
chat = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, api_key="ここにAPI Keyを貼る")
chain = LLMChain(prompt=prompt, llm=chat, output_parser=output_parser)
recipe = chain.run(dish="魚介パスタ")
print(recipe)
ポイントは、アウトプットにRecipeクラスの形式を適用しますというところです。これでRecipeクラスに沿った回答を得ることができます。
output_parser = PydanticOutputParser(pydantic_object=Recipe)
dish
には 魚介パスタ
を挿入します。では実行してみましょう。
実行結果
ingredients=['パスタ', 'エビ', 'イカ', 'ムール貝', 'トマト', 'ニンニク', 'オリーブオイル', '白ワイン', '塩', 'こしょう', 'パセリ']
steps=['パスタを茹でる。', 'フライパンにオリーブオイルを熱し、ニンニクを炒める。', 'エビ、イカ、ムール貝を加えて炒める。', '白ワインを加えてアルコールを飛ばす。', 'トマトを加えて煮込む。', '茹でたパスタを加えて絡める。', '塩とこしょうで味を調える。', 'パセリを散らして完成。']
feeling='魚介の旨味とトマトの酸味が絶妙にマッチして、とても美味しい!'
いや、すごいですね。こんなふうに、Recipeクラスに合わせて、食材・調理手順・食べた時の感想を出してくれました。
こんな感じで、Modelクラスを工夫することで簡単に返答形式を調整することができます。
色々試してみてください。