フューショットプロンプティング

LangChainを使ったLLMアプリケーション開発

Jonathan Bennion

AI Engineer & LangChain Contributor

標準プロンプトテンプレートの制限

  • PromptTemplate + ChatPromptTemplate
  • ✅ 少数のサンプルの扱い
  • ❌ 多くの例には対応しきれない
  • FewShotPromptTemplate
examples = [
    {
        "question": "..."
        "answer": "..."
    },
    ...
]
LangChainを使ったLLMアプリケーション開発

例セットの構築

examples = [
    {
        "question": "Does Henry Campbell have any pets?",
        "answer": "Henry Campbell has a dog called Pluto."
    },
    ...
]
# Convert pandas DataFrame to list of dicts
examples = df.to_dict(orient="records")
LangChainを使ったLLMアプリケーション開発

例のフォーマット

from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

example_prompt = PromptTemplate.from_template("Question: {question}\n{answer}")
prompt = example_prompt.invoke({"question": "What is the capital of Italy?"
                                "answer": "Rome"})
print(prompt.text)
Question: What is the capital of Italy?
Rome
LangChainを使ったLLMアプリケーション開発

FewShotPromptテンプレート

prompt_template = FewShotPromptTemplate(

examples=examples,
example_prompt=example_prompt,
suffix="Question: {input}",
input_variables=["input"]
)
  • examples: dictのリスト
  • example_prompt: フォーマット済みテンプレート
  • suffix: 入力に追加する接尾辞
  • input_variables
LangChainを使ったLLMアプリケーション開発

フューショットプロンプトテンプレートの呼び出し

prompt = prompt_template.invoke({"input": "What is the name of Henry Campbell's dog?"})

print(prompt.text)
Question: Does Henry Campbell have any pets?
Henry Campbell has a dog called Pluto.
...

Question: What is the name of Henry Campbell's dog?
LangChainを使ったLLMアプリケーション開発

チェーンとの統合

llm = ChatOpenAI(model="gpt-4o-mini", api_key="...")

llm_chain = prompt_template | llm response = llm_chain.invoke({"input": "What is the name of Henry Campbell's dog?"})
print(response.content)
The name of Henry Campbell's dog is Pluto.
LangChainを使ったLLMアプリケーション開発

練習しましょう!

LangChainを使ったLLMアプリケーション開発

Preparing Video For Download...