🦜️🔗LangChain : モジュール : モデル I/O – プロンプト : プロンプトテンプレート : カスタム・プロンプトテンプレート / テンプレート出力の整形 / テンプレート形式 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 08/22/2023
* 本ページは、LangChain の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
- Modules : Model I/O – Prompts : Prompt templates : Custom prompt template
- Modules : Model I/O – Prompts : Prompt templates : Format template output
- Modules : Model I/O – Prompts : Prompt templates : Template Formats
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- 人工知能研究開発支援
- 人工知能研修サービス(経営者層向けオンサイト研修)
- テクニカルコンサルティングサービス
- 実証実験(プロトタイプ構築)
- アプリケーションへの実装
- 人工知能研修サービス
- PoC(概念実証)を失敗させないための支援
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
- 株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
- sales-info@classcat.com ; Web: www.classcat.com ; ClassCatJP
🦜️🔗 LangChain : モジュール : モデル I/O – プロンプト : プロンプトテンプレート : カスタム・プロンプトテンプレート
関数の名前が与えられたときその英語の説明を生成することを LLM に望むと仮定します。このタスクを達成するため、カスタム・プロンプトテンプレートを作成します、これは入力として関数名を受け取り、関数のソースコードを提供するようにプロンプトテンプレートを整形します。
カスタム・プロンプトテンプレート何故必要なのでしょう?
LangChain はデフォルトのプロンプトテンプレートのセットを提供します、これは様々なタスク用のプロンプトを生成するために利用できます。けれども、デフォルトのプロンプトテンプレートが貴方のニーズに適合しないケースがあるかもしれません。例えば、貴方の言語モデルのために特定の動的なインストラクションを含むプロンプトテンプレートを作成したいかもしれません。そのような場合、カスタム・プロンプトテンプレートを作成することができます。
ここ でデフォルトのプロンプトテンプレートの現在のセットを見てください。
カスタム・プロンプトテンプレートの作成
基本的にはっきりと異なる 2 つのプロンプト・テンプレートが利用可能です – 文字列プロンプトテンプレートとチャットプロンプトテンプレートです。文字列プロンプトテンプレートが文字列形式の単純なプロンプトを提供する一方で、チャットプロンプトテンプレートはチャット API で使用される、より構造化されたプロンプトを生成します。
このガイドでは、文字列プロンプトテンプレートを使用してカスタムプロンプトを作成します。
カスタム文字列プロンプトテンプレートを作成するには、2 つの要件があります :
- それは input_variables 属性を持ちます、これはどのような入力変数をプロンプトテンプレートが想定するかを公開します。
- それは format メソッドを公開します、これは想定される input_variables に対応するキーワード引数を受け取り、整形されたプロンプトを返します。
入力として関数名を受け取り、関数のソースコードを提供するようなプロンプトを整形するカスタム・プロンプトテンプレートを作成します。これを実現するため、最初にその名前が与えられた関数のソースコードを返す関数を作成しましょう。
import inspect
def get_source_code(function_name):
# Get the source code of the function
return inspect.getsource(function_name)
次に、入力として関数名を受け取り、関数のソースコードを提供するようなプロンプトテンプレートを整形するカスタム・プロンプトテンプレートを作成します。
from langchain.prompts import StringPromptTemplate
from pydantic import BaseModel, validator
PROMPT = """\
Given the function name and source code, generate an English language explanation of the function.
Function Name: {function_name}
Source Code:
{source_code}
Explanation:
"""
class FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel):
"""A custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function."""
@validator("input_variables")
def validate_input_variables(cls, v):
"""Validate that the input variables are correct."""
if len(v) != 1 or "function_name" not in v:
raise ValueError("function_name must be the only input_variable.")
return v
def format(self, **kwargs) -> str:
# Get the source code of the function
source_code = get_source_code(kwargs["function_name"])
# Generate the prompt to be sent to the language model
prompt = PROMPT.format(
function_name=kwargs["function_name"].__name__, source_code=source_code
)
return prompt
def _prompt_type(self):
return "function-explainer"
API リファレンス
- StringPromptTemplate from langchain.prompts
カスタム・プロンプトテンプレートの使用
カスタム・プロンプトテンプレートを作成したので、それを使用してタスクのためにプロンプトを生成することができます。
fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])
# Generate a prompt for the function "get_source_code"
prompt = fn_explainer.format(function_name=get_source_code)
print(prompt)
Given the function name and source code, generate an English language explanation of the function. Function Name: get_source_code Source Code: def get_source_code(function_name): # Get the source code of the function return inspect.getsource(function_name) Explanation:
🦜️🔗 LangChain : モジュール : モデル I/O – プロンプト : プロンプトテンプレート : テンプレート出力の整形
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={})]
🦜️🔗 LangChain : モジュール : モデル I/O – プロンプト : プロンプトテンプレート : テンプレート形式
PromptTemplate はデフォルトではそのテンプレート形式として Python f-文字列を使用します。けれども、template_format 引数で指定された、jinja2 のような他のフォーマットも使用できます。
jinja2 テンプレートを使用するには :
from langchain.prompts import PromptTemplate
jinja2_template = "Tell me a {{ adjective }} joke about {{ content }}"
prompt = PromptTemplate.from_template(jinja2_template, template_format="jinja2")
prompt.format(adjective="funny", content="chickens")
# Output: Tell me a funny joke about chickens.
API リファレンス:
- PromptTemplate from langchain.prompts
Python f-文字列テンプレートを使用するには :
from langchain.prompts import PromptTemplate
fstring_template = """Tell me a {adjective} joke about {content}"""
prompt = PromptTemplate.from_template(fstring_template)
prompt.format(adjective="funny", content="chickens")
# Output: Tell me a funny joke about chickens.
API リファレンス:
- PromptTemplate from langchain.prompts
現在、jinja2 と f-string だけがサポートされています。For other formats, kindly raise an issue on the Github page.
以上