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.

    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:

    1. 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.
    2. 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.
    3. 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.

    1. import asyncio
    2. import logging
    3. from dataclasses import dataclass, field
    4. logger = logging.getLogger("search")
    5. @dataclass
    6. class SearchResult:
    7. source: str
    8. payload: dict
    9. score: float = 0.0
    10. meta: dict = field(default_factory=dict)
    11. class UnifiedSearchAdapter:
    12. """Pseudocode: demonstrates the call structure. Helper methods must be implemented separately."""
    13. def __init__(self, web_engine, api_connectors, db_manager,
    14. cache, rate_limiter, timeout_s=3.0, max_retries=2):
    15. self.web_engine = web_engine
    16. self.apis = api_connectors
    17. self.db = db_manager
    18. self.cache = cache
    19. self.limiter = rate_limiter
    20. self.timeout_s = timeout_s
    21. self.max_retries = max_retries
    22. async def search(self, query: str, context: dict) -> list[SearchResult]:
    23. # 1. Permission check: the caller can only access authorized data sources
    24. if not self._check_permission(context.get("user_id"), query):
    25. raise PermissionError("The caller is not authorized to access this data source")
    26. # 2. Check the cache. The cache key must not contain sensitive information
    27. cache_key = self._cache_key(query, context)
    28. cached = await self.cache.get(cache_key)
    29. if cached is not None:
    30. return cached
    31. # 3. Intent recognition and data source routing
    32. intent = self._analyze_intent(query)
    33. tasks = []
    34. if intent["need_public_web"]:
    35. tasks.append(self._call("web", self.web_engine.search, query))
    36. if intent["need_finance"]:
    37. tasks.append(self._call("finance", self.apis["finance"].fetch, query))
    38. if intent["need_internal_docs"]:
    39. tasks.append(self._call("internal", self.db.vector_search, query))
    40. # 4. Run queries in parallel. A failure in one data source does not affect the others
    41. outputs = await asyncio.gather(*tasks, return_exceptions=True)
    42. results: list[SearchResult] = []
    43. for out in outputs:
    44. if isinstance(out, Exception):
    45. logger.warning("Data source call failed: %s", type(out).__name__)
    46. continue
    47. results.extend(out)
    48. # 5. Normalize and rank results, then write them to the cache
    49. normalized = self._normalize_and_rank(results)
    50. await self.cache.set(cache_key, normalized, ttl=300)
    51. return normalized
    52. async def _call(self, source, func, query):
    53. # Apply rate limiting before each call. Retry only on timeouts, using exponential backoff
    54. for attempt in range(self.max_retries + 1):
    55. await self.limiter.acquire(source)
    56. try:
    57. return await asyncio.wait_for(func(query), timeout=self.timeout_s)
    58. except asyncio.TimeoutError:
    59. if attempt == self.max_retries:
    60. raise
    61. await 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:

    1. {
    2. "$schema": "https://json-schema.org/draft/2020-12/schema",
    3. "type": "object",
    4. "required": ["company_name", "legal_representative", "registered_capital_wan_cny", "shareholders", "source_url", "retrieved_at"],
    5. "properties": {
    6. "company_name": {"type": "string", "minLength": 1},
    7. "legal_representative": {"type": ["string", "null"]},
    8. "registered_capital_wan_cny": {"type": ["number", "null"], "minimum": 0},
    9. "shareholders": {
    10. "type": "array",
    11. "items": {
    12. "type": "object",
    13. "required": ["name", "ratio"],
    14. "properties": {
    15. "name": {"type": "string"},
    16. "ratio": {"type": "number", "minimum": 0, "maximum": 100}
    17. }
    18. }
    19. },
    20. "source_url": {"type": "string", "format": "uri"},
    21. "retrieved_at": {"type": "string", "format": "date-time"}
    22. },
    23. "additionalProperties": false
    24. }

    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