AgentSkillsCN

dspy.ts

DSPy TypeScript 框架,内置 ChainOfThought、Predict、MIPROv2 优化器以及多智能体编排功能。适用于构建程序化 LLM 管道、组合提示模块、利用 MIPROv2 优化提示链、实现结构化 LLM 推理,或将 Python 版 DSPy 程序移植至 TypeScript。

SKILL.md
--- frontmatter
name: "dspy.ts"
description: "DSPy TypeScript framework with ChainOfThought, Predict, MIPROv2 optimizer, and multi-agent orchestration. Use when building programmatic LLM pipelines, composing prompt modules, optimizing prompt chains with MIPROv2, implementing structured LLM reasoning, or porting Python DSPy programs to TypeScript."

dspy.ts

Full-featured TypeScript port of the DSPy framework providing ChainOfThought, Predict, ReAct, and other composable modules with MIPROv2 optimizer, multi-agent orchestration, and self-learning capabilities.

Quick Reference

TaskCode
Installnpx dspy.ts@latest
Importimport { ChainOfThought, Predict } from 'dspy.ts';
Predictconst p = new Predict('question -> answer');
CoTconst cot = new ChainOfThought('q -> a');
Forwardconst r = await cot.forward({ q: 'What is ML?' });
Optimizeconst opt = await compile(cot, { optimizer: new MIPROv2() });

Installation

Install: npx dspy.ts@latest See Installation Guide for the full ecosystem.

Key API

Predict

The simplest module: takes a signature and generates a prediction.

typescript
import { Predict } from 'dspy.ts';

const predict = new Predict('question -> answer');
const result = await predict.forward({ question: 'What is machine learning?' });
console.log(result.answer);

Constructor Options:

ParameterTypeDefaultDescription
signaturestringrequiredInput/output signature (e.g., 'q -> a')
modelstringdefault LMModel to use
temperaturenumber0.7Sampling temperature
maxTokensnumber1024Maximum output tokens
numCandidatesnumber1Candidates to generate

ChainOfThought

Predict with intermediate reasoning steps.

typescript
import { ChainOfThought } from 'dspy.ts';

const cot = new ChainOfThought('question -> answer');
const result = await cot.forward({ question: 'Solve: 2x + 5 = 15' });
console.log(result.reasoning);  // Step-by-step reasoning
console.log(result.answer);     // Final answer

ReAct

Reasoning and Acting with tool use.

typescript
import { ReAct } from 'dspy.ts';

const react = new ReAct('question -> answer', {
  tools: [searchTool, calculatorTool],
  maxSteps: 5,
});

const result = await react.forward({ question: 'What is the population of Tokyo in 2024?' });

Constructor Options:

OptionTypeDefaultDescription
toolsTool[][]Available tools
maxStepsnumber5Maximum reasoning steps
stopConditionstring'answer'When to stop reasoning

MIPROv2

Optimizer for automatic prompt optimization.

typescript
import { ChainOfThought, compile, MIPROv2 } from 'dspy.ts';

const cot = new ChainOfThought('question -> answer');

const optimized = await compile(cot, {
  optimizer: new MIPROv2({
    numTrials: 50,
    metric: (pred, gold) => pred.answer === gold.answer ? 1.0 : 0.0,
  }),
  trainset: trainingExamples,
});

MIPROv2 Options:

OptionTypeDefaultDescription
numTrialsnumber50Optimization trials
metricfunctionrequiredEvaluation metric function
maxBootstrappednumber4Max bootstrapped demos
maxLabeledDemosnumber16Max labeled demonstrations
miniBatchSizenumber25Evaluation mini-batch
seednumber42Random seed

configure

Set global LLM configuration.

typescript
import { configure } from 'dspy.ts';

configure({
  lm: 'anthropic/claude-sonnet-4-20250514',
  apiKey: process.env.ANTHROPIC_API_KEY,
  temperature: 0.0,
});

Config Options:

OptionTypeDefaultDescription
lmstringrequiredLanguage model identifier
apiKeystringfrom envAPI key
temperaturenumber0.7Default temperature
maxTokensnumber1024Default max tokens
cacheEnabledbooleantrueEnable prompt caching

Common Patterns

Multi-Step Pipeline

typescript
import { ChainOfThought, Predict, Pipeline } from 'dspy.ts';

const summarize = new ChainOfThought('document -> summary');
const classify = new Predict('summary -> category');
const extract = new Predict('summary, category -> keyPoints: list');

const pipeline = new Pipeline([summarize, classify, extract]);
const result = await pipeline.forward({ document: longText });

Optimized QA System

typescript
import { ChainOfThought, compile, MIPROv2 } from 'dspy.ts';

const qa = new ChainOfThought('context, question -> answer');

const optimized = await compile(qa, {
  optimizer: new MIPROv2({
    numTrials: 100,
    metric: (pred, gold) => {
      return pred.answer.includes(gold.answer) ? 1.0 : 0.0;
    },
  }),
  trainset: qaExamples,
  valset: valExamples,
});

// optimized now uses learned demonstrations and instructions
const result = await optimized.forward({ context, question });

Multi-Agent with DSPy Modules

typescript
import { ChainOfThought, Predict } from 'dspy.ts';

const researcher = new ChainOfThought('topic -> findings');
const analyst = new ChainOfThought('findings -> analysis');
const writer = new Predict('analysis, topic -> report');

const findings = await researcher.forward({ topic: 'quantum computing' });
const analysis = await analyst.forward(findings);
const report = await writer.forward({ ...analysis, topic: 'quantum computing' });

RAN DDD Context

Bounded Context: RANO Optimization

References