Few-shot prompting

การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain

Jonathan Bennion

AI Engineer & LangChain Contributor

ข้อจำกัดของ prompt template มาตรฐาน

 

  • PromptTemplate + ChatPromptTemplate
  • ✅ รองรับตัวอย่างจำนวนน้อย
  • ❌ ไม่รองรับตัวอย่างจำนวนมาก
  • FewShotPromptTemplate

 

examples = [
    {
        "question": "..."
        "answer": "..."
    },
    ...
]
การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain

การสร้างชุดตัวอย่าง

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")
การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain

การจัดรูปแบบตัวอย่าง

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
การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain

FewShotPromptTemplate

 

prompt_template = FewShotPromptTemplate(

examples=examples,
example_prompt=example_prompt,
suffix="Question: {input}",
input_variables=["input"]
)

 

 

  • examples: รายการของ dict
  • example_prompt: template ที่จัดรูปแบบแล้ว
  • suffix: ข้อความต่อท้าย input
  • input_variables
การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain

การเรียกใช้ few-shot prompt template

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?
การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain

การเชื่อมต่อกับ 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.
การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain

มาฝึกกันเถอะ!

การพัฒนาแอปพลิเคชัน LLM ด้วย LangChain

Preparing Video For Download...