跳转至

迭代检索模式

解决多代理工作流中的“上下文问题”:在子代理开始任务之前,无法知道所需的上下文。

激活时机

  • 当需要创建需要不可预测的代码库上下文的子代理时
  • 当构建上下文逐步改进的多代理工作流时
  • 当代理任务中出现“上下文过多”或“上下文缺失”失败时
  • 当为代码探索设计类似 RAG 的检索流水线时
  • 当优化代理编排中的 Token 使用量时

问题

子代理以有限的上下文创建。它无法知道: - 包含相关代码的文件 - 代码库中存在的模式 - 项目使用的术语

标准方法的失败: - 发送所有内容:超出上下文限制 - 不发送任何内容:代理没有重要信息 - 猜测所需内容:经常出错

解决方案:迭代检索

逐步改进上下文的 4 步循环:

┌─────────────────────────────────────────────┐
│                                             │
│   ┌──────────┐      ┌──────────┐            │
│   │ DISPATCH │─────│ EVALUATE │            │
│   └──────────┘      └──────────┘            │
│        ▲                  │                 │
│        │                  ▼                 │
│   ┌──────────┐      ┌──────────┐            │
│   │   LOOP   │─────│  REFINE  │            │
│   └──────────┘      └──────────┘            │
│                                             │
│        Max 3 cycles, then proceed           │
└─────────────────────────────────────────────┘

第 1 步:DISPATCH

用于收集候选文件的初始广泛查询:

// Start with high-level intent
const initialQuery = {
  patterns: ['src/**/*.ts', 'lib/**/*.ts'],
  keywords: ['authentication', 'user', 'session'],
  excludes: ['*.test.ts', '*.spec.ts']
};

// Dispatch to retrieval agent
const candidates = await retrieveFiles(initialQuery);

第 2 步:EVALUATE

评估检索内容的相关性:

function evaluateRelevance(files, task) {
  return files.map(file => ({
    path: file.path,
    relevance: scoreRelevance(file.content, task),
    reason: explainRelevance(file.content, task),
    missingContext: identifyGaps(file.content, task)
  }));
}

评分标准: - 高(0.8-1.0):直接实现目标功能 - 中(0.5-0.7):包含相关模式或类型 - 低(0.2-0.4):间接相关 - 无(0-0.2):不相关,排除

第 3 步:REFINE

基于评估更新检索条件:

function refineQuery(evaluation, previousQuery) {
  return {
    // Add new patterns discovered in high-relevance files
    patterns: [...previousQuery.patterns, ...extractPatterns(evaluation)],

    // Add terminology found in codebase
    keywords: [...previousQuery.keywords, ...extractKeywords(evaluation)],

    // Exclude confirmed irrelevant paths
    excludes: [...previousQuery.excludes, ...evaluation
      .filter(e => e.relevance < 0.2)
      .map(e => e.path)
    ],

    // Target specific gaps
    focusAreas: evaluation
      .flatMap(e => e.missingContext)
      .filter(unique)
  };
}

第 4 步:LOOP

使用改进的条件迭代(最多 3 次):

async function iterativeRetrieve(task, maxCycles = 3) {
  let query = createInitialQuery(task);
  let bestContext = [];

  for (let cycle = 0; cycle < maxCycles; cycle++) {
    const candidates = await retrieveFiles(query);
    const evaluation = evaluateRelevance(candidates, task);

    // Check if we have sufficient context
    const highRelevance = evaluation.filter(e => e.relevance >= 0.7);
    if (highRelevance.length >= 3 && !hasCriticalGaps(evaluation)) {
      return highRelevance;
    }

    // Refine and continue
    query = refineQuery(evaluation, query);
    bestContext = mergeContext(bestContext, highRelevance);
  }

  return bestContext;
}

实用示例

示例 1:修复 Bug 的上下文

Task: "Fix the authentication token expiry bug"

Cycle 1:
  DISPATCH: Search for "token", "auth", "expiry" in src/**
  EVALUATE: Found auth.ts (0.9), tokens.ts (0.8), user.ts (0.3)
  REFINE: Add "refresh", "jwt" keywords; exclude user.ts

Cycle 2:
  DISPATCH: Search refined terms
  EVALUATE: Found session-manager.ts (0.95), jwt-utils.ts (0.85)
  REFINE: Sufficient context (2 high-relevance files)

Result: auth.ts, tokens.ts, session-manager.ts, jwt-utils.ts

示例 2:功能实现

Task: "Add rate limiting to API endpoints"

Cycle 1:
  DISPATCH: Search "rate", "limit", "api" in routes/**
  EVALUATE: No matches - codebase uses "throttle" terminology
  REFINE: Add "throttle", "middleware" keywords

Cycle 2:
  DISPATCH: Search refined terms
  EVALUATE: Found throttle.ts (0.9), middleware/index.ts (0.7)
  REFINE: Need router patterns

Cycle 3:
  DISPATCH: Search "router", "express" patterns
  EVALUATE: Found router-setup.ts (0.8)
  REFINE: Sufficient context

Result: throttle.ts, middleware/index.ts, router-setup.ts

与代理集成

在代理 Prompt 中使用:

When retrieving context for this task:
1. Start with broad keyword search
2. Evaluate each file's relevance (0-1 scale)
3. Identify what context is still missing
4. Refine search criteria and repeat (max 3 cycles)
5. Return files with relevance >= 0.7

最佳实践

  1. 从广泛开始并逐步缩小 - 不要过度指定初始查询
  2. 学习代码库术语 - 第一个循环中主要揭示命名约定
  3. 跟踪缺失项 - 显式识别差距以驱动改进
  4. 在“足够好”的水平停止 - 3 个高相关文件优于 10 个中等水平文件
  5. 自信地排除 - 低相关文件不会变得相关
  • The Longform Guide - 子代理编排部分
  • continuous-learning 技能 - 随时间改进的模式
  • ~/.claude/agents/ 中的代理定义

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC