chore: import upstream snapshot with attribution
Continuous Integration / Pre-commit Linter (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.10) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.11) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.12) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.12) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Has been cancelled
Copybara PR Handler / close-imported-pr (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:25:13 +08:00
commit ec2b666284
2231 changed files with 491535 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
@@ -0,0 +1,123 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for AntigravityAgent.
Verifies the root-only construction constraint that keeps the agent usable only
as a standalone root agent while the SDK supports local mode only.
"""
from __future__ import annotations
from unittest.mock import AsyncMock
from unittest.mock import MagicMock
from unittest.mock import patch
from google.adk.agents.base_agent import BaseAgent
from google.adk.labs.antigravity import _antigravity_agent
from google.adk.labs.antigravity._antigravity_agent import AntigravityAgent
from google.antigravity import LocalAgentConfig
import pytest
def _make_config(**kwargs) -> LocalAgentConfig:
"""Returns a minimal real LocalAgentConfig for the wrapped SDK agent."""
return LocalAgentConfig(system_instructions='test', **kwargs)
def test_standalone_agent_is_allowed():
"""An AntigravityAgent with no parent and no sub-agents constructs cleanly."""
agent = AntigravityAgent(name='agy', config=_make_config())
assert agent.parent_agent is None
assert agent.sub_agents == []
def test_giving_sub_agents_is_rejected():
"""Constructing with sub-agents raises a temporary root-only error."""
child = BaseAgent(name='child')
with pytest.raises(ValueError, match='standalone root agent'):
AntigravityAgent(name='agy', config=_make_config(), sub_agents=[child])
def test_using_as_sub_agent_is_rejected():
"""Adopting the agent under a parent raises a temporary root-only error."""
agy = AntigravityAgent(name='agy', config=_make_config())
with pytest.raises(ValueError, match='standalone root agent'):
BaseAgent(name='parent', sub_agents=[agy])
@pytest.mark.asyncio
async def test_run_without_save_dir_raises():
"""Running without config.save_dir raises, since trajectories need a folder."""
agent = AntigravityAgent(name='agy', config=_make_config())
with pytest.raises(ValueError, match='requires config.save_dir'):
async for _ in agent._run_async_impl(MagicMock()):
pass
@pytest.mark.asyncio
async def test_resumed_replayed_steps_are_skipped(tmp_path):
"""On resume, steps at or below the resume index are not re-emitted."""
from google.antigravity import types as sdk_types
def _step(step_index: int, text: str):
step = MagicMock()
step.step_index = step_index
step.source = sdk_types.StepSource.MODEL
step.type = sdk_types.StepType.TEXT_RESPONSE
step.status = sdk_types.StepStatus.DONE
step.is_complete_response = True
step.content = text
step.tool_calls = []
return step
# The harness replays steps 0-1 (prior turn) then emits step 2 (this turn).
async def _receive_steps():
yield _step(0, 'old-1')
yield _step(1, 'old-2')
yield _step(2, 'new')
conversation = MagicMock()
conversation.send = AsyncMock()
conversation.receive_steps = _receive_steps
active_agent = MagicMock()
active_agent.conversation = conversation
active_agent.conversation_id = 'sess_456_agy'
active_agent.__aenter__ = AsyncMock(return_value=active_agent)
active_agent.__aexit__ = AsyncMock(return_value=None)
# A prior trajectory + resume index in save_dir triggers resume at index 1.
save_dir = tmp_path
(save_dir / 'traj-sess_456_agy').write_bytes(b'data')
(save_dir / 'traj-sess_456_agy.resume').write_text('1')
agent = AntigravityAgent(
name='agy', config=_make_config(save_dir=str(save_dir))
)
ctx = MagicMock()
ctx.invocation_id = 'inv_1'
ctx.branch = 'main'
ctx.session.id = 'sess_456'
ctx.user_content = None
ctx.run_config = None
with patch.object(_antigravity_agent, 'Agent', return_value=active_agent):
events = [event async for event in agent._run_async_impl(ctx)]
texts = [e.content.parts[0].text for e in events]
assert texts == ['new']
@@ -0,0 +1,226 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the Antigravity step-to-event converter.
Verifies that model text, function calls, and function responses map to the
expected ADK events, and that repeated steps are deduplicated.
"""
from __future__ import annotations
from unittest.mock import MagicMock
from google.adk.labs.antigravity import _event_converter
from google.antigravity import types as sdk_types
def _make_ctx() -> MagicMock:
ctx = MagicMock()
ctx.invocation_id = 'inv_1'
ctx.branch = 'main'
return ctx
def _convert(step, *, streaming=False):
return _event_converter.convert_step_to_events(
step,
ctx=_make_ctx(),
author='agy',
seen_tool_calls=set(),
seen_tool_results=set(),
streaming=streaming,
)
def test_completed_model_text_maps_to_one_model_text_event():
"""A completed model text response becomes a single model text event."""
step = sdk_types.Step(
step_index=0,
type=sdk_types.StepType.TEXT_RESPONSE,
source=sdk_types.StepSource.MODEL,
content='hello there',
is_complete_response=True,
)
events = _convert(step)
assert len(events) == 1
assert events[0].author == 'agy'
assert events[0].content.role == 'model'
assert events[0].content.parts[0].text == 'hello there'
def test_partial_model_text_produces_no_event():
"""A streaming partial text step (cumulative snapshot) yields nothing."""
step = sdk_types.Step(
step_index=0,
type=sdk_types.StepType.TEXT_RESPONSE,
source=sdk_types.StepSource.MODEL,
content='hello',
content_delta='hello',
is_complete_response=None,
)
assert _convert(step) == []
def test_function_call_maps_to_function_call_event():
"""A model tool-call step becomes a model function-call event."""
step = sdk_types.Step(
step_index=1,
type=sdk_types.StepType.TOOL_CALL,
source=sdk_types.StepSource.MODEL,
tool_calls=[
sdk_types.ToolCall(name='view_file', args={'path': '/x'}, id='c1')
],
)
events = _convert(step)
assert len(events) == 1
fc = events[0].content.parts[0].function_call
assert events[0].author == 'agy'
assert fc.name == 'view_file'
assert fc.id == 'c1'
assert fc.args == {'path': '/x'}
def test_function_response_maps_to_function_response_event():
"""A completed tool-execution step becomes a function-response event."""
step = sdk_types.Step(
step_index=2,
type=sdk_types.StepType.TOOL_CALL,
source=sdk_types.StepSource.SYSTEM,
status=sdk_types.StepStatus.DONE,
content='file contents',
tool_calls=[sdk_types.ToolCall(name='view_file', args={}, id='c1')],
)
events = _convert(step)
assert len(events) == 1
fr = events[0].content.parts[0].function_response
assert events[0].author == 'view_file'
assert events[0].content.role == 'user'
assert fr.name == 'view_file'
assert fr.id == 'c1'
assert fr.response == {'result': 'file contents'}
def test_errored_tool_step_maps_error_response():
"""A failed tool-execution step reports the error in the response payload."""
step = sdk_types.Step(
step_index=3,
type=sdk_types.StepType.TOOL_CALL,
source=sdk_types.StepSource.SYSTEM,
status=sdk_types.StepStatus.ERROR,
error='permission denied',
tool_calls=[sdk_types.ToolCall(name='run_command', args={}, id='c2')],
)
events = _convert(step)
assert events[0].content.parts[0].function_response.response == {
'error': 'permission denied'
}
def test_duplicate_tool_call_emitted_once():
"""The same tool call repeated across steps is emitted only once."""
call = sdk_types.ToolCall(name='view_file', args={}, id='c1')
step = sdk_types.Step(
step_index=1,
type=sdk_types.StepType.TOOL_CALL,
source=sdk_types.StepSource.MODEL,
tool_calls=[call],
)
ctx = _make_ctx()
seen: set[str] = set()
first = _event_converter.convert_step_to_events(
step, ctx=ctx, author='agy', seen_tool_calls=seen, seen_tool_results=set()
)
second = _event_converter.convert_step_to_events(
step, ctx=ctx, author='agy', seen_tool_calls=seen, seen_tool_results=set()
)
assert len(first) == 1
assert second == []
def test_incomplete_text_step_produces_no_final_event():
"""A non-final text step yields nothing in non-streaming mode."""
step = sdk_types.Step(
step_index=0,
type=sdk_types.StepType.TEXT_RESPONSE,
source=sdk_types.StepSource.MODEL,
thinking='reasoning...',
content='',
)
assert _convert(step) == []
def test_streaming_emits_partial_thinking_then_text_deltas():
"""In SSE mode a step's thinking and text deltas become partial events."""
step = sdk_types.Step(
step_index=0,
type=sdk_types.StepType.TEXT_RESPONSE,
source=sdk_types.StepSource.MODEL,
thinking_delta='thinking...',
content_delta='hello',
)
events = _convert(step, streaming=True)
assert len(events) == 2
assert events[0].partial is True
assert events[0].content.parts[0].thought is True
assert events[0].content.parts[0].text == 'thinking...'
assert events[1].partial is True
assert events[1].content.parts[0].text == 'hello'
def test_non_streaming_omits_partial_deltas():
"""Without SSE mode, delta-only steps yield no events."""
step = sdk_types.Step(
step_index=0,
type=sdk_types.StepType.TEXT_RESPONSE,
source=sdk_types.StepSource.MODEL,
thinking_delta='thinking...',
content_delta='hello',
)
assert _convert(step, streaming=False) == []
def test_streaming_completed_step_emits_partial_then_final():
"""A completed step in SSE mode emits the partial delta then the final text."""
step = sdk_types.Step(
step_index=1,
type=sdk_types.StepType.TEXT_RESPONSE,
source=sdk_types.StepSource.MODEL,
content_delta=' world',
content='hello world',
is_complete_response=True,
)
events = _convert(step, streaming=True)
assert len(events) == 2
assert events[0].partial is True
assert events[0].content.parts[0].text == ' world'
assert events[1].partial in (False, None)
assert events[1].content.parts[0].text == 'hello world'
@@ -0,0 +1,79 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for Antigravity trajectory resumption bookkeeping in save_dir.
Verifies trajectory detection, resume step index persistence, and renaming the
harness's randomly-named trajectory to a deterministic name.
"""
from __future__ import annotations
from google.adk.labs.antigravity import _trajectory_files
def test_has_trajectory_false_when_absent(tmp_path):
"""No trajectory file means no prior conversation to resume."""
assert not _trajectory_files.has_trajectory(str(tmp_path), 'sess_agy')
def test_has_trajectory_true_when_present(tmp_path):
"""An existing traj file is detected for the conversation."""
(tmp_path / 'traj-sess_agy').write_bytes(b'data')
assert _trajectory_files.has_trajectory(str(tmp_path), 'sess_agy')
def test_load_resume_step_index_minus_one_when_absent(tmp_path):
"""Missing resume step index reads as -1 (fresh)."""
assert (
_trajectory_files.load_resume_step_index(str(tmp_path), 'sess_agy') == -1
)
def test_resume_step_index_round_trips(tmp_path):
"""A saved resume step index reads back as the same value."""
_trajectory_files.save_resume_step_index(str(tmp_path), 'sess_agy', 12)
assert (
_trajectory_files.load_resume_step_index(str(tmp_path), 'sess_agy') == 12
)
def test_load_resume_step_index_minus_one_when_corrupt(tmp_path):
"""A non-integer resume step index is treated as fresh."""
(tmp_path / 'traj-sess_agy.resume').write_text('not-an-int')
assert (
_trajectory_files.load_resume_step_index(str(tmp_path), 'sess_agy') == -1
)
def test_rename_trajectory_to_conversation_id(tmp_path):
"""The harness's random trajectory is renamed to the deterministic name."""
(tmp_path / 'traj-random123').write_bytes(b'data')
_trajectory_files.rename_trajectory(str(tmp_path), 'sess_agy', 'random123')
assert not (tmp_path / 'traj-random123').exists()
assert (tmp_path / 'traj-sess_agy').read_bytes() == b'data'
def test_rename_trajectory_noop_when_already_named(tmp_path):
"""Renaming is a no-op when the harness id already matches."""
(tmp_path / 'traj-sess_agy').write_bytes(b'data')
_trajectory_files.rename_trajectory(str(tmp_path), 'sess_agy', 'sess_agy')
assert (tmp_path / 'traj-sess_agy').read_bytes() == b'data'
+13
View File
@@ -0,0 +1,13 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
@@ -0,0 +1,468 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
from unittest import mock
from google.adk.labs.openai._openai_llm import _function_declaration_to_openai_tool
from google.adk.labs.openai._openai_llm import _part_to_openai_content
from google.adk.labs.openai._openai_llm import _update_type_string
from google.adk.labs.openai._openai_llm import OpenAILlm
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.genai import types
from google.genai.types import Content
from google.genai.types import Part
import pytest
def test_supported_models():
models = OpenAILlm.supported_models()
assert len(models) == 3
assert models[0] == r"gpt-.*"
assert models[1] == r"o1-.*"
assert models[2] == r"o3-.*"
def test_update_type_string():
schema = {
"type": "OBJECT",
"properties": {
"name": {"type": "STRING"},
"age": {"type": "INTEGER"},
"tags": {"type": "ARRAY", "items": {"type": "STRING"}},
},
}
_update_type_string(schema)
assert schema["type"] == "object"
assert schema["properties"]["name"]["type"] == "string"
assert schema["properties"]["age"]["type"] == "integer"
assert schema["properties"]["tags"]["type"] == "array"
assert schema["properties"]["tags"]["items"]["type"] == "string"
def test_function_declaration_to_openai_tool():
fd = types.FunctionDeclaration(
name="get_weather",
description="Get weather",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={"location": types.Schema(type=types.Type.STRING)},
required=["location"],
),
)
tool = _function_declaration_to_openai_tool(fd)
assert tool["type"] == "function"
assert tool["function"]["name"] == "get_weather"
assert tool["function"]["parameters"]["type"] == "object"
assert (
tool["function"]["parameters"]["properties"]["location"]["type"]
== "string"
)
assert tool["function"]["parameters"]["required"] == ["location"]
def test_part_to_openai_content():
# Test text part
part = types.Part.from_text(text="Hello")
content = _part_to_openai_content(part)
assert content == "Hello"
# Test thought part
part = types.Part.from_text(text="I am thinking")
part.thought = True
content = _part_to_openai_content(part)
assert content == "Thought: I am thinking"
# Test image part (inline data)
part = types.Part(
inline_data=types.Blob(data=b"fake_data", mime_type="image/png")
)
content = _part_to_openai_content(part)
assert isinstance(content, dict)
assert content["type"] == "image_url"
assert content["image_url"]["url"].startswith("data:image/png;base64,")
def test_content_to_openai_messages_with_empty_response():
from google.adk.labs.openai._openai_llm import _content_to_openai_messages
# Test with empty dict response
content = types.Content(
role="tool",
parts=[
types.Part(
function_response=types.FunctionResponse(
id="call_123",
name="get_weather",
response={},
)
)
],
)
messages = _content_to_openai_messages(content)
assert len(messages) == 1
assert messages[0]["role"] == "tool"
assert messages[0]["tool_call_id"] == "call_123"
assert messages[0]["content"] == "{}"
# Test with None response
content = types.Content(
role="tool",
parts=[
types.Part(
function_response=types.FunctionResponse(
id="call_123",
name="get_weather",
response=None,
)
)
],
)
messages = _content_to_openai_messages(content)
assert len(messages) == 1
assert messages[0]["content"] == ""
@pytest.mark.asyncio
async def test_generate_content_async():
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test_key"}):
openai_llm = OpenAILlm(model="gpt-4o")
llm_request = LlmRequest(
model="gpt-4o",
contents=[Content(role="user", parts=[Part.from_text(text="Hello")])],
)
mock_response = mock.MagicMock()
mock_choice = mock.MagicMock()
mock_message = mock.MagicMock()
mock_message.content = "Hello there!"
mock_message.tool_calls = None
mock_choice.message = mock_message
mock_response.choices = [mock_choice]
mock_response.usage.prompt_tokens = 10
mock_response.usage.completion_tokens = 5
mock_response.usage.total_tokens = 15
async def mock_create(*args, **kwargs):
return mock_response
with mock.patch(
"google.adk.labs.openai._openai_llm.AsyncOpenAI"
) as mock_client_class:
mock_client = mock.MagicMock()
mock_client_class.return_value = mock_client
mock_client.chat.completions.create = mock_create
responses = [
resp
async for resp in openai_llm.generate_content_async(
llm_request, stream=False
)
]
assert len(responses) == 1
assert isinstance(responses[0], LlmResponse)
assert responses[0].content.parts[0].text == "Hello there!"
assert responses[0].usage_metadata.total_token_count == 15
@pytest.mark.asyncio
async def test_generate_content_async_with_config():
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test_key"}):
openai_llm = OpenAILlm(model="gpt-4o")
llm_request = LlmRequest(
model="gpt-4o",
contents=[Content(role="user", parts=[Part.from_text(text="Hello")])],
config=types.GenerateContentConfig(
temperature=0.7,
top_p=0.9,
stop_sequences=["STOP"],
max_output_tokens=100,
),
)
mock_response = mock.MagicMock()
mock_choice = mock.MagicMock()
mock_message = mock.MagicMock()
mock_message.content = "Hello there!"
mock_message.tool_calls = None
mock_choice.message = mock_message
mock_response.choices = [mock_choice]
mock_call = mock.MagicMock(return_value=mock_response)
mock_response.usage.prompt_tokens = 10
mock_response.usage.completion_tokens = 5
mock_response.usage.total_tokens = 15
create_kwargs = {}
async def mock_create(*args, **kwargs):
nonlocal create_kwargs
create_kwargs = kwargs
return mock_response
with mock.patch(
"google.adk.labs.openai._openai_llm.AsyncOpenAI"
) as mock_client_class:
mock_client = mock.MagicMock()
mock_client_class.return_value = mock_client
mock_client.chat.completions.create = mock_create
responses = [
resp
async for resp in openai_llm.generate_content_async(
llm_request, stream=False
)
]
assert len(responses) == 1
assert create_kwargs["temperature"] == 0.7
assert create_kwargs["top_p"] == 0.9
assert create_kwargs["stop"] == ["STOP"]
assert create_kwargs["max_tokens"] == 100
@pytest.mark.asyncio
async def test_generate_content_async_with_system_instruction():
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test_key"}):
openai_llm = OpenAILlm(model="gpt-4o")
llm_request = LlmRequest(
model="gpt-4o",
contents=[Content(role="user", parts=[Part.from_text(text="Hello")])],
config=types.GenerateContentConfig(
system_instruction="You are a helpful assistant.",
),
)
mock_response = mock.MagicMock()
mock_choice = mock.MagicMock()
mock_message = mock.MagicMock()
mock_message.content = "Hello there!"
mock_message.tool_calls = None
mock_choice.message = mock_message
mock_response.choices = [mock_choice]
mock_response.usage.prompt_tokens = 10
mock_response.usage.completion_tokens = 5
mock_response.usage.total_tokens = 15
create_kwargs = {}
async def mock_create(*args, **kwargs):
nonlocal create_kwargs
create_kwargs = kwargs
return mock_response
with mock.patch(
"google.adk.labs.openai._openai_llm.AsyncOpenAI"
) as mock_client_class:
mock_client = mock.MagicMock()
mock_client_class.return_value = mock_client
mock_client.chat.completions.create = mock_create
responses = [
resp
async for resp in openai_llm.generate_content_async(
llm_request, stream=False
)
]
assert len(responses) == 1
messages = create_kwargs["messages"]
assert len(messages) == 2
assert messages[0]["role"] == "system"
assert messages[0]["content"] == "You are a helpful assistant."
assert messages[1]["role"] == "user"
assert messages[1]["content"] == "Hello"
@pytest.mark.asyncio
async def test_generate_content_async_with_image():
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test_key"}):
openai_llm = OpenAILlm(model="gpt-4o")
image_part = Part(
inline_data=types.Blob(data=b"fake_image_data", mime_type="image/png")
)
llm_request = LlmRequest(
model="gpt-4o",
contents=[
Content(
role="user",
parts=[Part.from_text(text="Analyze this"), image_part],
)
],
)
mock_response = mock.MagicMock()
mock_choice = mock.MagicMock()
mock_message = mock.MagicMock()
mock_message.content = "It's an image."
mock_message.tool_calls = None
mock_choice.message = mock_message
mock_response.choices = [mock_choice]
mock_response.usage.prompt_tokens = 10
mock_response.usage.completion_tokens = 5
mock_response.usage.total_tokens = 15
create_kwargs = {}
async def mock_create(*args, **kwargs):
nonlocal create_kwargs
create_kwargs = kwargs
return mock_response
with mock.patch(
"google.adk.labs.openai._openai_llm.AsyncOpenAI"
) as mock_client_class:
mock_client = mock.MagicMock()
mock_client_class.return_value = mock_client
mock_client.chat.completions.create = mock_create
responses = [
resp
async for resp in openai_llm.generate_content_async(
llm_request, stream=False
)
]
assert len(responses) == 1
messages = create_kwargs["messages"]
assert len(messages) == 1
assert messages[0]["role"] == "user"
content = messages[0]["content"]
assert isinstance(content, list)
assert len(content) == 2
assert content[0]["type"] == "text"
assert content[0]["text"] == "Analyze this"
assert content[1]["type"] == "image_url"
assert content[1]["image_url"]["url"].startswith("data:image/png;base64,")
def _completion_with_cached_tokens(cached_tokens):
"""Builds a mock ChatCompletion whose usage carries prompt_tokens_details."""
mock_response = mock.MagicMock()
mock_choice = mock.MagicMock()
mock_message = mock.MagicMock()
mock_message.content = "Hello there!"
mock_message.tool_calls = None
mock_choice.message = mock_message
mock_response.choices = [mock_choice]
mock_response.usage.prompt_tokens = 100
mock_response.usage.completion_tokens = 5
mock_response.usage.total_tokens = 105
if cached_tokens is None:
mock_response.usage.prompt_tokens_details = None
else:
mock_response.usage.prompt_tokens_details.cached_tokens = cached_tokens
return mock_response
@pytest.mark.asyncio
async def test_generate_content_async_reports_cached_tokens():
"""prompt_tokens_details.cached_tokens populates cached_content_token_count."""
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test_key"}):
openai_llm = OpenAILlm(model="gpt-4o")
llm_request = LlmRequest(
model="gpt-4o",
contents=[Content(role="user", parts=[Part.from_text(text="Hello")])],
)
mock_response = _completion_with_cached_tokens(64)
async def mock_create(*args, **kwargs):
return mock_response
with mock.patch(
"google.adk.labs.openai._openai_llm.AsyncOpenAI"
) as mock_client_class:
mock_client = mock.MagicMock()
mock_client_class.return_value = mock_client
mock_client.chat.completions.create = mock_create
responses = [
resp
async for resp in openai_llm.generate_content_async(
llm_request, stream=False
)
]
assert len(responses) == 1
assert responses[0].usage_metadata.cached_content_token_count == 64
assert responses[0].usage_metadata.prompt_token_count == 100
@pytest.mark.asyncio
async def test_generate_content_async_zero_cached_tokens():
"""No cache hit (cached_tokens=0) reports 0, not a regression."""
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test_key"}):
openai_llm = OpenAILlm(model="gpt-4o")
llm_request = LlmRequest(
model="gpt-4o",
contents=[Content(role="user", parts=[Part.from_text(text="Hello")])],
)
mock_response = _completion_with_cached_tokens(0)
async def mock_create(*args, **kwargs):
return mock_response
with mock.patch(
"google.adk.labs.openai._openai_llm.AsyncOpenAI"
) as mock_client_class:
mock_client = mock.MagicMock()
mock_client_class.return_value = mock_client
mock_client.chat.completions.create = mock_create
responses = [
resp
async for resp in openai_llm.generate_content_async(
llm_request, stream=False
)
]
assert responses[0].usage_metadata.cached_content_token_count == 0
@pytest.mark.asyncio
async def test_generate_content_async_absent_prompt_tokens_details():
"""Missing prompt_tokens_details maps to None (no cached count reported)."""
with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "test_key"}):
openai_llm = OpenAILlm(model="gpt-4o")
llm_request = LlmRequest(
model="gpt-4o",
contents=[Content(role="user", parts=[Part.from_text(text="Hello")])],
)
mock_response = _completion_with_cached_tokens(None)
async def mock_create(*args, **kwargs):
return mock_response
with mock.patch(
"google.adk.labs.openai._openai_llm.AsyncOpenAI"
) as mock_client_class:
mock_client = mock.MagicMock()
mock_client_class.return_value = mock_client
mock_client.chat.completions.create = mock_create
responses = [
resp
async for resp in openai_llm.generate_content_async(
llm_request, stream=False
)
]
assert responses[0].usage_metadata.cached_content_token_count is None
File diff suppressed because it is too large Load Diff