Skip to content

🔀 工作流模式(Workflow Patterns)

当需要比自由 Agent 更可靠、可预测的结果时,使用结构化工作流模式。

模式选择指南

因素考量
灵活性 vs 控制LLM 需要多少自由度?需要多严格地约束其行为?
错误容忍度您的用例中错误的后果是什么?
成本考量更复杂的系统通常意味着更多的 LLM 调用和更高的成本
可维护性更简单的架构更容易调试和修改

1. 顺序处理(Sequential Chains)

步骤按预定顺序执行,每步的输出成为下一步的输入。

typescript
import { generateText, generateObject } from 'ai';
import { z } from 'zod';

async function generateMarketingCopy(input: string) {
  const model = "anthropic/claude-sonnet-4.5";

  // 第一步:生成营销文案
  const { text: copy } = await generateText({
    model,
    prompt: `Write persuasive marketing copy for: ${input}`,
  });

  // 第二步:质量检查
  const { object: qualityMetrics } = await generateObject({
    model,
    schema: z.object({
      hasCallToAction: z.boolean(),
      emotionalAppeal: z.number().min(1).max(10),
      clarity: z.number().min(1).max(10),
    }),
    prompt: `Evaluate this marketing copy: ${copy}`,
  });

  // 第三步:如果质量不达标,重新生成
  if (!qualityMetrics.hasCallToAction || qualityMetrics.emotionalAppeal < 7) {
    const { text: improvedCopy } = await generateText({
      model,
      prompt: `Rewrite with stronger call to action: ${copy}`,
    });
    return { copy: improvedCopy, qualityMetrics };
  }

  return { copy, qualityMetrics };
}

2. 路由(Routing)

根据上下文和中间结果决定工作流路径。

typescript
import { generateObject, generateText } from 'ai';
import { z } from 'zod';

async function handleCustomerQuery(query: string) {
  // 分类查询类型
  const { object: classification } = await generateObject({
    model: "anthropic/claude-sonnet-4.5",
    schema: z.object({
      type: z.enum(['general', 'refund', 'technical']),
      complexity: z.enum(['simple', 'complex']),
    }),
    prompt: `Classify this query: ${query}`,
  });

  // 根据分类路由
  const { text: response } = await generateText({
    model: classification.complexity === 'simple' 
      ? 'openai/gpt-4o-mini' 
      : 'openai/o4-mini',
    system: {
      general: 'You are a customer service agent.',
      refund: 'You specialize in refund requests.',
      technical: 'You are a technical support specialist.',
    }[classification.type],
    prompt: query,
  });

  return { response, classification };
}

3. 并行处理(Parallel Processing)

独立任务同时执行,提高效率。

typescript
import { generateText, generateObject } from 'ai';
import { z } from 'zod';

async function parallelCodeReview(code: string) {
  const model = "anthropic/claude-sonnet-4.5";

  // 并行运行多个审查
  const [securityReview, performanceReview, maintainabilityReview] =
    await Promise.all([
      generateObject({
        model,
        system: 'Focus on security vulnerabilities.',
        schema: z.object({
          vulnerabilities: z.array(z.string()),
          riskLevel: z.enum(['low', 'medium', 'high']),
        }),
        prompt: `Review: ${code}`,
      }),
      generateObject({
        model,
        system: 'Focus on performance bottlenecks.',
        schema: z.object({
          issues: z.array(z.string()),
          impact: z.enum(['low', 'medium', 'high']),
        }),
        prompt: `Review: ${code}`,
      }),
      generateObject({
        model,
        system: 'Focus on code quality.',
        schema: z.object({
          concerns: z.array(z.string()),
          qualityScore: z.number().min(1).max(10),
        }),
        prompt: `Review: ${code}`,
      }),
    ]);

  // 汇总结果
  const { text: summary } = await generateText({
    model,
    system: 'Summarize multiple code reviews.',
    prompt: `Synthesize: ${JSON.stringify({
      security: securityReview.object,
      performance: performanceReview.object,
      maintainability: maintainabilityReview.object,
    })}`,
  });

  return { reviews: [securityReview, performanceReview, maintainabilityReview], summary };
}

4. 编排者-工作者(Orchestrator-Worker)

主模型(编排者)协调专业工作者的执行。

typescript
import { generateObject } from 'ai';
import { z } from 'zod';

async function implementFeature(featureRequest: string) {
  // 编排者:规划实现
  const { object: plan } = await generateObject({
    model: "anthropic/claude-sonnet-4.5",
    schema: z.object({
      files: z.array(z.object({
        purpose: z.string(),
        filePath: z.string(),
        changeType: z.enum(['create', 'modify', 'delete']),
      })),
    }),
    system: 'You are a software architect.',
    prompt: `Plan implementation for: ${featureRequest}`,
  });

  // 工作者:执行变更
  const changes = await Promise.all(
    plan.files.map(async file => {
      const workerPrompt = {
        create: 'You implement new files.',
        modify: 'You modify existing code.',
        delete: 'You safely remove code.',
      }[file.changeType];

      const { object: change } = await generateObject({
        model: "anthropic/claude-sonnet-4.5",
        schema: z.object({
          explanation: z.string(),
          code: z.string(),
        }),
        system: workerPrompt,
        prompt: `Implement for ${file.filePath}: ${file.purpose}`,
      });

      return { file, implementation: change };
    }),
  );

  return { plan, changes };
}

5. 评估-优化器(Evaluator-Optimizer)

专门的评估步骤评估中间结果,根据评估进行改进。

typescript
import { generateText, generateObject } from 'ai';
import { z } from 'zod';

async function translateWithFeedback(text: string, targetLanguage: string) {
  let currentTranslation = '';
  const MAX_ITERATIONS = 3;

  // 初始翻译
  const { text: translation } = await generateText({
    model: "anthropic/claude-sonnet-4.5",
    system: 'You are an expert literary translator.',
    prompt: `Translate to ${targetLanguage}: ${text}`,
  });

  currentTranslation = translation;

  // 评估-优化循环
  for (let i = 0; i < MAX_ITERATIONS; i++) {
    const { object: evaluation } = await generateObject({
      model: "anthropic/claude-sonnet-4.5",
      schema: z.object({
        qualityScore: z.number().min(1).max(10),
        preservesTone: z.boolean(),
        specificIssues: z.array(z.string()),
      }),
      prompt: `Evaluate: Original: ${text}, Translation: ${currentTranslation}`,
    });

    if (evaluation.qualityScore >= 8 && evaluation.preservesTone) {
      break;
    }

    // 根据反馈改进
    const { text: improved } = await generateText({
      model: "anthropic/claude-sonnet-4.5",
      prompt: `Improve based on: ${evaluation.specificIssues.join('\n')}\n\nOriginal: ${text}\nCurrent: ${currentTranslation}`,
    });

    currentTranslation = improved;
  }

  return { finalTranslation: currentTranslation };
}

前端面试知识库