Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend/copilot): web_search returns every cited source with its number (#15186)

Bently7e448a4d436a
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index dfd81cbb6d..80d8447866 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -1069,12 +1069,12 @@ class WebFetchResponse(ToolResponseBase):
class WebSearchResult(BaseModel):
- """One entry in a web_search tool response."""
+ """One source in a web_search tool response. ``n`` is the number the
+ answer cites it by, as ``[n]``."""
+ n: int
title: str
url: str
- snippet: str = ""
- page_age: str | None = None
class WebSearchResponse(ToolResponseBase):
diff --git a/autogpt_platform/backend/backend/copilot/tools/testdata/web_search_sonar_responses.json b/autogpt_platform/backend/backend/copilot/tools/testdata/web_search_sonar_responses.json
new file mode 100644
index 0000000000..aa16da3c2e
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/testdata/web_search_sonar_responses.json
@@ -0,0 +1,540 @@
+{
+ "_note": "Real perplexity/sonar responses recorded through OpenRouter on 2026-10-05 (ids replaced). Annotation i is the answer's [i+1]; start/end_index are always 0 and there is no content or search_results field.",
+ "jwst_news": {
+ "object": "chat.completion",
+ "created": 1791211110,
+ "model": "perplexity/sonar",
+ "provider": "Perplexity",
+ "system_fingerprint": null,
+ "service_tier": null,
+ "choices": [
+ {
+ "index": 0,
+ "logprobs": null,
+ "finish_reason": "stop",
+ "native_finish_reason": "stop",
+ "message": {
+ "role": "assistant",
+ "content": "Here are the **latest Webb discoveries highlighted in current NASA, ESA, and major space-news coverage**:\n\n- **Water and dust near the Milky Way’s central black hole:** Webb found that **oxygen-rich dust and water can survive surprisingly close to Sagittarius A\\***, our galaxy’s supermassive black hole.[2][21]\n- **A new moon at Uranus:** NASA reported that a Webb team identified a **previously unknown Uranian moon**, bringing the planet’s known satellite count to **29**.[7]\n- **Extremely early galaxies:** Webb has continued to push the timeline back, with reports of galaxies existing about **280 million years after the Big Bang** and other early-universe objects that challenge current galaxy-formation models.[12][11]\n- **Heavy elements in the young universe:** Webb observations indicate that by about **500 million years after the Big Bang**, galaxies were already enriching their surroundings with elements like **oxygen, carbon, and silicon**.[22][3]\n- **Star formation in IC 348:** NASA recently highlighted Webb observations of **IC 348**, a nearby star-forming region about **1,000 light-years** away.[1][4]\n- **New details in nearby star and galaxy systems:** ESA’s latest Webb releases include studies of **young stellar systems**, **brown dwarfs as light as twice Jupiter’s mass**, and **centaurus A’s crowded center**, all using Webb’s infrared sensitivity to reveal structures hidden in visible light.[2][6]\n- **Potential exoplanet breakthroughs:** Webb has also been used to study worlds such as **WD 1856 b**, where it measured the planet’s **mass, temperature, and atmosphere**, and to probe other candidate planets and atmospheres in recent coverage.[2][16]\n\nIf you want, I can turn this into a **“top 5 most important JWST discoveries of 2026”** list or a **breakdown by topic**: early universe, exoplanets, stars, or Solar System.",
+ "refusal": null,
+ "reasoning": null,
+ "annotations": [
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://science.nasa.gov/mission/webb/latestnews/",
+ "title": "News",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://esawebb.org/news/",
+ "title": "Press Releases - ESA/Webb",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.space.com/astronomy/james-webb-space-telescope",
+ "title": "James Webb Space Telescope",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://science.nasa.gov/mission/webb/",
+ "title": "James Webb Space Telescope - NASA Science",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.esa.int/Science_Exploration/Space_Science/Webb",
+ "title": "ESA - Webb",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://esawebb.org/news/archive/year/2026/",
+ "title": "Press Releases 2026 | ESA/Webb",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://science.nasa.gov/blogs/webb/",
+ "title": "James Webb Space Telescope Archives - NASA Science",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://science.nasa.gov/mission/webb/science-overview/",
+ "title": "Science Overview",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://science.nasa.gov/mission/webb/other-worlds/",
+ "title": "Other Worlds",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://news.abplive.com/topic/nasa-james-webb-space-telescope",
+ "title": "Nasa James Webb Space Telescope News: Latest News, Photos, Videos & Live Updates | ABP Live English",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.space.com/news/live/james-webb-space-telescope-updates",
+ "title": "NASA's James Webb Space Telescope mission — Live updates",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://science.nasa.gov/mission/webb/early-universe/",
+ "title": "Early Universe",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.sciencedaily.com/releases/2026/08/260822015141.htm",
+ "title": "www.sciencedaily.com › releases › 2026JWST finds early galaxies may be 4 times more massive than ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://esawebb.org/news/page/3/?search=galaxies",
+ "title": "Press Releases - ESA/Webb",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.newsbytesapp.com/news/science/james-webb-space-telescope",
+ "title": "James Webb Space Telescope: Latest News, News Articles, Photos, Videos - NewsBytes",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.cbsnews.com/tag/james-webb-space-telescope/",
+ "title": "James Webb Space Telescope news - Today's latest updates",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://news.abplive.com/topic/webb-space-telescope",
+ "title": "Webb Space Telescope News: Latest News, Photos, Videos & Live Updates | ABP Live English",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.skyatnightmagazine.com/space-missions/james-webb-space-telescope-images",
+ "title": "NASA James Webb Space Telescope latest images",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://science.nasa.gov/missions/webb/3-years-of-science-10-cosmic-surprises-from-nasas-webb-telescope/",
+ "title": "3 Years of Science: 10 Cosmic Surprises from NASA’s Webb Telescope",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.space.com/astronomy/james-webb-space-telescope/james-webb-space-telescope-and-hubble-discover-27-puzzling-new-objects-orbiting-the-sun-far-beyond-neptune",
+ "title": "James Webb Space Telescope and Hubble discover 27 ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.space.com/astronomy/james-webb-space-telescope-finds-water-near-our-nearest-supermassive-black-hole-space-photo-of-the-day-for-sept-23-2026",
+ "title": "James Webb Space Telescope finds water near our nearest ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.space.com/astronomy/james-webb-space-telescope/james-webb-space-telescope-looks-back-in-time-finds-our-ancient-universe-wasnt-as-pure-as-we-thought",
+ "title": "James Webb Space Telescope finds our ancient universe ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.sciencedaily.com/releases/2025/04/250424121701.htm",
+ "title": "Scientists use James Webb Space Telescope to better ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.space.com/astronomy",
+ "title": "Astronomy Coverage",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.sciencedaily.com/releases/2025/03/250310152925.htm",
+ "title": "James Webb Space Telescope reveals unexpected ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ }
+ ]
+ }
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 9,
+ "completion_tokens": 429,
+ "total_tokens": 438,
+ "cost": 0.00544,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 0.00544,
+ "upstream_inference_prompt_cost": 0.000009,
+ "upstream_inference_completions_cost": 0.005431
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "id": "gen-recorded-jwst-news"
+ },
+ "central_bank_rates": {
+ "object": "chat.completion",
+ "created": 1791211110,
+ "model": "perplexity/sonar",
+ "provider": "Perplexity",
+ "system_fingerprint": null,
+ "service_tier": null,
+ "choices": [
+ {
+ "index": 0,
+ "logprobs": null,
+ "finish_reason": "stop",
+ "native_finish_reason": "stop",
+ "message": {
+ "role": "assistant",
+ "content": "The **Fed**’s current target range is **3.75%–4.00%**.[10][20] For the other major central banks, I don’t have reliable current-rate search results in the provided set for the **ECB**, **Bank of England**, or **Bank of Japan**, so I can’t state their latest policy rates with confidence from these sources alone.\n\n- **Federal Reserve (Fed):** **3.75%–4.00%**.[10][20]\n- **European Central Bank (ECB):** not verifiable from the provided results.\n- **Bank of England (BoE):** not verifiable from the provided results.\n- **Bank of Japan (BoJ):** not verifiable from the provided results.\n\nIf you want, I can help you compile the latest rates for the ECB, BoE, and BoJ from up-to-date sources as well.",
+ "refusal": null,
+ "reasoning": null,
+ "annotations": [
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.newyorkfed.org/markets/reference-rates/effr",
+ "title": "Effective Federal Funds Rate",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://tradingeconomics.com/united-states/interest-rate",
+ "title": "United States Fed Funds Interest Rate",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.federalreserve.gov/releases/h15/",
+ "title": "Federal Reserve Board - H.15 - Selected Interest Rates (Daily)",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://fred.stlouisfed.org/series/FF",
+ "title": "Federal Funds Effective Rate (FF) | FRED | St. Louis Fed",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.usbank.com/investing/financial-perspectives/market-news/federal-reserve-tapering-asset-purchases.html",
+ "title": "Federal Reserve Monetary Policy | U.S. Bank",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.tradingview.com/symbols/ECONOMICS-USINTR/",
+ "title": "Usintr",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.usbank.com/investing/financial-perspectives/market-news/federal-reserve-interest-rate.html",
+ "title": "Fed raises rates to 3.75%-4.00%, first hike since 2023",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.federalreserve.gov/economy-at-a-glance-policy-rate.htm",
+ "title": "The Fed - Economy at a Glance - Policy Rate - Federal Reserve",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.investing.com/central-banks/",
+ "title": "Central Banks Interest Rates",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://finance.yahoo.com/economy/policy/live/federal-reserve-meeting-live-updates-25-basis-point-interest-rate-hike-chairman-kevin-warsh-143452661.html",
+ "title": "Fed meeting live updates: Fed hikes interest rates by 25 ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.bankrate.com/banking/federal-reserve/",
+ "title": "The Federal Reserve And Your Money | Bankrate",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.investing.com/central-banks/fed-rate-monitor",
+ "title": "Fed Rate Monitor Tool",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://finance.yahoo.com/economy/policy/live/federal-reserve-meeting-live-updates-chairman-kevin-warsh-143452661.html",
+ "title": "Fed meeting live updates: Fed hikes interest rates by 25 basis points for ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://finance.yahoo.com/personal-finance/banking/article/do-we-want-high-or-low-interest-rates-223031516.html",
+ "title": "Understanding the Fed's rate decisions: Do we want high or low interest rates​?",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.cnbc.com/2026/07/29/fed-rate-decision-july-2026.html",
+ "title": "Divided Fed holds interest rates steady",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.cnn.com/2026/09/16/business/live-news/federal-reserve-interest-rate-september",
+ "title": "www.cnn.com · 2026/09/16 · businessFed raises interest rates for the first time since 2023",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.usatoday.com/story/money/economy/2026/09/16/fed-rate-decision-meeting-updates--live/91746863007/",
+ "title": "Fed raises rates for first time since 2023. What it means for you",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.nytimes.com/live/2026/09/16/business/fed-meeting-warsh-interest-rates/what-to-know-about-the-feds-decision?eafs_enabled=false",
+ "title": "Fed Raises Interest Rates in Push for 'Timelier' Retreat ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://finance.yahoo.com/economy/policy/articles/fed-hikes-key-interest-rate-174644822.html",
+ "title": "Fed Hikes Key Interest Rate for First Time Since 2023 - Yahoo Finance",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.cnbc.com/amp/2026/09/16/fed-meeting-today-live-updates.html",
+ "title": "Fed meeting today: Live updates",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://finance.yahoo.com/economy/policy/articles/us-federal-raises-key-interest-211933297.html",
+ "title": "US Federal Reserve raises key interest rate for first time ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://abc7.com/story/federal-reserve-expected-raise-interest-rates-first-time-2023/19838663/",
+ "title": "Federal Reserve expected to raise interest rates for the first ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.cnbc.com/2026/09/16/fed-meeting-today-live-updates.html?msockid=27a93fff2e8d65c32546281c2f83642f",
+ "title": "Fed meeting today: Live updates - CNBC",
+ "start_index": 0,
+ "end_index": 0
+ }
+ },
+ {
+ "type": "url_citation",
+ "url_citation": {
+ "url": "https://www.pbs.org/newshour/amp/economy/watch-live-warsh-holds-briefing-after-fed-meeting-as-interest-rates-expected-to-rise",
+ "title": "WATCH LIVE: Warsh holds briefing after Fed meeting as interest ...",
+ "start_index": 0,
+ "end_index": 0
+ }
+ }
+ ]
+ }
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 21,
+ "completion_tokens": 191,
+ "total_tokens": 212,
+ "cost": 0.00521,
+ "is_byok": false,
+ "prompt_tokens_details": {
+ "cached_tokens": 0,
+ "cache_write_tokens": 0,
+ "audio_tokens": 0,
+ "video_tokens": 0
+ },
+ "cost_details": {
+ "upstream_inference_cost": 0.00521,
+ "upstream_inference_prompt_cost": 0.000021,
+ "upstream_inference_completions_cost": 0.005189
+ },
+ "completion_tokens_details": {
+ "reasoning_tokens": 0,
+ "image_tokens": 0,
+ "audio_tokens": 0
+ }
+ },
+ "id": "gen-recorded-central-bank-rates"
+ }
+}
diff --git a/autogpt_platform/backend/backend/copilot/tools/web_search.py b/autogpt_platform/backend/backend/copilot/tools/web_search.py
index 6add6389e6..4a429f916f 100644
--- a/autogpt_platform/backend/backend/copilot/tools/web_search.py
+++ b/autogpt_platform/backend/backend/copilot/tools/web_search.py
@@ -26,6 +26,7 @@ drift. ``_extract_cost_usd`` mirrors the baseline service's
import logging
import math
+import re
from typing import Any
from openai import AsyncOpenAI
@@ -55,7 +56,10 @@ _DEEP_MAX_TOKENS = _QUICK_MAX_TOKENS * 4
_DEFAULT_MAX_RESULTS = 5
_HARD_MAX_RESULTS = 20
-_SNIPPET_MAX_CHARS = 500
+
+# Sonar cites sources inline as ``[n]``; ``n`` is the 1-based position
+# of the source in the response's ``url_citation`` annotations.
+_CITATION_MARKER = re.compile(r"\[(\d{1,3})\]")
# OpenRouter-specific extra_body flag that embeds the real generation
# cost into the response usage object. Same dict shape the baseline
@@ -74,8 +78,9 @@ class WebSearchTool(BaseTool):
def description(self) -> str:
return (
"Search the web for live info (news, recent docs). Returns a "
- "synthesised answer grounded in fresh page content plus "
- "{title, url, snippet} citations — read the answer first "
+ "synthesised answer grounded in fresh page content, citing "
+ "sources as [n], plus {n, title, url} for every source it "
+ "cites — read the answer first "
"before reaching for web_fetch. Set deep=true when the user "
"asks for research / comparison / in-depth analysis; leave "
"deep=false for quick fact lookups. Prefer one targeted "
@@ -94,8 +99,10 @@ class WebSearchTool(BaseTool):
"max_results": {
"type": "integer",
"description": (
- f"Max results (default {_DEFAULT_MAX_RESULTS}, "
- f"cap {_HARD_MAX_RESULTS})."
+ "Minimum number of sources to return (default "
+ f"{_DEFAULT_MAX_RESULTS}, capped at {_HARD_MAX_RESULTS}). "
+ "It is a floor, not a limit: every source the answer "
+ "cites is always returned, even beyond this number."
),
"default": _DEFAULT_MAX_RESULTS,
},
@@ -226,37 +233,49 @@ def _extract_answer(resp: ChatCompletion) -> str:
def _extract_results(resp: ChatCompletion, *, limit: int) -> list[WebSearchResult]:
- """Pull ``url_citation`` annotations from the response.
-
- Shared across both tiers — OpenRouter normalises the annotation
- schema across Perplexity's sonar models into
- ``Annotation.url_citation`` (typed in ``openai.types.chat``). The
- ``content`` snippet is an OpenRouter extension on the otherwise-
- typed ``AnnotationURLCitation``; pydantic stashes unknown fields in
- ``model_extra``, which we read there rather than via ``getattr``.
+ """Return the sources the answer cites, each with its ``[n]`` number.
+
+ OpenRouter passes Perplexity's whole source list through as
+ ``url_citation`` annotations (``openai.types.chat``), in the order
+ the answer numbers them: annotation i is ``[i+1]``. Their
+ ``start_index``/``end_index`` are always 0 and no page snippet comes
+ with them, so the answer's ``[n]`` markers are the only link between
+ a claim and its source.
+
+ Every source the answer cites is returned (up to
+ ``_HARD_MAX_RESULTS``), so no marker is left without its source.
+ When the answer cites fewer than ``limit``, the first uncited
+ sources fill the list up to ``limit``. Markers with no matching
+ annotation are dropped; two numbers that share a URL each keep
+ their own entry, so every cited number still resolves.
"""
if not resp.choices:
return []
- annotations = resp.choices[0].message.annotations or []
- out: list[WebSearchResult] = []
- for ann in annotations:
- if len(out) >= limit:
- break
- if ann.type != "url_citation":
- continue
- citation = ann.url_citation
- extras = citation.model_extra or {}
- snippet_raw = extras.get("content")
- snippet = (snippet_raw or "")[:_SNIPPET_MAX_CHARS] if snippet_raw else ""
- out.append(
- WebSearchResult(
- title=citation.title,
- url=citation.url,
- snippet=snippet,
- page_age=None,
- )
+ message = resp.choices[0].message
+ sources = [
+ ann.url_citation
+ for ann in message.annotations or []
+ if ann.type == "url_citation"
+ ]
+ cited = _cited_numbers(message.content or "", len(sources))
+ if len(cited) > _HARD_MAX_RESULTS:
+ logger.info(
+ f"[web_search] answer cites {len(cited)} sources; "
+ f"returning the first {_HARD_MAX_RESULTS}"
)
- return out
+ cited = cited[:_HARD_MAX_RESULTS]
+ uncited = [n for n in range(1, len(sources) + 1) if n not in cited]
+ numbers = sorted(cited + uncited[: max(0, limit - len(cited))])
+ return [
+ WebSearchResult(n=n, title=sources[n - 1].title, url=sources[n - 1].url)
+ for n in numbers
+ ]
+
+
+def _cited_numbers(answer: str, source_count: int) -> list[int]:
+ """Distinct ``[n]`` numbers in ``answer`` that name a source, ascending."""
+ found = {int(m) for m in _CITATION_MARKER.findall(answer)}
+ return sorted(n for n in found if 1 <= n <= source_count)
def _extract_cost_usd(usage: CompletionUsage | None) -> float | None:
diff --git a/autogpt_platform/backend/backend/copilot/tools/web_search_test.py b/autogpt_platform/backend/backend/copilot/tools/web_search_test.py
index 7b341e3c44..8464cffecf 100644
--- a/autogpt_platform/backend/backend/copilot/tools/web_search_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/web_search_test.py
@@ -9,6 +9,9 @@ the handler plumbs through to ``persist_and_record_usage`` with
``provider='open_router'`` and the real ``usage.cost`` value.
"""
+import json
+import re
+from pathlib import Path
from typing import Any
from unittest.mock import AsyncMock, patch
@@ -24,7 +27,7 @@ from openai.types.chat.chat_completion_message import (
from backend.copilot.model import ChatSession
-from .models import ErrorResponse, WebSearchResponse
+from .models import ErrorResponse, WebSearchResponse, WebSearchResult
from .web_search import (
WebSearchTool,
_extract_answer,
@@ -54,19 +57,12 @@ def _usage(
return CompletionUsage.model_construct(None, **payload)
-def _citation(*, url: str, title: str, content: str | None = None) -> Annotation:
- """Typed ``Annotation`` for a URL citation. ``content`` is an
- OpenRouter extension on the otherwise-typed schema — goes into
- ``url_citation.model_extra`` when model_construct preserves it."""
- payload: dict[str, Any] = {
- "url": url,
- "title": title,
- "start_index": 0,
- "end_index": len(title),
- }
- if content is not None:
- payload["content"] = content
- url_citation = AnnotationURLCitation.model_construct(None, **payload)
+def _citation(*, url: str, title: str) -> Annotation:
+ """Typed ``Annotation`` for a URL citation, shaped like OpenRouter's
+ Sonar annotations (indices always 0, no snippet)."""
+ url_citation = AnnotationURLCitation(
+ url=url, title=title, start_index=0, end_index=0
+ )
return Annotation(type="url_citation", url_citation=url_citation)
@@ -82,11 +78,7 @@ def _fake_response(
response — typed end-to-end so the production code's attribute
access runs under the real SDK types in tests."""
annotations = [
- _citation(
- url=c.get("url", ""),
- title=c.get("title", "untitled"),
- content=c.get("content"),
- )
+ _citation(url=c.get("url", ""), title=c.get("title", "untitled"))
for c in citations or []
]
message = ChatCompletionMessage.model_construct(
@@ -121,35 +113,98 @@ class TestExtractResults:
OpenRouter surfaces here first. Same extractor serves both tiers
because OpenRouter normalises annotations across models."""
- def test_extracts_title_url_and_content_snippet(self):
+ def test_extracts_number_title_and_url(self):
resp = _fake_response(
citations=[
- {
- "title": "Kimi K2.6 launch",
- "url": "https://example.com/kimi",
- "content": "Moonshot released K2.6 on 2026-04-20.",
- },
+ {"title": "Kimi K2.6 launch", "url": "https://example.com/kimi"},
{
"title": "OpenRouter pricing",
"url": "https://openrouter.ai/moonshotai/kimi-k2.6",
},
- ]
+ ],
+ answer="K2.6 launched on 2026-04-20.[1] Pricing is listed.[2]",
)
out = _extract_results(resp, limit=10)
- assert len(out) == 2
- assert out[0].title == "Kimi K2.6 launch"
- assert out[0].url == "https://example.com/kimi"
- assert out[0].snippet.startswith("Moonshot released")
- # Missing ``content`` extension → empty snippet rather than crash.
- assert out[1].snippet == ""
-
- def test_limit_caps_returned_results(self):
+ assert [r.model_dump() for r in out] == [
+ {"n": 1, "title": "Kimi K2.6 launch", "url": "https://example.com/kimi"},
+ {
+ "n": 2,
+ "title": "OpenRouter pricing",
+ "url": "https://openrouter.ai/moonshotai/kimi-k2.6",
+ },
+ ]
+
+ def test_answer_without_markers_returns_first_limit_sources(self):
resp = _fake_response(
citations=[{"title": f"r{i}", "url": f"https://e/{i}"} for i in range(10)]
)
out = _extract_results(resp, limit=3)
- assert len(out) == 3
- assert [r.title for r in out] == ["r0", "r1", "r2"]
+ assert [(r.n, r.title) for r in out] == [(1, "r0"), (2, "r1"), (3, "r2")]
+
+ def test_cited_sources_with_gaps_are_padded_to_limit(self):
+ resp = _fake_response(
+ citations=[
+ {"title": f"r{i}", "url": f"https://e/{i}"} for i in range(1, 25)
+ ],
+ answer="The rate is 3.75%.[10][20]",
+ )
+ out = _extract_results(resp, limit=5)
+ assert [r.n for r in out] == [1, 2, 3, 10, 20]
+ assert {r.n: r.url for r in out}[20] == "https://e/20"
+
+ def test_cited_sources_are_not_cut_to_limit(self):
+ resp = _fake_response(
+ citations=[
+ {"title": f"r{i}", "url": f"https://e/{i}"} for i in range(1, 25)
+ ],
+ answer="".join(f"Fact.[{n}] " for n in (2, 4, 7, 9, 13, 15, 21)),
+ )
+ out = _extract_results(resp, limit=1)
+ assert [r.n for r in out] == [2, 4, 7, 9, 13, 15, 21]
+
+ def test_markers_with_no_annotation_are_dropped(self):
+ resp = _fake_response(
+ citations=[
+ {"title": f"r{i}", "url": f"https://e/{i}"} for i in range(1, 4)
+ ],
+ answer="Known.[2] Unknown.[9] Not a source.[0]",
+ )
+ out = _extract_results(resp, limit=1)
+ assert [r.n for r in out] == [2]
+
+ def test_duplicate_urls_keep_each_cited_number(self):
+ resp = _fake_response(
+ citations=[
+ {"title": "Page", "url": "https://e/same"},
+ {"title": "Other", "url": "https://e/other"},
+ {"title": "Page again", "url": "https://e/same"},
+ ],
+ answer="One.[1] Two.[3]",
+ )
+ out = _extract_results(resp, limit=1)
+ assert [(r.n, r.url) for r in out] == [
+ (1, "https://e/same"),
+ (3, "https://e/same"),
+ ]
+
+ def test_repeated_markers_return_one_entry_per_number(self):
+ resp = _fake_response(
+ citations=[
+ {"title": f"r{i}", "url": f"https://e/{i}"} for i in range(1, 4)
+ ],
+ answer="A.[2] B.[2][2] C.[3]",
+ )
+ assert [r.n for r in _extract_results(resp, limit=1)] == [2, 3]
+
+ def test_more_than_twenty_cited_sources_are_capped_at_twenty(self):
+ resp = _fake_response(
+ citations=[
+ {"title": f"r{i}", "url": f"https://e/{i}"} for i in range(1, 31)
+ ],
+ answer="".join(f"Fact.[{n}] " for n in range(1, 31)),
+ )
+ out = _extract_results(resp, limit=5)
+ assert [r.n for r in out] == list(range(1, 21))
def test_missing_choices_returns_empty(self):
resp = ChatCompletion.model_construct(
@@ -182,14 +237,81 @@ class TestExtractResults:
)
assert _extract_answer(resp) == ""
- def test_snippet_clamped_to_max_chars(self):
- long_body = "x" * 5000
- resp = _fake_response(
- citations=[{"title": "t", "url": "https://e", "content": long_body}]
+
+_SONAR_FIXTURES = json.loads(
+ (Path(__file__).parent / "testdata" / "web_search_sonar_responses.json").read_text()
+)
+
+
+def _recorded_response(name: str) -> ChatCompletion:
+ """A real ``perplexity/sonar`` response recorded through OpenRouter."""
+ return ChatCompletion.model_validate(_SONAR_FIXTURES[name])
+
+
+def _cited_numbers(answer: str) -> set[int]:
+ return {int(n) for n in re.findall(r"\[(\d+)\]", answer)}
+
+
+class TestCitedSources:
+ """Sonar's answer cites its sources as ``[n]`` markers that index
+ the annotation list (annotation i is ``[i+1]``). Every number the
+ answer cites must come back with that number, or the caller cannot
+ say where a claim came from."""
+
+ @pytest.mark.asyncio
+ async def test_max_results_pads_the_cited_sources_up_to_it(self, monkeypatch):
+ sources = [
+ {"title": f"Source {i}", "url": f"https://news.example.com/story-{i}"}
+ for i in range(1, 13)
+ ]
+ dispatch = TestWebSearchToolDispatch()
+ mock_client = dispatch._mock_client(
+ _fake_response(citations=sources, answer="A.[11] B.[12]")
)
- out = _extract_results(resp, limit=1)
- assert len(out) == 1
- assert len(out[0].snippet) == 500
+ monkeypatch.setattr(
+ "backend.copilot.tools.web_search._chat_config",
+ type(
+ "C",
+ (),
+ {"api_key": "sk-test", "base_url": "https://openrouter.ai/api/v1"},
+ )(),
+ )
+ with (
+ patch(
+ "backend.copilot.tools.web_search.AsyncOpenAI",
+ return_value=mock_client,
+ ),
+ patch(
+ "backend.copilot.tools.web_search.persist_and_record_usage",
+ new=AsyncMock(return_value=160),
+ ),
+ ):
+ result = await WebSearchTool()._execute(
+ user_id="u1",
+ session=dispatch._session(),
+ query="twelve sources",
+ max_results=4,
+ )
+
+ assert isinstance(result, WebSearchResponse)
+ assert [r.n for r in result.results] == [1, 2, 11, 12]
+
+ @pytest.mark.parametrize("name", ["jwst_news", "central_bank_rates"])
+ def test_recorded_sonar_response_every_cited_number_resolves(self, name):
+ resp = _recorded_response(name)
+ annotations = resp.choices[0].message.annotations or []
+ cited = _cited_numbers(_extract_answer(resp))
+ assert cited, "fixture answer should cite sources"
+
+ by_n = {r.n: r for r in _extract_results(resp, limit=5)}
+ assert cited <= set(by_n)
+ for n in cited:
+ assert by_n[n].url == annotations[n - 1].url_citation.url
+ assert by_n[n].title == annotations[n - 1].url_citation.title
+
+ def test_description_and_result_promise_no_snippet(self):
+ assert "snippet" not in WebSearchTool().description
+ assert "snippet" not in WebSearchResult.model_fields
class TestExtractCostUsd:
@@ -257,13 +379,7 @@ class TestWebSearchToolDispatch:
@pytest.mark.asyncio
async def test_quick_path_uses_sonar_base(self, monkeypatch):
fake_resp = _fake_response(
- citations=[
- {
- "title": "hello",
- "url": "https://example.com",
- "content": "greeting",
- }
- ],
+ citations=[{"title": "hello", "url": "https://example.com"}],
answer="Kimi K2.6 launched 2026-04-20 [1].",
cost=0.01,
)
@@ -303,7 +419,11 @@ class TestWebSearchToolDispatch:
assert isinstance(result, WebSearchResponse)
assert result.answer == "Kimi K2.6 launched 2026-04-20 [1]."
assert len(result.results) == 1
- assert result.results[0].snippet == "greeting"
+ assert result.results[0].model_dump() == {
+ "n": 1,
+ "title": "hello",
+ "url": "https://example.com",
+ }
create_call = mock_client.chat.completions.create.call_args
assert create_call.kwargs["model"] == "perplexity/sonar"
@@ -318,13 +438,7 @@ class TestWebSearchToolDispatch:
@pytest.mark.asyncio
async def test_deep_path_uses_sonar_deep_research(self, monkeypatch):
fake_resp = _fake_response(
- citations=[
- {
- "title": "deep find",
- "url": "https://example.com/deep",
- "content": "research body",
- }
- ],
+ citations=[{"title": "deep find", "url": "https://example.com/deep"}],
cost=0.087,
)
mock_client = self._mock_client(fake_resp)
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResultViews.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResultViews.tsx
index 527c94a0fb..b7a818baa7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResultViews.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResultViews.tsx
@@ -93,11 +93,17 @@ export function SearchResults({ items, answer }: SearchResultsProps) {
const url = str(item, "url", "link");
const domain = url ? safeHostname(url) : null;
const title = str(item, "title", "snippet") ?? inline(item);
+ const citation = typeof item.n === "number" ? item.n : null;
return (
<div
- key={resultItemKey(item, i)}
+ key={citation === null ? resultItemKey(item, i) : `n:${citation}`}
className="flex items-center gap-2.5 px-3 py-2"
>
+ {citation !== null && (
+ <span className="shrink-0 text-xs tabular-nums text-zinc-600">
+ [{citation}]
+ </span>
+ )}
<ResultFavicon domain={domain} />
{url ? (
<a
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResultViews.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResultViews.test.tsx
index 9a512888df..949831a017 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResultViews.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolResultViews.test.tsx
@@ -1,5 +1,5 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { ChainRow } from "../helpers";
import {
FileCard,
@@ -38,6 +38,31 @@ describe("SearchResults", () => {
expect(screen.getByText("en.wikipedia.org")).toBeDefined();
});
+ it("labels each cited source with its [n] number, even when URLs repeat", () => {
+ const consoleError = vi.spyOn(console, "error");
+ render(
+ <SearchResults
+ items={[
+ { n: 3, title: "First cite", url: "https://example.com/a" },
+ { n: 12, title: "Same page again", url: "https://example.com/a" },
+ { title: "Stored before numbering", url: "https://example.com/old" },
+ ]}
+ answer="Claim.[3] Another claim.[12]"
+ />,
+ );
+
+ expect(screen.getByText("[3]")).toBeDefined();
+ expect(screen.getByText("[12]")).toBeDefined();
+ expect(screen.getAllByText(/^\[\d+\]$/)).toHaveLength(2);
+ expect(
+ screen
+ .getByRole("link", { name: "Same page again" })
+ .getAttribute("href"),
+ ).toBe("https://example.com/a");
+ expect(consoleError).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
it("renders unlinked results as plain text", () => {
render(<SearchResults items={[{ snippet: "Loose snippet" }]} />);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/GenericTool.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/GenericTool.tsx
index b884192d3a..669a9907c0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/GenericTool.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/GenericTool.tsx
@@ -323,8 +323,14 @@ function getWebAccordionData(
const href = getStringField(r, "url") ?? "";
const snippet = getStringField(r, "snippet");
const pageAge = getStringField(r, "page_age");
+ const citation = typeof r.n === "number" ? r.n : null;
return (
<div key={i} className="text-sm">
+ {citation !== null && (
+ <span className="mr-1.5 text-xs tabular-nums text-slate-500">
+ [{citation}]
+ </span>
+ )}
{href ? (
<a
href={href}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/__tests__/GenericTool.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/__tests__/GenericTool.test.tsx
index 8543d5b581..81b0b577f8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/__tests__/GenericTool.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/GenericTool/__tests__/GenericTool.test.tsx
@@ -197,6 +197,39 @@ describe("GenericTool", () => {
expect(secondLink.getAttribute("href")).toBe("https://example.com/two");
});
+ it("labels each cited source with its [n] and still renders older results without one", () => {
+ render(
+ <GenericTool
+ part={makeWebSearchPart([
+ {
+ n: 3,
+ title: "Cited source",
+ url: "https://example.com/cited",
+ },
+ {
+ title: "Legacy result",
+ url: "https://example.com/legacy",
+ snippet: "Legacy snippet",
+ page_age: "1 week ago",
+ },
+ ])}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { expanded: false }));
+
+ const citedRow = screen.getByRole("link", {
+ name: "Cited source",
+ }).parentElement as HTMLElement;
+ expect(citedRow.textContent).toMatch(/^\[3\]Cited source/);
+
+ const legacyRow = screen.getByRole("link", {
+ name: "Legacy result",
+ }).parentElement as HTMLElement;
+ expect(legacyRow.textContent).not.toMatch(/\[\d+\]/);
+ expect(screen.queryByText("Legacy snippet")).not.toBeNull();
+ expect(screen.queryByText("1 week ago")).not.toBeNull();
+ });
+
it("uses singular 'search result' when there is exactly one result", () => {
render(
<GenericTool