AI Agent Search in Practice: Accessing Deep Web and Structured Data
This article explains why AI agents often fail to get the data they need, and how a unified search infrastructure can return structured, traceable results by combining web retrieval, vertical APIs, and private data queries. It covers the stages of search technology, an adapter design, output validation, latency control, evaluation methods, and compliance considerations.
1. Search Blind Spots: Why Agents Cannot Get Usable Data
In complex enterprise settings, agents often need precise data to make decisions. Common failures include the following. When querying a company’s equity penetration structure, the agent only gets a generic profile from the company’s official website. When searching for production-grade code, it returns beginner tutorials. When analyzing threat intelligence for a suspicious IP address, it returns a popular science article.
The problem mainly lies in the input. The internet holds large amounts of deep web data and structured databases. Because of technical limits or access controls, conventional search engines usually do not index them. If an agent can only read web summaries, its output quality is capped by its input, no matter how large the model is or how strong its reasoning. Feeding incomplete or low-quality information to a model does not make the results better.
2. From Web Summaries to Structured Retrieval: The Evolution of Search
Some people divide the development of search technology into four stages. This division has no unified standard. This article uses it only to organize the discussion.
| Stage | Representative approach | What is returned to the agent | Main limitation |
|---|---|---|---|
| Stage 1 | Keyword matching | List of web links | Depends on keywords and requires manual filtering |
| Stage 2 | Knowledge graph semantic search | Entities and relationships | Limited graph coverage and delayed updates |
| Stage 3 | LLM-based web summarization | Natural language summaries | Summaries may lose details, and sources are hard to verify |
| Stage 4 (the direction discussed in this article) | Structured, trusted retrieval | Structured data with fields and sources | High integration cost, and it requires permission and compliance management |
The search infrastructure of Stage 4 needs three capabilities:
- Deep web data access: Connect to professional databases, APIs, and internal data sources in vertical domains. Only connect to sources that are authorized or explicitly allowed to be accessed.
- Multi-format data processing: Process text, code, tables, and charts in a unified way, and convert them into a standard format that large language models can understand.
- Credibility filtering: Identify authoritative sources, remove noise and low-quality content, and record the source and retrieval time of each piece of data.
3. Building a Unified Search Infrastructure
3.1 Multi-Source Access and Adaptation
A single web crawler cannot meet the needs of an agent. Most teams need a data adaptation layer that handles three types of access.
- Public web retrieval: Crawl regular web pages, and use a model during indexing to assess content quality. Prioritize reliable sources such as technical communities and official documentation. Before crawling, check robots.txt and the website’s terms of service, control request frequency, and respect privacy requirements. For sites with access restrictions, do not try to bypass anti-crawling mechanisms. Use the official interface or data license the site provides instead.
- Vertical API integration: Domains such as financial data, threat intelligence, and code repositories usually provide official APIs. Integration requires handling authentication, quotas, and error code mapping, and keeping call logs for auditing. Relevant personnel must confirm the API’s terms of use and data licensing before integration.
- Private data queries: Internal knowledge bases stored in object storage or relational databases can combine vector retrieval with SQL queries for joint searches across internal and external data. SQL queries must use parameterized statements. Never concatenate user input directly into a query.
The following pseudocode illustrates the structure. It is not ready for production. Some helper methods, such as intent recognition, permission checks, and result ranking, must be implemented according to the actual system.
import asyncioimport loggingfrom dataclasses import dataclass, fieldlogger = logging.getLogger("search")@dataclassclass SearchResult:source: strpayload: dictscore: float = 0.0meta: dict = field(default_factory=dict)class UnifiedSearchAdapter:"""Pseudocode: demonstrates the call structure. Helper methods must be implemented separately."""def __init__(self, web_engine, api_connectors, db_manager,cache, rate_limiter, timeout_s=3.0, max_retries=2):self.web_engine = web_engineself.apis = api_connectorsself.db = db_managerself.cache = cacheself.limiter = rate_limiterself.timeout_s = timeout_sself.max_retries = max_retriesasync def search(self, query: str, context: dict) -> list[SearchResult]:# 1. Permission check: the caller can only access authorized data sourcesif not self._check_permission(context.get("user_id"), query):raise PermissionError("The caller is not authorized to access this data source")# 2. Check the cache. The cache key must not contain sensitive informationcache_key = self._cache_key(query, context)cached = await self.cache.get(cache_key)if cached is not None:return cached# 3. Intent recognition and data source routingintent = self._analyze_intent(query)tasks = []if intent["need_public_web"]:tasks.append(self._call("web", self.web_engine.search, query))if intent["need_finance"]:tasks.append(self._call("finance", self.apis["finance"].fetch, query))if intent["need_internal_docs"]:tasks.append(self._call("internal", self.db.vector_search, query))# 4. Run queries in parallel. A failure in one data source does not affect the othersoutputs = await asyncio.gather(*tasks, return_exceptions=True)results: list[SearchResult] = []for out in outputs:if isinstance(out, Exception):logger.warning("Data source call failed: %s", type(out).__name__)continueresults.extend(out)# 5. Normalize and rank results, then write them to the cachenormalized = self._normalize_and_rank(results)await self.cache.set(cache_key, normalized, ttl=300)return normalizedasync def _call(self, source, func, query):# Apply rate limiting before each call. Retry only on timeouts, using exponential backofffor attempt in range(self.max_retries + 1):await self.limiter.acquire(source)try:return await asyncio.wait_for(func(query), timeout=self.timeout_s)except asyncio.TimeoutError:if attempt == self.max_retries:raiseawait asyncio.sleep(2 ** attempt * 0.5)
Several design points in the code need explanation. Permission checks run first. Cache keys contain no credentials or personal information. When one data source fails, results from the other sources are still returned. Retries apply only to timeouts, not to permission or parameter errors. Logs record only the exception type, so query content and keys are never written to logs. Secrets should be read from environment variables or a key management service, never hard-coded.
3.2 Structured Output and Validation
After data is retrieved, HTML, JSON, or plain text must be organized into a fixed structure. Using company information as an example, you can use a JSON Schema to constrain the output fields:
{"$schema": "https://json-schema.org/draft/2020-12/schema","type": "object","required": ["company_name", "legal_representative", "registered_capital_wan_cny", "shareholders", "source_url", "retrieved_at"],"properties": {"company_name": {"type": "string", "minLength": 1},"legal_representative": {"type": ["string", "null"]},"registered_capital_wan_cny": {"type": ["number", "null"], "minimum": 0},"shareholders": {"type": "array","items": {"type": "object","required": ["name", "ratio"],"properties": {"name": {"type": "string"},"ratio": {"type": "number", "minimum": 0, "maximum": 100}}}},"source_url": {"type": "string", "format": "uri"},"retrieved_at": {"type": "string", "format": "date-time"}},"additionalProperties": false}
Model output must be validated. If validation fails, first ask the model to regenerate the output once according to the schema. If it still fails, mark the missing fields as null and attach the reason. Do not let the model guess and fill them in. Once fields are constrained, parsing errors in downstream agents usually decrease, and repeated calls caused by invalid output also decrease.
3.3 Performance and Latency Control
Multi-step agent reasoning calls search frequently, so latency directly affects total processing time. Three common techniques help. First, cache the results of frequent queries and set reasonable expiration times. Second, when a data source supports streaming, pass partial results to the agent first. Third, set independent timeouts for each data source so that a slow source does not stall the entire workflow.
Latency targets should be set by business SLAs, not copied from others. Measurements must state concurrency, data source type, cache hit rate, and network conditions. Otherwise, the numbers cannot be compared. For example, a team can first record its current P50, P95, and P99 as a baseline, then optimize slow queries step by step.
4. Evaluation and Verification: Measuring Search Capability
Improvements in search capability should be judged by benchmark tests, not by subjective impressions. The table below gives an evaluation framework. Teams should set the thresholds based on their own baselines.
| Dimension | Metric | Test set | Pass threshold | Measurement conditions |
|---|---|---|---|---|
| Accuracy | Factual accuracy rate | Manually labeled fact-checking samples, with the sample source and labeling rules documented | Set based on baseline | Fixed model version; record prompts and data snapshots |
| Completeness | Dimension coverage rate | Multi-dimensional query samples, each listing the dimensions it should cover | Set based on baseline | Same as above |
| Response latency | P50, P95, P99 | Requests built from the real traffic distribution |
