typescriptadvanced
AI Prompt Chaining Pattern
Chain multiple LLM calls sequentially where each step's output feeds into the next for complex tasks.
typescriptPress ⌘/Ctrl + Shift + C to copy
import OpenAI from 'openai';
const openai = new OpenAI();
async function llm(prompt: string, system?: string): Promise<string> {
const res = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
...(system ? [{ role: 'system' as const, content: system }] : []),
{ role: 'user', content: prompt },
],
max_tokens: 1000,
});
return res.choices[0].message.content ?? '';
}
type ChainStep = {
name: string;
prompt: (input: string) => string;
system?: string;
};
async function runChain(steps: ChainStep[], input: string): Promise<string> {
let current = input;
for (const step of steps) {
console.log(`Running step: ${step.name}`);
current = await llm(step.prompt(current), step.system);
}
return current;
}
const result = await runChain(
[
{ name: 'extract', prompt: (i) => `Extract key topics from: ${i}` },
{ name: 'research', prompt: (i) => `Provide details on: ${i}` },
{ name: 'summarize', prompt: (i) => `Summarize in 3 bullets: ${i}` },
],
'Latest trends in serverless computing',
);
console.log(result);Use Cases
- Complex multi-step AI workflows
- Research and summarization pipelines
- Content generation with refinement steps
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Few-Shot Prompt Template
Build structured few-shot prompts with examples, system instructions, and output format constraints.
Best for: Consistent AI outputs
#prompts#few-shot
pythonbeginner
Prompt Template Engineering Patterns
Design reusable, parameterized prompt templates for consistent LLM outputs.
Best for: Consistent LLM outputs
#ai#prompt-engineering
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming
typescriptadvanced
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
Best for: document Q&A
#rag#embeddings