Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

feat: add gemini native thinking (#5124)

cthomas93d9ff01c6f3
diff --git a/letta/interfaces/gemini_streaming_interface.py b/letta/interfaces/gemini_streaming_interface.py
index fa270199b..052006612 100644
--- a/letta/interfaces/gemini_streaming_interface.py
+++ b/letta/interfaces/gemini_streaming_interface.py
@@ -182,20 +182,23 @@ class SimpleGeminiStreamingInterface:
# NOTE: the thought_signature comes on the Part with the function_call
thought_signature = part.thought_signature
self.thinking_signature = thought_signature
- # TODO: support reasoning
- # yield ReasoningMessage(
- # id=self.letta_message_id,
- # date=datetime.now(timezone.utc).isoformat(),
- # otid=Message.generate_otid_from_id(self.letta_message_id, message_index),
- # source="reasoner_model",
- # reasoning="",
- # signature=base64.b64encode(thought_signature).decode('utf-8'),
- # )
+ if prev_message_type and prev_message_type != "reasoning_message":
+ message_index += 1
+ yield ReasoningMessage(
+ id=self.letta_message_id,
+ date=datetime.now(timezone.utc).isoformat(),
+ otid=Message.generate_otid_from_id(self.letta_message_id, message_index),
+ source="reasoner_model",
+ reasoning="",
+ signature=base64.b64encode(thought_signature).decode("utf-8"),
+ )
+ prev_message_type = "reasoning_message"
# Thinking summary content part (bool means text is thought part)
if part.thought:
reasoning_summary = part.text
- self.thinking_summaries.append(reasoning_summary)
+ if prev_message_type and prev_message_type != "reasoning_message":
+ message_index += 1
yield ReasoningMessage(
id=self.letta_message_id,
date=datetime.now(timezone.utc).isoformat(),
@@ -205,6 +208,7 @@ class SimpleGeminiStreamingInterface:
run_id=self.run_id,
step_id=self.step_id,
)
+ prev_message_type = "reasoning_message"
self.content_parts.append(
ReasoningContent(
is_native=True,
@@ -217,6 +221,8 @@ class SimpleGeminiStreamingInterface:
elif part.text:
content = part.text
self.text_content = content if self.text_content is None else self.text_content + content
+ if prev_message_type and prev_message_type != "assistant_message":
+ message_index += 1
yield AssistantMessage(
id=self.letta_message_id,
otid=Message.generate_otid_from_id(self.letta_message_id, message_index),
@@ -225,6 +231,7 @@ class SimpleGeminiStreamingInterface:
run_id=self.run_id,
step_id=self.step_id,
)
+ prev_message_type = "assistant_message"
self.content_parts.append(
TextContent(
text=content,
@@ -247,6 +254,8 @@ class SimpleGeminiStreamingInterface:
self.tool_call_args = arguments
if self.tool_call_name and self.tool_call_name in self.requires_approval_tools:
+ if prev_message_type and prev_message_type != "approval_request_message":
+ message_index += 1
yield ApprovalRequestMessage(
id=self.letta_message_id,
otid=Message.generate_otid_from_id(self.letta_message_id, message_index),
@@ -259,7 +268,10 @@ class SimpleGeminiStreamingInterface:
run_id=self.run_id,
step_id=self.step_id,
)
+ prev_message_type = "approval_request_message"
else:
+ if prev_message_type and prev_message_type != "tool_call_message":
+ message_index += 1
yield ToolCallMessage(
id=self.letta_message_id,
otid=Message.generate_otid_from_id(self.letta_message_id, message_index),
@@ -272,6 +284,7 @@ class SimpleGeminiStreamingInterface:
run_id=self.run_id,
step_id=self.step_id,
)
+ prev_message_type = "tool_call_message"
self.content_parts.append(
ToolCallContent(
id=call_id,
diff --git a/letta/llm_api/google_vertex_client.py b/letta/llm_api/google_vertex_client.py
index 123d46ee8..687ac9373 100644
--- a/letta/llm_api/google_vertex_client.py
+++ b/letta/llm_api/google_vertex_client.py
@@ -1,3 +1,4 @@
+import base64
import json
import uuid
from typing import AsyncIterator, List, Optional
@@ -379,6 +380,7 @@ class GoogleVertexClient(LLMClientBase):
)
thinking_config = ThinkingConfig(
thinking_budget=(thinking_budget),
+ include_thoughts=(thinking_budget > 1),
)
request_data["config"]["thinking_config"] = thinking_config.model_dump()
@@ -440,13 +442,15 @@ class GoogleVertexClient(LLMClientBase):
# NOTE(Apr 9, 2025): there's a very strange bug on 2.5 where the response has a part with broken text
# {'candidates': [{'content': {'parts': [{'functionCall': {'name': 'send_message', 'args': {'request_heartbeat': False, 'message': 'Hello! How can I make your day better?', 'inner_thoughts': 'User has initiated contact. Sending a greeting.'}}}], 'role': 'model'}, 'finishReason': 'STOP', 'avgLogprobs': -0.25891534213362066}], 'usageMetadata': {'promptTokenCount': 2493, 'candidatesTokenCount': 29, 'totalTokenCount': 2522, 'promptTokensDetails': [{'modality': 'TEXT', 'tokenCount': 2493}], 'candidatesTokensDetails': [{'modality': 'TEXT', 'tokenCount': 29}]}, 'modelVersion': 'gemini-1.5-pro-002'}
# To patch this, if we have multiple parts we can take the last one
- if len(parts) > 1:
+ if len(parts) > 1 and not llm_config.enable_reasoner:
logger.warning(f"Unexpected multiple parts in response from Google AI: {parts}")
+ # only truncate if reasoning is off
parts = [parts[-1]]
# TODO support parts / multimodal
# TODO support parallel tool calling natively
# TODO Alternative here is to throw away everything else except for the first part
+ openai_response_message = None
for response_message in parts:
# Convert the actual message style to OpenAI style
if response_message.function_call:
@@ -472,22 +476,39 @@ class GoogleVertexClient(LLMClientBase):
# inner_thoughts = response_message.text
# Google AI API doesn't generate tool call IDs
- openai_response_message = Message(
- role="assistant", # NOTE: "model" -> "assistant"
- content=inner_thoughts,
- tool_calls=[
- ToolCall(
- id=get_tool_call_id(),
- type="function",
- function=FunctionCall(
- name=function_name,
- arguments=clean_json_string_extra_backslash(json_dumps(function_args)),
- ),
- )
- ],
+ tool_call = ToolCall(
+ id=get_tool_call_id(),
+ type="function",
+ function=FunctionCall(
+ name=function_name,
+ arguments=clean_json_string_extra_backslash(json_dumps(function_args)),
+ ),
)
+ if openai_response_message is None:
+ openai_response_message = Message(
+ role="assistant", # NOTE: "model" -> "assistant"
+ content=inner_thoughts,
+ tool_calls=[tool_call],
+ )
+ else:
+ openai_response_message.content = inner_thoughts
+ if openai_response_message.tool_calls is None:
+ openai_response_message.tool_calls = []
+ openai_response_message.tool_calls.append(tool_call)
+ if response_message.thought_signature:
+ thought_signature = base64.b64encode(response_message.thought_signature).decode("utf-8")
+ openai_response_message.reasoning_content_signature = thought_signature
+
else:
+ if response_message.thought:
+ if openai_response_message is None:
+ openai_response_message = Message(
+ role="assistant", # NOTE: "model" -> "assistant"
+ reasoning_content=response_message.text,
+ )
+ else:
+ openai_response_message.reasoning_content = response_message.text
try:
# Structured output tool call
function_call = json_loads(response_message.text)
@@ -508,20 +529,25 @@ class GoogleVertexClient(LLMClientBase):
inner_thoughts = None
# Google AI API doesn't generate tool call IDs
- openai_response_message = Message(
- role="assistant", # NOTE: "model" -> "assistant"
- content=inner_thoughts,
- tool_calls=[
- ToolCall(
- id=get_tool_call_id(),
- type="function",
- function=FunctionCall(
- name=function_name,
- arguments=clean_json_string_extra_backslash(json_dumps(function_args)),
- ),
- )
- ],
+ tool_call = ToolCall(
+ id=get_tool_call_id(),
+ type="function",
+ function=FunctionCall(
+ name=function_name,
+ arguments=clean_json_string_extra_backslash(json_dumps(function_args)),
+ ),
)
+ if openai_response_message is None:
+ openai_response_message = Message(
+ role="assistant", # NOTE: "model" -> "assistant"
+ content=inner_thoughts,
+ tool_calls=[tool_call],
+ )
+ else:
+ openai_response_message.content = inner_thoughts
+ if openai_response_message.tool_calls is None:
+ openai_response_message.tool_calls = []
+ openai_response_message.tool_calls.append(tool_call)
except json.decoder.JSONDecodeError:
if candidate.finish_reason == "MAX_TOKENS":
@@ -530,10 +556,16 @@ class GoogleVertexClient(LLMClientBase):
inner_thoughts = response_message.text
# Google AI API doesn't generate tool call IDs
- openai_response_message = Message(
- role="assistant", # NOTE: "model" -> "assistant"
- content=inner_thoughts,
- )
+ if openai_response_message is None:
+ openai_response_message = Message(
+ role="assistant", # NOTE: "model" -> "assistant"
+ content=inner_thoughts,
+ )
+ else:
+ openai_response_message.content = inner_thoughts
+ if response_message.thought_signature:
+ thought_signature = base64.b64encode(response_message.thought_signature).decode("utf-8")
+ openai_response_message.reasoning_content_signature = thought_signature
# Google AI API uses different finish reason strings than OpenAI
# OpenAI: 'stop', 'length', 'function_call', 'content_filter', null
diff --git a/letta/schemas/message.py b/letta/schemas/message.py
index 5883d1524..1d24e6de2 100644
--- a/letta/schemas/message.py
+++ b/letta/schemas/message.py
@@ -1344,7 +1344,7 @@ class Message(BaseMessage):
}
elif self.role == "assistant" or self.role == "approval":
- assert self.tool_calls is not None or text_content is not None
+ assert self.tool_calls is not None or text_content is not None or len(self.content) > 1
google_ai_message = {
"role": "model", # NOTE: different
}
diff --git a/tests/configs/llm_model_configs/gemini-2.5-flash-vertex.json b/tests/configs/llm_model_configs/gemini-2.5-flash-vertex.json
index 102dff1f5..feedd7eb4 100644
--- a/tests/configs/llm_model_configs/gemini-2.5-flash-vertex.json
+++ b/tests/configs/llm_model_configs/gemini-2.5-flash-vertex.json
@@ -5,5 +5,5 @@
"context_window": 1048576,
"put_inner_thoughts_in_kwargs": true,
"enable_reasoner": true,
- "max_reasoning_tokens": 1
+ "max_reasoning_tokens": 20000
}
diff --git a/tests/configs/llm_model_configs/gemini-2.5-flash.json b/tests/configs/llm_model_configs/gemini-2.5-flash.json
index ee91676f7..387f1eb72 100644
--- a/tests/configs/llm_model_configs/gemini-2.5-flash.json
+++ b/tests/configs/llm_model_configs/gemini-2.5-flash.json
@@ -6,5 +6,5 @@
"model_wrapper": null,
"put_inner_thoughts_in_kwargs": true,
"enable_reasoner": true,
- "max_reasoning_tokens": 1
+ "max_reasoning_tokens": 20000
}
diff --git a/tests/integration_test_send_message_v2.py b/tests/integration_test_send_message_v2.py
index 3ffac7d97..eca630869 100644
--- a/tests/integration_test_send_message_v2.py
+++ b/tests/integration_test_send_message_v2.py
@@ -120,7 +120,11 @@ def assert_greeting_response(
assert len(messages) == expected_message_count
except:
# Reasoning summary in responses API when effort is high is still flaky, so don't throw if missing
- if LLMConfig.is_openai_reasoning_model(llm_config):
+ if (
+ LLMConfig.is_openai_reasoning_model(llm_config)
+ or LLMConfig.is_google_vertex_reasoning_model(llm_config)
+ or LLMConfig.is_google_ai_reasoning_model(llm_config)
+ ):
assert len(messages) == expected_message_count - 1
else:
raise
@@ -136,15 +140,22 @@ def assert_greeting_response(
otid_suffix = 0
try:
if (
- LLMConfig.is_openai_reasoning_model(llm_config) and llm_config.reasoning_effort == "high"
- ) or LLMConfig.is_anthropic_reasoning_model(llm_config):
+ (LLMConfig.is_openai_reasoning_model(llm_config) and llm_config.reasoning_effort == "high")
+ or LLMConfig.is_anthropic_reasoning_model(llm_config)
+ or LLMConfig.is_google_vertex_reasoning_model(llm_config)
+ or LLMConfig.is_google_ai_reasoning_model(llm_config)
+ ):
assert isinstance(messages[index], ReasoningMessage)
assert messages[index].otid and messages[index].otid[-1] == str(otid_suffix)
index += 1
otid_suffix += 1
except:
# Reasoning summary in responses API when effort is high is still flaky, so don't throw if missing
- if LLMConfig.is_openai_reasoning_model(llm_config):
+ if (
+ LLMConfig.is_openai_reasoning_model(llm_config)
+ or LLMConfig.is_google_vertex_reasoning_model(llm_config)
+ or LLMConfig.is_google_ai_reasoning_model(llm_config)
+ ):
pass
else:
raise
@@ -325,8 +336,11 @@ def get_expected_message_count(llm_config: LLMConfig, tool_call: bool = False, s
"""
is_reasoner_model = (
- LLMConfig.is_openai_reasoning_model(llm_config) and llm_config.reasoning_effort == "high"
- ) or LLMConfig.is_anthropic_reasoning_model(llm_config)
+ (LLMConfig.is_openai_reasoning_model(llm_config) and llm_config.reasoning_effort == "high")
+ or LLMConfig.is_anthropic_reasoning_model(llm_config)
+ or LLMConfig.is_google_vertex_reasoning_model(llm_config)
+ or LLMConfig.is_google_ai_reasoning_model(llm_config)
+ )
# assistant message
expected_message_count = 1