A Practical Guide to Retrieval Infrastructure for AI Agents

    This article explains how to treat search as a core infrastructure layer for AI agents rather than a single feature. It breaks down a mature retrieval stack into four layers, covers unified API design, hybrid keyword and vector retrieval, reranking, scenario-specific practices for coding, research, security, and enterprise knowledge, evaluation metrics, deployment on general cloud capabilities, and common pitfalls to avoid.

    1. The Problem: Agents Can Work, but Visibility Is Still the Bottleneck

    Over the past six months, tasks such as code generation, research, log investigation, and security auditing have shifted from “requiring a human to guide every step” to “the model can complete most of the work independently.” But as tasks move from closed domains to open domains, the bottleneck shifts quickly: no matter how strong the model’s reasoning is, it cannot know the latest state of the world out of thin air. Three gaps—factual accuracy, timeliness, and long-tail knowledge—can only be filled by external retrieval.

    An industry conclusion that has been repeatedly validated is this: the same model, paired with more complete retrieval and higher-quality context, shows a clear jump in real-world usability. Search should therefore be treated not as a feature point but as a layer of infrastructure in the agent runtime, on the same level as compute, storage, and message queues.

    It is worth emphasizing that this article does not review or recommend any specific product. Instead, it breaks down the general engineering problem of “providing a unified retrieval entry point for agents.”

    2. Abstracting Search as Infrastructure: Four Layers

    A mature retrieval layer can usually be split into four layers, decoupled from each other through clear contracts:

    1. Data source ingestion layer: web page bodies, code repositories, Q&A communities, structured market data and databases, and internal enterprise documents. Each source type has different crawl frequencies, deduplication strategies, and copyright and compliance constraints.
    2. Indexing and recall layer: inverted indexes handle exact keyword matches, vector indexes handle approximate semantic recall, and the two are fused into hybrid retrieval.
    3. Orchestration and reranking layer: query rewriting, multi-path recall, deduplication, reranking, and context trimming determine the quality of the content ultimately fed to the model.
    4. Serving and governance layer: authentication, quotas, rate limiting, caching, observability, and cost accounting.

    The value of layering is this: swapping a data source does not touch orchestration, swapping a model does not touch the index, and scaling targets only the hot layer.

    3. Designing the Unified Retrieval Interface

    It is recommended to converge retrieval capability into a semantically stable abstract interface that hides the underlying heterogeneity:

    1. {
    2. "query": "engineering trade-offs of distributed rate limiting algorithms",
    3. "top_k": 8,
    4. "filters": { "source_type": ["web", "code", "qa"], "lang": ["en"] },
    5. "time_range": "recent_30d",
    6. "response_mode": "summary_with_citations"
    7. }

    There are four key design points. First, the response structure must carry source identifiers and citable snippets, so the model can generate answers with attribution and humans can review them. Second, top_k should be linked to the context budget and dynamically converged by the orchestration layer based on the model’s window, rather than hard-coded. Third, retrieval timeouts need a fallback path: if the primary path times out, degrade to pure keyword recall; if that also fails, return an empty set and explicitly tell the model that “information is insufficient” to prevent fabrication. Fourth, every request carries a trace identifier that spans the retrieval, reranking, and generation stages for end-to-end latency breakdown.

    4. Hybrid Retrieval: Why a Single Path Is Not Enough

    Pure vector retrieval is good at handling paraphrases but tends to fail on proper nouns, error codes, and version numbers; pure keyword retrieval is precise but has narrow recall. A more robust engineering approach is to run both paths in parallel and then fuse and rerank:

    1. def hybrid_search(q, top_k=8):
    2. kw = keyword_recall(q, top_k=top_k * 3) # exact matches first
    3. vec = vector_recall(embed(q), top_k=top_k * 3) # semantic expansion
    4. merged = deduplicate(kw + vec)
    5. return rerank(merged, q)[:top_k] # cross-encoder or lightweight scoring

    At the fusion stage, it is recommended to introduce three features: source credibility, publication-time decay, and body completeness. A page with only a summary should carry lower weight than a structurally complete long-form article—a tuning point many teams overlook but that yields clear gains.

    5. Practical Points for Different Scenarios

    Code and R&D scenarios: the retrieval target is not “articles” but executable context. You need to filter by file path, symbol name, and dependency version, and inject the repository’s directory structure as well; otherwise the model tends to produce code that does not match the actual project. Example:

    1. { "query": "retry backoff implementation",
    2. "filters": { "source_type": ["code"], "path_glob": ["src/**"], "version": "2.x" } }

    Research and intelligence scenarios: cross-validation across multiple sources takes priority over the number of results from a single recall. Require at least two independent sources for the same conclusion, and when they conflict, present the differences to the model as-is rather than making the trade-off for it in advance.

    Security and auditing scenarios: emphasize time windows and change sets. Audits often care about “what changed recently,” so time filtering and diff comparison matter more than semantic similarity.

    Internal enterprise knowledge scenarios: permissions must be enforced at the retrieval layer—authenticate first, then recall—to avoid the privilege risk of “retrieve first, filter later.”

    6. Evaluation: Turning “Feels Better” into Numbers

    A retrieval layer that cannot be evaluated cannot be iterated on. It is recommended to maintain at least four metrics: recall hit rate (whether the snippet containing the answer was recalled), answer accuracy (human or model review), end-to-end latency (P50/P95), and cost per task. Build a domain evaluation set of around a hundred items covering four categories: paraphrased queries, negative questions, multi-hop questions, and time-sensitive questions, and run a regression pass every time you adjust the index or reranking strategy. The empirical approach is: fix recall first, then fix ranking, and tune prompts and context budget last—reversing this order wastes effort.

    7. Deployment and Operations: Built on General Cloud Capabilities

    You do not need to build everything in-house. Crawl and parsing jobs can run on a container platform with elastic scaling; raw documents and snapshots go to object storage; a message queue decouples recall from generation and absorbs traffic spikes; retrieval and model calls go through a unified gateway for rate limiting and quotas; log services and monitoring alerts handle long-tail latency diagnosis and error-rate dashboards. Baidu AI Cloud offers corresponding capabilities in these general categories, and teams can integrate them smoothly with their existing tech stack. For caching, hot query results can be shared for a short window, but strongly time-sensitive queries should explicitly bypass the cache.

    8. Common Pitfalls Checklist

    First, stuffing the context too full dilutes the model’s attention and makes answers worse. Second, lacking an “insufficient information” exit leads to hallucination. Third, ignoring crawl compliance and copyright boundaries. Fourth, treating reranking as tuning by guesswork without an evaluation set to support it. Fifth, missing quota design—a single infinite loop of calls can exhaust the budget.

    9. Conclusion

    The essence of making search infrastructure is confining uncertainty within a controllable, observable, and replaceable engineering boundary. First define the layers and contracts clearly, then use hybrid retrieval and reranking to secure quality, and finally rely on evaluation and operations to preserve long-term performance—this path is more durable than chasing any single tool.