6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[翻訳] LangChainのチャットプロンプトテンプレート

Posted at

Chat Prompt Templates — 🦜🔗 LangChain 0.0.190の翻訳です。

本書は抄訳であり内容の正確性を保証するものではありません。正確な内容に関しては原文を参照ください。

Chat Modelschat messages as入力のリストを受け取ります。このリストは通常promptと呼ばれます。これらのチャットメッセージは、すべてのメッセージがroleと関連づけられる点で(LLMモデルの入力になる)生の文字列と異なります。

例えば、OpenAIのChat Completion APIでは、チャットメッセージは、AI、人間、システムロールと紐づけられます。このモデルはシステムのチャットメッセージからの指示により密接に従うとされています。

LangChainはプロンプトの構築、取り扱いをより容易にするいくつかのプロンプトテンプレートを提供します。背後のチャットモデルを最大限に活用するために、チャットモデルに問い合わせを行う際にPromptTemplateではなく、これらのチャット関連プロンプトテンプレートを使うことをお勧めします。

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

ロールと関連づけられたメッセージテンプレートを作成するには、MessagePromptTemplateを使います。便利にするために、テンプレートに公開されているfrom_templateメソッドがあります。このテンプレートを使いたいのであれば、これは以下のようになるでしょう:

template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

MessagePromptTemplateをより直接的に構築したいのであれば、以下のようにPromptTemplateを作成して引き渡すことができます:

prompt=PromptTemplate(
    template="You are a helpful assistant that translates {input_language} to {output_language}.",
    input_variables=["input_language", "output_language"],
)
system_message_prompt_2 = SystemMessagePromptTemplate(prompt=prompt)

assert system_message_prompt == system_message_prompt_2

この後で、一つ以上のMessagePromptTemplatesからChatPromptTemplateを構築することができます。ChatPromptTemplateformat_promptを使うことができます。これは、llmモデルやchatモデルへの入力としてフォーマットされた値を使いたいのかどうかに応じて、文字列やMessageオブジェクトに変換することができるPromptValueを返却します。

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="English", output_language="French", text="I love programming.").to_messages()
[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
 HumanMessage(content='I love programming.', additional_kwargs={})]

アウトプットのフォーマット

formatメソッドのアウトプットは文字列、メッセージのリスト、ChatPromptValueとして利用できます。

文字列として出力:

output = chat_prompt.format(input_language="English", output_language="French", text="I love programming.")
output
'System: You are a helpful assistant that translates English to French.\nHuman: I love programming.'
# or alternatively 
output_2 = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_string()

assert output == output_2

ChatPromptValueとして出力:

chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.")
ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})])

Messageオブジェクトのリスト:

chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages()
[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
 HumanMessage(content='I love programming.', additional_kwargs={})]

色々なタイプのMessagePromptTemplate

LangChainは色々なタイプのMessagePromptTemplateを提供します。最もよく使われるのは、AIメッセージ、システムメッセージ、人間のメッセージを作成するAIMessagePromptTemplateSystemMessagePromptTemplateHumanMessagePromptTemplateです。

しかし、chatモデルが任意のロールのチャットメッセージをサポートしている場合、ロール名を指定できるChatMessagePromptTemplateを使うことができます。

from langchain.prompts import ChatMessagePromptTemplate

prompt = "May the {subject} be with you"

chat_message_prompt = ChatMessagePromptTemplate.from_template(role="Jedi", template=prompt)
chat_message_prompt.format(subject="force")
ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')

また、LangChainはフォーマットにおいてどのメッセージがレンダリングされるのかに関するフルコントロールを提供するMessagesPlaceholderも提供しています。これは、お使いのメッセージプロンプトテンプレートでどのロールを使うべきかが不明確である場合やフォーマットでメッセージのリストをインサートしたい場合には有用です。

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="""\
1. Choose a programming language: Decide on a programming language that you want to learn. 

2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.

3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
""")

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={}),
 AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn. \n\n2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.\n\n3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}),
 HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})]
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?