Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: preserve Gemini thought_signature across AgentLoop dict-history replay

mvanhorn4ac49e8582c7
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index a016ba052..0272730d5 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import copy
import json
import logging
from datetime import datetime
@@ -292,21 +293,32 @@ class ContextBuilder:
Returns:
OpenAI-format assistant message.
"""
+ formatted_tool_calls = []
+ has_extra_content = False
+ for tc in tool_calls:
+ tool_call = {
+ "id": tc.id,
+ "type": "function",
+ "function": {
+ "name": tc.name,
+ "arguments": json.dumps(tc.arguments, ensure_ascii=False),
+ },
+ }
+ extra_content = getattr(tc, "extra_content", None)
+ if extra_content:
+ tool_call["extra_content"] = dict(extra_content)
+ has_extra_content = True
+ formatted_tool_calls.append(tool_call)
+
message = {
"role": "assistant",
"content": content,
- "tool_calls": [
- {
- "id": tc.id,
- "type": "function",
- "function": {
- "name": tc.name,
- "arguments": json.dumps(tc.arguments, ensure_ascii=False),
- },
- }
- for tc in tool_calls
- ],
+ "tool_calls": formatted_tool_calls,
}
+ if has_extra_content:
+ message["additional_kwargs"] = {
+ "tool_calls": copy.deepcopy(formatted_tool_calls),
+ }
if reasoning_content is not None:
message["reasoning_content"] = reasoning_content
return message
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 626722c16..f0ba2cec8 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -14,6 +14,7 @@ Tool execution:
from __future__ import annotations
import concurrent.futures
+import copy
import json
import logging
import os
@@ -290,36 +291,73 @@ def _fix_tool_pairs(messages: list) -> None:
messages.insert(pos, stub)
-def _attach_tool_call_thought_signatures(message: dict[str, Any], tool_calls: list) -> None:
- """Attach Gemini thought signatures to replayed assistant tool calls."""
+def _attach_tool_call_thought_signatures(message: dict[str, Any], tool_calls: list) -> dict[str, Any]:
+ """Attach Gemini thought signatures to assistant replay tool calls.
+
+ The replay message is later converted back into LangChain messages from a
+ plain dict history. Keep signatures in both the provider-neutral
+ ``extra_content.thought_signature`` slot and Gemini's OpenAI-compatible
+ ``extra_content.google.thought_signature`` slot so both local replay tests
+ and the Gemini request injector can recover the value.
+ """
outbound_tool_calls = message.get("tool_calls")
if not isinstance(outbound_tool_calls, list):
- return
-
- signatures_by_id = {
- tc.id: tc.thought_signature
- for tc in tool_calls
- if getattr(tc, "thought_signature", None)
- }
- for index, outbound_tool_call in enumerate(outbound_tool_calls):
- if not isinstance(outbound_tool_call, dict):
- continue
- signature = signatures_by_id.get(outbound_tool_call.get("id"))
- if not signature and index < len(tool_calls):
- signature = getattr(tool_calls[index], "thought_signature", None)
+ return message
+
+ signatures_by_id: dict[str, str] = {}
+ signatures_by_index: dict[int, str] = {}
+ for index, tc in enumerate(tool_calls):
+ extra_content = getattr(tc, "extra_content", None)
+ signature = None
+ if isinstance(extra_content, dict):
+ signature = extra_content.get("thought_signature")
+ google_extra = extra_content.get("google")
+ if not signature and isinstance(google_extra, dict):
+ signature = google_extra.get("thought_signature") or google_extra.get(
+ "thoughtSignature"
+ )
+ signature = signature or getattr(tc, "thought_signature", None)
if not signature:
continue
-
- extra_content = outbound_tool_call.get("extra_content")
+ tc_id = getattr(tc, "id", None)
+ if tc_id:
+ signatures_by_id[str(tc_id)] = signature
+ signatures_by_index[index] = signature
+
+ if not signatures_by_id and not signatures_by_index:
+ return message
+
+ def attach(raw_tool_call: Any, index: int) -> None:
+ if not isinstance(raw_tool_call, dict):
+ return
+ signature = signatures_by_id.get(str(raw_tool_call.get("id"))) or signatures_by_index.get(index)
+ if not signature:
+ return
+ extra_content = raw_tool_call.setdefault("extra_content", {})
if not isinstance(extra_content, dict):
extra_content = {}
- outbound_tool_call["extra_content"] = extra_content
- google = extra_content.get("google")
+ raw_tool_call["extra_content"] = extra_content
+ extra_content["thought_signature"] = signature
+ google = extra_content.setdefault("google", {})
if not isinstance(google, dict):
google = {}
extra_content["google"] = google
google["thought_signature"] = signature
+ for index, raw_tool_call in enumerate(outbound_tool_calls):
+ attach(raw_tool_call, index)
+
+ additional_kwargs = message.setdefault("additional_kwargs", {})
+ raw_tool_calls = additional_kwargs.setdefault(
+ "tool_calls",
+ copy.deepcopy(outbound_tool_calls),
+ )
+ if isinstance(raw_tool_calls, list):
+ for index, raw_tool_call in enumerate(raw_tool_calls):
+ attach(raw_tool_call, index)
+
+ return message
+
# -- Structured summary templates ------------------------------------------
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.py
index da90fb5be..276d6b116 100644
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@ -36,12 +36,15 @@ class ToolCallRequest:
name: Tool name.
arguments: Tool argument dict.
thought_signature: Gemini thinking-model signature to echo on the next turn.
+ extra_content: Provider-specific tool-call metadata that must be
+ replayed with the assistant turn, such as Gemini thought signatures.
"""
id: str
name: str
arguments: Dict[str, Any]
thought_signature: Optional[str] = None
+ extra_content: Dict[str, Any] = field(default_factory=dict)
@dataclass
@@ -355,19 +358,37 @@ class ChatLLM:
usage = dict(usage)
except (TypeError, ValueError):
usage = None
+ additional_kwargs = getattr(ai_message, "additional_kwargs", {}) or {}
thought_signatures_by_id, thought_signatures_by_index = (
ChatLLM._tool_call_thought_signature_maps(ai_message)
)
- native_tool_calls = [
- ToolCallRequest(
- id=tc["id"],
- name=tc["name"],
- arguments=tc["args"],
- thought_signature=thought_signatures_by_id.get(str(tc["id"]))
- or thought_signatures_by_index.get(index),
+ raw_tool_calls = additional_kwargs.get("tool_calls") or []
+ raw_by_id = {
+ raw.get("id"): raw
+ for raw in raw_tool_calls
+ if isinstance(raw, dict) and raw.get("id")
+ }
+
+ native_tool_calls: list[ToolCallRequest] = []
+ for index, tc in enumerate(ai_message.tool_calls):
+ extra_content = _merge_tool_call_extra_content(tc, raw_by_id.get(tc["id"]))
+ signature = (
+ thought_signatures_by_id.get(str(tc["id"]))
+ or thought_signatures_by_index.get(index)
+ or extra_content.get("thought_signature")
)
- for index, tc in enumerate(ai_message.tool_calls)
- ]
+ if signature:
+ extra_content.setdefault("thought_signature", signature)
+ native_tool_calls.append(
+ ToolCallRequest(
+ id=tc["id"],
+ name=tc["name"],
+ arguments=tc["args"],
+ thought_signature=signature,
+ extra_content=extra_content,
+ )
+ )
+
dsml_tool_calls = [] if native_tool_calls else _parse_dsml_tool_calls(ai_message.content)
tool_calls = native_tool_calls or dsml_tool_calls
@@ -385,8 +406,47 @@ class ChatLLM:
return LLMResponse(
content="" if dsml_tool_calls else ai_message.content,
tool_calls=tool_calls,
- reasoning_content=ai_message.additional_kwargs.get("reasoning_content"),
+ reasoning_content=additional_kwargs.get("reasoning_content"),
finish_reason=finish_reason,
usage_metadata=usage,
content_filter_triggered=content_filter_triggered,
)
+
+
+def _extract_tool_call_extra_content(raw_tool_call: Any) -> Dict[str, Any]:
+ """Extract provider-specific tool-call metadata LangChain would drop."""
+ if not isinstance(raw_tool_call, dict):
+ return {}
+
+ extra_content: Dict[str, Any] = {}
+ raw_extra = raw_tool_call.get("extra_content")
+ if isinstance(raw_extra, dict):
+ extra_content.update(raw_extra)
+ google_extra = raw_extra.get("google")
+ if isinstance(google_extra, dict):
+ signature = google_extra.get("thought_signature") or google_extra.get(
+ "thoughtSignature"
+ )
+ if signature:
+ extra_content["thought_signature"] = signature
+
+ function = raw_tool_call.get("function")
+ if isinstance(function, dict):
+ function_extra = function.get("extra_content")
+ if isinstance(function_extra, dict):
+ extra_content.update(function_extra)
+ if function.get("thought_signature"):
+ extra_content["thought_signature"] = function["thought_signature"]
+
+ if raw_tool_call.get("thought_signature"):
+ extra_content["thought_signature"] = raw_tool_call["thought_signature"]
+
+ return extra_content
+
+
+def _merge_tool_call_extra_content(*raw_tool_calls: Any) -> Dict[str, Any]:
+ """Merge provider metadata from standardized and raw tool-call shapes."""
+ extra_content: Dict[str, Any] = {}
+ for raw_tool_call in raw_tool_calls:
+ extra_content.update(_extract_tool_call_extra_content(raw_tool_call))
+ return extra_content
diff --git a/agent/tests/test_agent_loop_thought_signature.py b/agent/tests/test_agent_loop_thought_signature.py
new file mode 100644
index 000000000..91631f8f8
--- /dev/null
+++ b/agent/tests/test_agent_loop_thought_signature.py
@@ -0,0 +1,143 @@
+"""Regression coverage for Gemini thought_signature replay in AgentLoop history."""
+
+from __future__ import annotations
+
+import json
+
+from langchain_core.messages import AIMessage, convert_to_messages
+
+from src.agent.context import ContextBuilder
+from src.agent.loop import _attach_tool_call_thought_signatures
+from src.providers.chat import ChatLLM, ToolCallRequest
+
+
+def _raw_tool_call(
+ call_id: str,
+ name: str,
+ arguments: dict,
+ thought_signature: str | None = None,
+) -> dict:
+ raw = {
+ "id": call_id,
+ "type": "function",
+ "function": {
+ "name": name,
+ "arguments": json.dumps(arguments),
+ },
+ }
+ if thought_signature:
+ raw["extra_content"] = {"thought_signature": thought_signature}
+ return raw
+
+
+def test_dict_history_replay_preserves_thought_signature() -> None:
+ message = ContextBuilder.format_assistant_tool_calls(
+ [
+ ToolCallRequest(
+ id="tc_1",
+ name="get_price",
+ arguments={"symbol": "AAPL"},
+ extra_content={"thought_signature": "sig-iteration-1"},
+ )
+ ],
+ content="",
+ )
+
+ replayed = convert_to_messages([message])[0]
+ raw_tool_call = replayed.additional_kwargs["tool_calls"][0]
+
+ assert message["tool_calls"][0]["extra_content"]["thought_signature"] == "sig-iteration-1"
+ assert raw_tool_call["extra_content"]["thought_signature"] == "sig-iteration-1"
+
+
+def test_multiple_tool_calls_keep_their_own_signatures() -> None:
+ message = ContextBuilder.format_assistant_tool_calls(
+ [
+ ToolCallRequest(
+ id="tc_signed_1",
+ name="get_price",
+ arguments={"symbol": "AAPL"},
+ extra_content={"thought_signature": "sig-a"},
+ ),
+ ToolCallRequest(
+ id="tc_unsigned",
+ name="get_news",
+ arguments={"symbol": "MSFT"},
+ ),
+ ToolCallRequest(
+ id="tc_signed_2",
+ name="get_fundamentals",
+ arguments={"symbol": "GOOG"},
+ extra_content={"thought_signature": "sig-g"},
+ ),
+ ],
+ content="",
+ )
+
+ raw_tool_calls = message["additional_kwargs"]["tool_calls"]
+
+ assert raw_tool_calls[0]["extra_content"]["thought_signature"] == "sig-a"
+ assert "extra_content" not in raw_tool_calls[1]
+ assert raw_tool_calls[2]["extra_content"]["thought_signature"] == "sig-g"
+
+
+def test_in_memory_ai_message_path_preserves_thought_signature() -> None:
+ ai_message = AIMessage(
+ content="",
+ tool_calls=[
+ {"id": "tc_1", "name": "get_price", "args": {"symbol": "AAPL"}},
+ ],
+ additional_kwargs={
+ "tool_calls": [
+ _raw_tool_call(
+ "tc_1",
+ "get_price",
+ {"symbol": "AAPL"},
+ thought_signature="sig-from-ai-message",
+ )
+ ]
+ },
+ )
+
+ response = ChatLLM._parse_response(ai_message)
+ replay = ContextBuilder.format_assistant_tool_calls(response.tool_calls, content="")
+
+ assert response.tool_calls[0].extra_content["thought_signature"] == "sig-from-ai-message"
+ assert replay["additional_kwargs"]["tool_calls"][0]["extra_content"]["thought_signature"] == \
+ "sig-from-ai-message"
+
+
+def test_loop_helper_attaches_thought_signature_to_dict_history() -> None:
+ message = {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ _raw_tool_call("tc_1", "get_price", {"symbol": "AAPL"}),
+ _raw_tool_call("tc_2", "get_news", {"symbol": "MSFT"}),
+ ],
+ }
+ tool_calls = [
+ ToolCallRequest(
+ id="tc_1",
+ name="get_price",
+ arguments={"symbol": "AAPL"},
+ extra_content={"thought_signature": "sig-only-first"},
+ ),
+ ToolCallRequest(id="tc_2", name="get_news", arguments={"symbol": "MSFT"}),
+ ]
+
+ attached = _attach_tool_call_thought_signatures(message, tool_calls)
+ raw_tool_calls = attached["additional_kwargs"]["tool_calls"]
+
+ assert raw_tool_calls[0]["extra_content"]["thought_signature"] == "sig-only-first"
+ assert "extra_content" not in raw_tool_calls[1]
+
+
+def test_unsigned_tool_calls_do_not_emit_signature_metadata() -> None:
+ message = ContextBuilder.format_assistant_tool_calls(
+ [ToolCallRequest(id="tc_1", name="get_price", arguments={"symbol": "AAPL"})],
+ content="",
+ )
+
+ assert "additional_kwargs" not in message
+ assert "extra_content" not in message["tool_calls"][0]