typescriptbeginner
Few-Shot Prompt Template
Build structured few-shot prompts with examples, system instructions, and output format constraints.
typescriptPress ⌘/Ctrl + Shift + C to copy
interface FewShotExample {
input: string;
output: string;
}
export function buildFewShotPrompt({
systemPrompt,
examples,
userInput,
outputFormat,
}: {
systemPrompt: string;
examples: FewShotExample[];
userInput: string;
outputFormat?: string;
}): { role: string; content: string }[] {
const messages: { role: string; content: string }[] = [
{ role: 'system', content: systemPrompt },
];
for (const ex of examples) {
messages.push({ role: 'user', content: ex.input });
messages.push({ role: 'assistant', content: ex.output });
}
const finalInput = outputFormat
? `${userInput}\n\nRespond in this format: ${outputFormat}`
: userInput;
messages.push({ role: 'user', content: finalInput });
return messages;
}
// Usage:
// const messages = buildFewShotPrompt({
// systemPrompt: 'Classify the sentiment',
// examples: [
// { input: 'Great product!', output: 'positive' },
// { input: 'Terrible service', output: 'negative' },
// ],
// userInput: 'Works okay, nothing special',
// });Use Cases
- Consistent AI outputs
- Classification tasks
- Structured data extraction
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
AI Prompt Chaining Pattern
Chain multiple LLM calls sequentially where each step's output feeds into the next for complex tasks.
Best for: Complex multi-step AI workflows
#prompt-engineering#chaining
pythonbeginner
Prompt Template Engineering Patterns
Design reusable, parameterized prompt templates for consistent LLM outputs.
Best for: Consistent LLM outputs
#ai#prompt-engineering
pythonbeginner
Jinja2 Prompt Templates for AI
Manage complex AI prompt templates with Jinja2 for reusable, parameterised prompt generation.
Best for: prompt management
#jinja2#prompts
pythonintermediate
LangChain Few-Shot Prompt Examples
Improve LLM accuracy with dynamic few-shot examples selected by semantic similarity.
Best for: few-shot learning
#langchain#few-shot