Few-shot prompting is a powerful technique that teaches a language model a specific pattern by providing a handful of examples at runtime. This approach avoids hardcoding lengthy instructions and lets the LLM infer the desired transformation from context.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Table of Contents
- Prerequisites
- Defining Examples
- Creating an Example Prompt
- Building the Few-Shot Prompt
- Assembling the Chat Prompt Template
- Inspecting the Prompt Structure
- Formatting for Invocation
- Invoking the Model
- References
1. Prerequisites
Install the required packages and set your OpenAI API key:Never commit your API keys to version control. Use environment variables or a secret manager instead.
2. Defining Examples
Prepare a small list of example pairs. Each item maps aninput (country name) to its output (the reversed string):
3. Creating an Example Prompt
UseChatPromptTemplate to describe how each example should appear in the conversation:
4. Building the Few-Shot Prompt
Combine your individual example template with the list of examples viaFewShotChatMessagePromptTemplate:
5. Assembling the Chat Prompt Template
Wrap the system instruction, the few-shot examples, and the final human query into a singleChatPromptTemplate:
6. Inspecting the Prompt Structure
Print out the internal representation to verify the sequence of messages:7. Formatting for Invocation
Populate the template with a new input—e.g.,"Brazil"—to generate the messages you’ll send to the LLM:
8. Invoking the Model
Pass the formatted messages to theChatOpenAI model and print the response:
You can adapt this structure to teach any pattern by changing the
system role or example pairs.