FreeStack

Prompt Chain

Multi-step prompt chaining framework with validation, retry logic, and intermediate result caching. Define complex AI workflows as composable, typed chains.

TypeScriptAI WorkflowsBuilt with Claude
1.2k
Stars
5.4k
Installs
3
Deps
2
Comments

Install / Copy

npx create-freestack-module prompt-chain

Code Preview

index.tsx
import { z } from "zod";

interface ChainStep<TInput, TOutput> {
  name: string;
  prompt: (input: TInput) => string;
  schema: z.ZodType<TOutput>;
  retries?: number;
}

export class PromptChain<T> {
  private steps: ChainStep<any, any>[] = [];

  add<TOutput>(step: ChainStep<T, TOutput>): PromptChain<TOutput> {
    this.steps.push(step);
    return this as any;
  }

  async run(input: T): Promise<any> {
    let result = input;
    for (const step of this.steps) {
      const prompt = step.prompt(result);
      for (let attempt = 0; attempt <= (step.retries ?? 2); attempt++) {
        const raw = await this.llm.complete(prompt);
        const parsed = step.schema.safeParse(JSON.parse(raw));
        if (parsed.success) { result = parsed.data; break; }
      }
    }
    return result;
  }
}
PR
prompteng6 days ago

The Zod validation between steps catches so many issues early. Great pattern.

TY
typescripter2 weeks ago

Type inference through the chain is excellent. Feels like a well-designed library.