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.
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
#openai#streaming
typescriptadvanced
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
#rag#embeddings
typescriptbeginner
Claude Messages API (Anthropic SDK)
Send messages to Claude using the official Anthropic SDK with system prompt and user turn.
#anthropic#claude
pythonbeginner
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
#langchain#openai