Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(vibey): count Gemini searches from their calls and cite the grounded answer (#3040)
Call Whitec1edf77dc716
diff --git a/core/agent_core/ai/google.py b/core/agent_core/ai/google.pyindex 9ed9dff17..41700aa3c 100644--- a/core/agent_core/ai/google.py+++ b/core/agent_core/ai/google.py@@ -19,6 +19,7 @@ import httpxfrom core.agent_core.ai.hosted import (GOOGLE_SEARCH_TOOL_TYPE,+ google_grounding_citations,google_grounding_sources,google_hosted_block,google_search_count,@@ -111,7 +112,11 @@ _GOOGLE_WIRE_SHAPES = {WireField("groundingMetadata",Mapping,- children=(WireField("webSearchQueries", list), WireField("groundingChunks", list)),+ children=(+ WireField("webSearchQueries", list),+ WireField("groundingChunks", list),+ WireField("groundingSupports", list),+ ),),WireField("content",@@ -256,6 +261,8 @@ class _GoogleStream:# Each Google Search by its call id: its slot and its toolCall part, until its toolResponse arrives.self._searches: dict[str, tuple[tuple[str, str], dict[str, Any]]] = {}self._grounding: Mapping[str, Any] | None = None+ # Each answer text block's text as streamed, by its slot, for the grounding Gemini reports at the finish.+ self._texts: dict[tuple[str, int], list[str]] = {}self.ended = Falseself._finish: str | None = Noneself._finish_message: str | None = None@@ -352,7 +359,9 @@ class _GoogleStream:self.assembler.set_thinking_signature(key, signature)return eventsif text:- emitted = self.assembler.text_delta(self._key("text"), text)+ key = self._key("text")+ self._texts.setdefault(key, []).append(text)+ emitted = self.assembler.text_delta(key, text)if emitted is not None:events.append(emitted)if signature:@@ -398,13 +407,15 @@ class _GoogleStream:)def _ground(self) -> None:- """Gemini reports a response's searches and sources once: they count its calls and fill its last record."""-- if not self._searches or self._grounding is None:+ """A response's searches are counted from its own calls. Gemini reports the sources once, with the answer they+ ground, which is often a later response of the turn: they cite its text, and fill this response's last search+ record when it ran one."""++ if self._searches:+ calls = [part for _, part in self._searches.values()]+ self.assembler.set_hosted_facts(counts={"web_search_requests": google_search_count(calls)})+ if self._grounding is None or "web_search" not in self.hosted:return- searches = google_search_count(self._grounding)- if searches:- self.assembler.set_hosted_facts(counts={"web_search_requests": searches})sources = google_grounding_sources(self._grounding)completed = [(key, block) for key, _ in self._searches.values()@@ -413,6 +424,30 @@ class _GoogleStream:if sources and completed:key, block = completed[-1]self.assembler.hosted_block(key, replace(block, record=replace(block.record, sources=sources)))+ self._cite()++ def _cite(self) -> None:+ """Each grounding support as citations on the answer text it grounds: at its range where that text is found+ (in order, after the end of the last one found, so a repeated sentence cites each occurrence), else once per+ source on the last text block."""++ texts = [(key, "".join(parts)) for key, parts in self._texts.items()]+ if not texts:+ return+ position = (0, 0)+ loose: set[str] = set()+ for segment, citations in google_grounding_citations(self._grounding):+ found = _find_segment([text for _, text in texts], segment, position) if segment else None+ if found is not None and segment:+ index, start = found+ position = (index, start + len(segment))+ for item in citations:+ self.assembler.add_text_citation(texts[index][0], replace(item, start=start, end=start + len(segment)))+ continue+ for item in citations:+ if item.url not in loose:+ loose.add(item.url)+ self.assembler.add_text_citation(texts[-1][0], item)def finish(self) -> list[Any]:if self._finish is None and self._blocked is None:@@ -432,6 +467,21 @@ class _GoogleStream:return events+def _find_segment(texts: list[str], segment: str, position: tuple[int, int]) -> tuple[int, int] | None:+ """Where ``segment`` first occurs in the texts at or after ``position`` (block, offset), else anywhere."""++ block, offset = position+ for index in range(block, len(texts)):+ start = texts[index].find(segment, offset if index == block else 0)+ if start >= 0:+ return index, start+ for index, text in enumerate(texts):+ start = text.find(segment)+ if start >= 0:+ return index, start+ return None++def build_google_payload(request: ModelRequest,messages: tuple[Any, ...],diff --git a/core/agent_core/ai/hosted.py b/core/agent_core/ai/hosted.pyindex 1041e5db8..63bfd6978 100644--- a/core/agent_core/ai/hosted.py+++ b/core/agent_core/ai/hosted.py@@ -286,13 +286,48 @@ def google_grounding_sources(metadata: Any) -> tuple[HostedSource, ...]:return tuple(sources.values())-def google_search_count(metadata: Any) -> int:- """The searches Google bills a Gemini response for: its distinct, non-empty ``webSearchQueries``."""+def google_search_count(calls: Iterable[Mapping[str, Any]]) -> int:+ """The searches Google bills a Gemini response for: the distinct queries each of its search ``toolCall`` parts+ ran, at least one per call.- queries = metadata.get("webSearchQueries") if isinstance(metadata, Mapping) else None- return len({query.strip() for query in queries if isinstance(query, str) and query.strip()}) if isinstance(- queries, list- ) else 0+ The response that ran them says so; ``groundingMetadata.webSearchQueries`` comes with the grounded answer, often+ a later response of the turn, and lists only the queries that grounded it (measured 2026-10-27).+ """++ count = 0+ for part in calls:+ call = part.get("toolCall") if isinstance(part, Mapping) else None+ raw = call.get("args", {}).get("queries") if isinstance(call, Mapping) and isinstance(call.get("args"), Mapping) else None+ queries = {query.strip() for query in raw if isinstance(query, str) and query.strip()} if isinstance(raw, list) else set()+ count += max(1, len(queries))+ return count+++def google_grounding_citations(metadata: Any) -> list[tuple[Optional[str], tuple[Citation, ...]]]:+ """Each ``groundingSupports`` entry of a Gemini answer: the text it grounds (``segment.text``, or None) and a+ citation, without a range, for every web chunk it names."""++ if not isinstance(metadata, Mapping):+ return []+ chunks = metadata.get("groundingChunks") if isinstance(metadata.get("groundingChunks"), list) else []+ supports = metadata.get("groundingSupports") if isinstance(metadata.get("groundingSupports"), list) else []+ cited = []+ for support in supports:+ if not isinstance(support, Mapping) or not isinstance(support.get("groundingChunkIndices"), list):+ continue+ segment = support.get("segment")+ text = _text(segment.get("text")) if isinstance(segment, Mapping) else None+ items = []+ for number in support["groundingChunkIndices"]:+ if isinstance(number, bool) or not isinstance(number, int) or not 0 <= number < len(chunks):+ continue+ web = chunks[number].get("web") if isinstance(chunks[number], Mapping) else None+ url = _text(web.get("uri")) if isinstance(web, Mapping) else None+ if url is not None:+ items.append(Citation(url=url, title=_text(web.get("title"))))+ if items:+ cited.append((text, tuple(items)))+ return citeddef citation(raw: Mapping[str, Any], *, offset: int = 0) -> Optional[Citation]:diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex 74b54c813..704fdef22 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -674,7 +674,7 @@ Gemini stream events (each `data:` frame is a `GenerateContentResponse` whose pa| `…parts[].functionCall` | delta | `ToolCallStart` and one `ToolCallDelta` of the JSON `args`; `id` is the native id, `thoughtSignature` the call's signature. An empty name is terminal `invalid_request`. || `…parts[].toolCall` / `toolResponse` with `toolType: GOOGLE_SEARCH_WEB` | state | One `web_search` `HostedToolBlock` per call `id` (Hosted tools, below), only when the request declared it natively. || any other part | ignored | Parts of a kind the request did not declare (inline data, code execution, another server-side tool). |-| `candidates[0].groundingMetadata` | state | `webSearchQueries` and `groundingChunks` of the response, read at its finish (Hosted tools, below). |+| `candidates[0].groundingMetadata` | state | `groundingChunks` and `groundingSupports` of the answer they ground, read at the response's finish (Hosted tools, below). || `candidates[0].finishReason` | state | Stop reason (below). || `usageMetadata` | state | `input = promptTokenCount - cachedContentTokenCount`; `output = candidatesTokenCount + thoughtsTokenCount`; `cache_read = cachedContentTokenCount`; `reasoning = thoughtsTokenCount`. The last frame's counts win. || `promptFeedback.blockReason` without a finish | Done | `safety`, with the block reason as `error_message`. |@@ -749,9 +749,9 @@ Gemini (`google`, plan `../vibey-gemini-native.md` §4) runs `web_search` as Goo| --- | --- || Native declaration | `{"googleSearch": {}}` after the `functionDeclarations`, for the overlay's `{"type": "google_search"}`, plus `toolConfig.includeServerSideToolInvocations: true` || Proxy declaration | a `functionDeclarations` entry with the canonical schema |-| Native result → `HostedToolBlock` | a `toolCall` part (`toolType: GOOGLE_SEARCH_WEB`, `args.queries`) opens one `search` block by its `id`, `pending`; the `toolResponse` part with the same `id` completes it. Both parts, signatures included, are its `native.payload`. The `search_suggestions` markup in the response is never kept. |-| Response-level facts | at the finish, the distinct `groundingMetadata.webSearchQueries` are `counts.web_search_requests`, and the `groundingChunks` (`web.uri`, `web.title`, each URL once) are the sources of the response's last completed search |-| Citations | none yet: `groundingSupports` is not read |+| Native result → `HostedToolBlock` | a `toolCall` part (`toolType: GOOGLE_SEARCH_WEB`, `args.queries`) opens one `search` block by its `id`, `pending`; the `toolResponse` part with the same `id` completes it. Both parts, signatures included, are its `native.payload`; the `search_suggestions` markup the `toolResponse` carries stays only there, never shown. |+| Response-level facts | at the finish, the distinct `args.queries` of each search call (at least one per call) are `counts.web_search_requests`; when the response also carries `groundingMetadata`, its `groundingChunks` (`web.uri`, `web.title`, each URL once) are the sources of its last completed search |+| Citations | each `groundingSupports` entry of a response's `groundingMetadata` (which comes with the grounded answer, often the turn's response after the search): a citation per named `groundingChunks[].web` on the text block where its `segment.text` is next found (after the previous support's match, so a repeated sentence cites each occurrence), at that range, else once per URL on the last text block without a range; only on a request that declared Google Search || Same-Source replay | `native.payload` parts verbatim, in place in the `model` content || Other-origin replay | the portable synthetic call and result, as for the other protocols || Pinning, in-flight replay | as for the other protocols; the in-flight response is the last `model` content followed only by function responses |diff --git a/docs/plans/vibey-gemini-native.md b/docs/plans/vibey-gemini-native.mdindex d8d292f9f..8904059c0 100644--- a/docs/plans/vibey-gemini-native.md+++ b/docs/plans/vibey-gemini-native.md@@ -117,18 +117,24 @@ included (owner, 2026-10-27: "统一都走原生").- The adapter sends that declaration as `{"googleSearch": {}}` after the `functionDeclarations`, with`toolConfig.includeServerSideToolInvocations: true`, which Gemini requires to run it next to functions (measured).- A response's `toolCall`/`toolResponse` pair (`toolType: GOOGLE_SEARCH_WEB`) becomes one `HostedToolBlock`- (`action: search` with the call's `queries`; the record's sources are the response's `groundingChunks`, each- once), with both parts verbatim, signatures included, as its native payload. Same-Source replay sends them back- in place; any other target gets the synthetic call and result (`vibey-hosted-tools.md` §5). The- `search_suggestions` markup is never kept (§0). A server-side part of a tool the request did not declare stays- out of the transcript.+ (`action: search` with the call's `queries`), with both parts verbatim, signatures included, as its native+ payload. Same-Source replay sends them back in place; any other target gets the synthetic call and result+ (`vibey-hosted-tools.md` §5). The `toolResponse` carries Google's `search_suggestions` markup: it stays inside that+ opaque payload, which only goes back to the Source, and is never shown, rendered into a record or sent elsewhere+ (§0). A server-side part of a tool the request did not declare stays out of the transcript.+- Gemini reports a search's sources once, in `groundingMetadata`, on the response whose answer they ground. After a+ search and a function call that is the turn's next response, which ran no search (measured 2026-10-27). So each+ `groundingSupports` entry cites the answer text it grounds (`TextBlock.citations`: its `segment.text` found in the+ response's text, in order, gives the range; one not found cites each source once without one), on every surface through the+ shared citation builder. When the search and its answer are one response, the `groundingChunks` (each URL once)+ are also its last search record's sources. `searchEntryPoint` is not read.- Gateway: `hosted_admission` reads the keyed declaration through `request.declared_tool_types` and Gemini'sserver-side parts as replays (the in-flight response is the last `model` content followed only by functionresponses). Gemini's refusal "Tool call context circulation is not enabled" before output is the narrow negative- rule for `web_search` `call`, so the hop falls back to the executor chain. Cost: the response's distinct `groundingMetadata.webSearchQueries` × list price, as- `hosted_summary.counts.web_search_requests`.-- Not in this step: a positive evidence rule (the Tools tab shows no "最近一次 … 正常" for Google Search) and- answer citations from `groundingSupports` (the record lists the sources; the text carries no links).+ rule for `web_search` `call`, so the hop falls back to the executor chain. Cost: the distinct `args.queries` of each+ search call (at least one per call) × list price, as `hosted_summary.counts.web_search_requests` of the response+ that ran them; `webSearchQueries` lists only the queries that grounded the answer (measured: one of two).+- Not in this step: a positive evidence rule (the Tools tab shows no "最近一次 … 正常" for Google Search).- Public docs (`avibe-docs`, en and zh): Gemini searches with Google, queries go to Google, and the price.## 5. Delivery@@ -146,7 +152,8 @@ of each other once PR 1 is merged.- A Gemini subscription (Antigravity) is served by the engine over Chat only; it keeps Exa/Tavily search.- Source links in Google's grounding are redirect URLs; the card shows the domain as title.-- Google Search has no positive evidence yet and Gemini answers carry no inline citations (§4).+- Google Search has no positive evidence yet (§4).+- A search whose answer comes in a later response lists no sources on its own card; the answer cites them (§4).- Gemini is not a search executor for other hops: the executor speaks Anthropic and Responses only, so Gemini runsGoogle Search on its own hop and names no `executor_models` (a follow-up would add a `google` executor requestand result).diff --git a/tests/agent_core/ai/test_google_adapter.py b/tests/agent_core/ai/test_google_adapter.pyindex e78baf939..e0da0dd19 100644--- a/tests/agent_core/ai/test_google_adapter.py+++ b/tests/agent_core/ai/test_google_adapter.py@@ -16,6 +16,7 @@ from core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, Mofrom core.agent_core.cancel import CancelTokenfrom core.agent_core.messages import (AssistantMessage,+ Citation,HostedSource,HostedToolBlock,ImageBlock,@@ -332,14 +333,21 @@ RESPONSE_PART = {"toolResponse": {"toolType": "GOOGLE_SEARCH_WEB", "response": {"search_suggestions": "<div>chips</div>"}, "id": "srch_1"},"thoughtSignature": SIG_B,}+# Gemini lists only the queries that grounded the answer (measured: one of the call's two).GROUNDING = {- "webSearchQueries": ["btc price today", "btc close", "btc price today"],+ "webSearchQueries": ["btc price today"],"groundingChunks": [{"web": {"uri": "https://grounding.invalid/a", "title": "coindesk.com"}},{"web": {"uri": "https://grounding.invalid/b", "title": "coinbase.com"}},{"web": {"uri": "https://grounding.invalid/a", "title": "coindesk.com"}},],+ "groundingSupports": [+ {"segment": {"startIndex": 0, "endIndex": 21, "text": "BTC closed at $79,6xx"}, "groundingChunkIndices": [0, 1]},+ ],+ "searchEntryPoint": {"renderedContent": "<div>chips</div>"},}+A = "https://grounding.invalid/a"+B = "https://grounding.invalid/b"def _searching(*messages: Any) -> ModelRequest:@@ -396,8 +404,14 @@ async def test_a_google_search_is_one_hosted_call_whose_parts_go_back_verbatim()HostedSource(url="https://grounding.invalid/b", title="coinbase.com"),)assert search.native.source_id == SOURCE and search.native.payload == (CALL_PART, RESPONSE_PART)- # Google bills each distinct query the model ran.+ # Google bills each distinct query the call ran, not only those the grounding lists.assert message.hosted_summary is not None and message.hosted_summary.counts == {"web_search_requests": 2}+ # The grounded sentence cites its sources at its range; the Search Suggestions are not kept.+ [answer] = [block for block in message.content if isinstance(block, TextBlock)]+ assert answer.citations == (+ Citation(url=A, title="coindesk.com", start=0, end=21), Citation(url=B, title="coinbase.com", start=0, end=21),+ )+ assert "chips" not in json.dumps([str(block) for block in message.content if not isinstance(block, HostedToolBlock)])# Back to the same Source, the call's parts go verbatim, signatures included, before the answer.body = await _body(_searching(_user("btc?"), message, _user("and eth?")), gateway=True)@@ -414,5 +428,50 @@ async def test_a_google_search_is_one_hosted_call_whose_parts_go_back_verbatim()async def test_a_server_side_call_the_request_did_not_declare_stays_out_of_the_transcript() -> None:- message = _final(await _stream(_parts(CALL_PART), _parts(RESPONSE_PART), _parts({"text": "ok"}, finish="STOP")))- assert message.content == (TextBlock(text="ok"),) and message.hosted_summary is None+ grounded = {"candidates": [{"content": {"role": "model", "parts": []}, "groundingMetadata": GROUNDING}]}+ message = _final(await _stream(+ _parts(CALL_PART), _parts(RESPONSE_PART), _parts({"text": "BTC closed at $79,6xx."}, finish="STOP"), grounded,+ ))+ assert message.content == (TextBlock(text="BTC closed at $79,6xx."),) and message.hosted_summary is None+++async def test_the_answer_a_search_of_an_earlier_response_grounds_cites_it() -> None:+ """Gemini reports the sources with the answer they ground: after a search and a function call, that is the next+ response of the turn, which ran no search and so is not billed for one (measured 2026-10-27)."""++ grounding = {**GROUNDING, "groundingSupports": [+ *GROUNDING["groundingSupports"],+ # A support whose text is not in the answer as streamed cites its source once, without a range.+ {"segment": {"text": "not in the answer"}, "groundingChunkIndices": [1, 7]},+ {"segment": {"text": "also elsewhere"}, "groundingChunkIndices": [1]},+ ]}+ finish = {"candidates": [{"content": {"role": "model", "parts": [{"text": "."}]}, "finishReason": "STOP",+ "groundingMetadata": grounding}]}+ events = await _stream(_parts({"text": "Checked: "}), _parts({"text": "BTC closed at $79,6xx"}), finish,+ request=_searching(_user("btc?")))+ message = _final(events)++ assert message.hosted_summary is None+ assert not [block for block in message.content if isinstance(block, HostedToolBlock)]+ [answer] = message.content+ assert answer == TextBlock(text="Checked: BTC closed at $79,6xx.", citations=(+ Citation(url=A, title="coindesk.com", start=9, end=30), Citation(url=B, title="coinbase.com", start=9, end=30),+ Citation(url=B, title="coinbase.com"),+ ))+++async def test_supports_of_a_repeated_sentence_cite_each_occurrence_in_order() -> None:+ grounding = {+ "groundingChunks": [{"web": {"uri": A, "title": "a.example"}}, {"web": {"uri": B, "title": "b.example"}}],+ "groundingSupports": [+ {"segment": {"text": "No change."}, "groundingChunkIndices": [0]},+ {"segment": {"text": "No change."}, "groundingChunkIndices": [1]},+ ],+ }+ finish = {"candidates": [{"content": {"role": "model", "parts": [{"text": "Alpha: No change. Beta: No change."}]},+ "finishReason": "STOP", "groundingMetadata": grounding}]}+ [answer] = _final(await _stream(finish, request=_searching(_user("status?")))).content++ assert answer.citations == (+ Citation(url=A, title="a.example", start=7, end=17), Citation(url=B, title="b.example", start=24, end=34),+ )