Open in Colab

Prompts#

promptモデルへの入力です、promptを動的に作成・操作できるようにクラスや関数が利用できます。

  • LLM Prompt Templates

  • Chat Prompt Templates

  • Example Selectors

  • Output Parsers

Prompt Templates#

Prompt Templatesとは、promptを生成するための再現可能な方法を指します。テキスト文字列(テンプレート)が含まれており、エンドユーザーからパラメータのセットを受け取り、promptを生成できます。

次のコードはPrompt Templatesの例です。

from langchain import PromptTemplate


template = """
あなたは句会のメンバーです
{season} の俳句を読んでください
"""

prompt = PromptTemplate(
    input_variables=["season"],
    template=template,
)
prompt.format(season="売上高")
'\nあなたは句会のメンバーです\n売上高 の俳句を読んでください\n'

入力変数がないpromptの例です。

# An example prompt with no input variables
no_input_prompt = PromptTemplate(input_variables=[], template="夏の俳句を読んでください")
no_input_prompt.format()
'夏の俳句を読んでください'

入力変数が1つの場合の例です。

# An example prompt with one input variable
one_input_prompt = PromptTemplate(input_variables=["season"], template="{season} の俳句を読んでください")
one_input_prompt.format(season="夏")
'夏 の俳句を読んでください'

複数の入力変数を持つプロンプトの例です。

# An example prompt with multiple input variables
multiple_input_prompt = PromptTemplate(
    input_variables=["season", "theme"], 
    template="{theme} を題材にして {season} の俳句を読んでください"
)
multiple_input_prompt.format(season="夏", theme="スイカ")
'スイカ を題材にして 夏 の俳句を読んでください'

input_variables を手動で指定したくない場合は、 from_template メソッドでPrompt Templateを作成できます。

template = "{theme} を題材にして {season} の俳句を読んでください"

prompt_template = PromptTemplate.from_template(template)
prompt_template.input_variables
['season', 'theme']
prompt_template.format(season="夏", theme="スイカ")
'スイカ を題材にして 夏 の俳句を読んでください'

Chat Prompt Template#

Chat Models はチャットメッセージのリストを入力として受け取ります。このリストは一般にpromptと呼ばれます。これらのチャットメッセージはroleと関連付けられています。

from langchain.prompts import (
    ChatPromptTemplate,
    PromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain.schema import (
    AIMessage,
    HumanMessage,
    SystemMessage
)

roleに関連するメッセージテンプレートを作成するには、 MessagePromptTemplate を使います。

template="あなたは {input_language}{output_language} の通訳者です"
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

print(system_message_prompt)
print(human_message_prompt)
prompt=PromptTemplate(input_variables=['input_language', 'output_language'], output_parser=None, partial_variables={}, template='あなたは {input_language} と {output_language} の通訳者です', template_format='f-string', validate_template=True) additional_kwargs={}
prompt=PromptTemplate(input_variables=['text'], output_parser=None, partial_variables={}, template='{text}', template_format='f-string', validate_template=True) additional_kwargs={}

PromptTemplate からも作成できます。

prompt=PromptTemplate(
    template="あなたは {input_language}{output_language} の通訳者です",
    input_variables=["input_language", "output_language"],
)
system_message_prompt_2 = SystemMessagePromptTemplate(prompt=prompt)

assert system_message_prompt == system_message_prompt_2

MessagePromptTemplate から ChatPromptTemplate を構築します。

chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

# get a chat completion from the formatted messages
chat_prompt.format_prompt(input_language="英語", output_language="日本語", text="I have a pen.").to_messages()
[SystemMessage(content='あなたは 英語 と 日本語 の通訳者です', additional_kwargs={}),
 HumanMessage(content='I have a pen.', additional_kwargs={}, example=False)]

Format output#

format メソッド、 to_string メソッドは入力promptからフォーマットされた文字列を返します。

chat_prompt.format(input_language="英語", output_language="日本語", text="I have a pen.")
'System: あなたは English と French の通訳者です\nHuman: I have a pen.'
chat_prompt.format_prompt(input_language="英語", output_language="日本語", text="I have a pen.").to_string()
'System: あなたは 英語 と 日本語 の通訳者です\nHuman: I have a pen.'

MessagePromptTemplate#

ChatMessagePromptTemplate ではroleを指定できます。

from langchain.prompts import ChatMessagePromptTemplate

prompt = "私は {subject} のプレイヤーです"

chat_message_prompt = ChatMessagePromptTemplate.from_template(role="player", template=prompt)
chat_message_prompt.format(subject="チェス")
ChatMessage(content='私は チェス のプレイヤーです', additional_kwargs={}, role='player')

MessagesPlaceholder はフォーマット中に表示されるメッセージを完全にコントロールできます。これはメッセージプロンプトテンプレートにどのようなroleを使用すべきか不明な場合や、フォーマット中にメッセージのリストを挿入したい場合に便利です。

from langchain.prompts import MessagesPlaceholder

human_prompt = "Summarize our conversation so far in {word_count} words."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)

chat_prompt = ChatPromptTemplate.from_messages([MessagesPlaceholder(variable_name="conversation"), human_message_template])
human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(content="""\
我々は一人の英雄を失った。しかし、これは敗北を意味するのか?否!始まりなのだ!
地球連邦に比べ、我がジオンの国力は30分の1以下である。
にもかかわらず今日まで戦い抜いてこられたのは何故か?
諸君!我がジオン公国の戦争目的が正義だからだ。これは諸君らが一番知っている。
我々は地球を追われ、宇宙移民者にさせられた。
そして、一握りのエリートらが宇宙にまで膨れ上がった地球連邦を支配して50余年、
宇宙に住む我々が自由を要求して何度踏みにじられたか。
ジオン公国の掲げる人類一人一人の自由のための戦いを神が見捨てるはずはない。
私の弟!諸君らが愛してくれたガルマ・ザビは死んだ。
何故だ!?\
""")

chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages()
[HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}, example=False),
 AIMessage(content='我々は一人の英雄を失った。しかし、これは敗北を意味するのか?否!始まりなのだ!\n地球連邦に比べ、我がジオンの国力は30分の1以下である。\nにもかかわらず今日まで戦い抜いてこられたのは何故か?\n諸君!我がジオン公国の戦争目的が正義だからだ。これは諸君らが一番知っている。\n我々は地球を追われ、宇宙移民者にさせられた。\nそして、一握りのエリートらが宇宙にまで膨れ上がった地球連邦を支配して50余年、\n宇宙に住む我々が自由を要求して何度踏みにじられたか。\nジオン公国の掲げる人類一人一人の自由のための戦いを神が見捨てるはずはない。\n私の弟!諸君らが愛してくれたガルマ・ザビは死んだ。\n何故だ!?', additional_kwargs={}, example=False),
 HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={}, example=False)]