Few-shot prompting

Tworzenie aplikacji LLM z LangChain

Jonathan Bennion

AI Engineer & LangChain Contributor

Ograniczenia standardowych szablonów promptów

 

  • PromptTemplate + ChatPromptTemplate
  • ✅ Sprawdza się przy małej liczbie przykładów
  • ❌ Nie skaluje się dla wielu przykładów
  • FewShotPromptTemplate

 

examples = [
    {
        "question": "..."
        "answer": "..."
    },
    ...
]
Tworzenie aplikacji LLM z LangChain

Tworzenie zestawu przykładów

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")
Tworzenie aplikacji LLM z LangChain

Formatowanie przykładów

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
Tworzenie aplikacji LLM z LangChain

FewShotPromptTemplate

 

prompt_template = FewShotPromptTemplate(

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

 

 

  • examples: lista słowników
  • example_prompt: sformatowany szablon
  • suffix: sufiks dodawany do wejścia
  • input_variables
Tworzenie aplikacji LLM z LangChain

Wywoływanie szablonu few-shot prompt

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?
Tworzenie aplikacji LLM z LangChain

Integracja z łańcuchem

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.
Tworzenie aplikacji LLM z LangChain

Czas na ćwiczenia!

Tworzenie aplikacji LLM z LangChain

Preparing Video For Download...