跳到正文
DEV Community· Achyut Srivastava·· 1 小時前AI 評分55

快速 AI 智能體的順序網頁搜尋為何失效,以及如何改進

Why Sequential Web Search Fails for Fast AI Agents (and How We Fixed It)

AI 導讀

文章提出以單次模型呼叫生成多個搜尋查詢、並行執行搜尋及 hedged requests 取代順序搜尋的 AI 智能體流程,並稱使用者等待時間可由 12s – 16s 降至 3s – 4s。文中提供 Python asyncio/httpx 範例,並建議在搜尋期間串流進度訊息,待綜合模型開始生成後即逐步輸出 token。

正文

If you've built an autonomous AI agent that searches the web, you've probably run into the exact same problem everyone faces: search latency destroys user experience.

The standard agent loop runs synchronously:

  1. Prompt model for Search Query #1 (2s)
  2. Wait for search API response (1.5s)
  3. Prompt model again to analyze if more info is needed (2s)
  4. Execute Search Query #2 (1.5s)
  5. Generate final response (3s)

Total latency: 10 to 15+ seconds. The user is left staring at a spinning wheel.

Here is an architectural breakdown of how to design an agentic search pipeline that runs in under 4 seconds using concurrency and request hedging.


1. The Real Bottleneck: Single-Query Tunnel Vision

When a user asks a complex technical question (for example, comparing framework compatibility or diagnosing a subtle bug), a single query rarely captures the whole picture.

To get a comprehensive answer, an AI needs multiple perspectives:

  • The official documentation or changelog
  • Community issue trackers (e.g., GitHub or forums)
  • Real-world benchmarks or migration guides

If your agent executes these steps one after another, you pay network roundtrip penalties every single time.

The Fix: Multi-Angle Generation in One Turn

Instead of letting the agent query, wait, and re-query in a loop, configure your agent's system prompt to generate multiple search angles upfront in a single structured output (such as a JSON array):

{
  "queries": [
    "library v2 breaking changes changelog",
    "library v2 common peer dependency issues",
    "library v2 performance migration guide"
  ]
}

By generating all necessary search queries in a single inference call, you eliminate multiple roundtrips entirely.


2. Parallel Search Execution

Once you have your list of queries, never execute them in a serial for loop. Standard asynchronous execution in Python allows you to dispatch all search queries simultaneously:

import asyncio
import httpx

async def fetch_query(client: httpx.AsyncClient, query: str):
    # Standard external search API call
    response = await client.get("https://api.example.com/search", params={"q": query})
    return response.json()

async def search_in_parallel(queries: list[str]):
    async with httpx.AsyncClient(timeout=5.0) as client:
        # Dispatch all queries concurrently
        tasks = [fetch_query(client, q) for q in queries]
        results = await asyncio.gather(*tasks, return_exceptions=True)

    # Aggregate and deduplicate documents
    documents = []
    seen = set()
    for res in results:
        if isinstance(res, dict) and "items" in res:
            for item in res["items"]:
                url = item.get("url")
                if url not in seen:
                    seen.add(url)
                    documents.append(item)
    return documents

By querying your search provider concurrently, 3 queries take essentially the same amount of time as 1 query (~1.5s instead of 4.5s).


3. Dealing with Upstream Latency Jitter

In production AI apps, upstream API latency can fluctuate heavily due to rate limits or regional routing delays.

If your application depends on an external API that occasionally spikes from 500ms to 3,000ms, a classic distributed systems technique to smooth out the tail latency is hedged requests: sending redundant calls or racing fallbacks using asyncio.wait(..., return_when=asyncio.FIRST_COMPLETED).

This ensures that the user experience is determined by the fastest response, rather than being dragged down by the slowest outlier.


4. Streaming UX: Don't Leave Users in the Dark

When an agent is performing live searches, do not hold back the entire response until everything finishes.

  1. Emit Instant Status Events: As soon as queries are dispatched, stream a lightweight progress indicator (e.g., "Searching 3 sources...").
  2. Buffer Structural Metadata: Keep search parameters and raw API payloads out of the visible conversational text so the client only sees clean, formatted answers.
  3. Stream Tokens Progressively: The moment the synthesis model begins generating text with the aggregated context, stream tokens immediately to maintain sub-second Time to First Token (TTFT).

Summary of Results

Switching from a sequential agent loop to a concurrent multi-query architecture yields dramatic improvements:

Architecture Query Time Roundtrips User Wait Time
Sequential Loop ~6.0s (3 x 2s) 3+ back-and-forth turns 12s – 16s
Concurrent Multi-Query ~1.5s (parallel) 1 single turn 3s – 4s

If you're building agentic tools, designing around concurrency and network latency is just as important as the model you choose.


Written by the engineering team at LuxurAI. We build fast developer tools and AI infrastructure. Check out our public Python SDK at pypi.org/project/luxur-ai.

來源:DEV Community · dev.to