typescriptadvanced

AI Prompt Chaining Pattern

Chain multiple LLM calls sequentially where each step's output feeds into the next for complex tasks.

typescript
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.