少樣本提示

使用 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 應用

FewShotPromptTemplate

 

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 應用

與 chain 整合

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...