Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from genkit import FinishReason, GenkitError, Message, ModelResponse, Part, Role
from genkit.model import GenerationUsage, ModelRequest, ToolDefinition, ToolRequest
from genkit_amazon_bedrock._config import BedrockConfig
from genkit_amazon_bedrock._tool_input import unwrap_string_input, wrap_string_input, wrap_string_schema

# Bedrock returns signed and sometimes redacted reasoning that has to be sent
# back verbatim next turn or the model rejects it, so both ride on the part
Expand Down Expand Up @@ -340,7 +341,7 @@ def _tool_use_id(ref: str | None, label: str) -> str:
return ref


def _part_to_blocks(part: Part) -> list[dict[str, Any]]:
def _part_to_blocks(part: Part, tools: list[ToolDefinition] | None = None) -> list[dict[str, Any]]:
"""Converts one Genkit part to Converse content blocks.

Unknown part kinds are silently dropped so a foreign part cannot fail a
Expand All @@ -355,7 +356,7 @@ def _part_to_blocks(part: Part) -> list[dict[str, Any]]:
'toolUse': {
'toolUseId': _tool_use_id(tool_request.ref, 'tool request'),
'name': tool_request.name,
'input': tool_request.input,
'input': wrap_string_input(tool_request.name, tool_request.input, tools),
}
}
]
Expand Down Expand Up @@ -396,6 +397,7 @@ def _system_blocks(message: Message | Any) -> list[dict[str, Any]]: # noqa: ANN

def convert_messages(
messages: list[Message] | None,
tools: list[ToolDefinition] | None = None,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Splits Genkit messages into Converse messages and top-level system blocks.

Expand All @@ -421,7 +423,7 @@ def convert_messages(
for part in message.content or []:
if part is None:
continue
blocks.extend(_part_to_blocks(part))
blocks.extend(_part_to_blocks(part, tools))
if not blocks:
continue
converse_messages.append({'role': role, 'content': blocks})
Expand All @@ -446,6 +448,7 @@ def _normalize_tool_schema(schema: Any) -> dict[str, Any]: # noqa: ANN401
normalized = parsed if isinstance(parsed, dict) else {'type': 'object', 'properties': {}}
else:
return {'type': 'object', 'properties': {}}
normalized = wrap_string_schema(normalized) or normalized
normalized.setdefault('type', 'object')
if normalized.get('type') == 'object':
normalized.setdefault('properties', {})
Expand Down Expand Up @@ -499,9 +502,8 @@ def build_converse_request(model_id: str, request: ModelRequest[Any]) -> dict[st
if request is None:
raise GenkitError(message='bedrock: model request is missing', status='INVALID_ARGUMENT')
config = normalize_config(request.config)
messages, system = convert_messages(request.messages)

tools = request.tools or []
messages, system = convert_messages(request.messages, tools)
tool_choice = _requested_tool_choice(request, config) if tools else ''
# "none" means omit toolConfig entirely — Bedrock has no none mode.
send_tool_config = bool(tools) and tool_choice != 'none'
Expand Down Expand Up @@ -598,6 +600,7 @@ def _coerce_map(value: dict[str, Any], schema: dict[str, Any]) -> dict[str, Any]

def coerce_tool_input(name: str, value: Any, tools: list[ToolDefinition] | None) -> Any: # noqa: ANN401
"""Coerces a decoded tool input toward the named tool's declared schema."""
value = unwrap_string_input(name, value, tools)
if not isinstance(value, dict):
return value
for tool in tools or []:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# 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.
#
# SPDX-License-Identifier: Apache-2.0

"""Wire envelope for tools whose Genkit input is a bare string."""

from __future__ import annotations

from collections.abc import Sequence
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from genkit.model import ToolDefinition

TOOL_INPUT_FIELD = 'input'


def wrap_string_schema(schema: dict[str, Any] | None) -> dict[str, Any] | None:
"""Object-only provider APIs receive ``{'input': <string schema>}``."""
if not isinstance(schema, dict) or schema.get('type') != 'string':
return schema
return {
'type': 'object',
'properties': {TOOL_INPUT_FIELD: dict(schema)},
'required': [TOOL_INPUT_FIELD],
}


def is_string_tool(name: str, tools: Sequence[ToolDefinition | None] | None) -> bool:
return any(
tool is not None
and tool.name == name
and isinstance(tool.input_schema, dict)
and tool.input_schema.get('type') == 'string'
for tool in tools or ()
)


def unwrap_string_input(name: str, value: Any, tools: Sequence[ToolDefinition] | None) -> Any: # noqa: ANN401
"""Restore the original string only for a declared string tool."""
if is_string_tool(name, tools) and isinstance(value, dict) and TOOL_INPUT_FIELD in value:
return value[TOOL_INPUT_FIELD]
return value


def wrap_string_input(name: str, value: Any, tools: Sequence[ToolDefinition] | None) -> Any: # noqa: ANN401
"""Replay a prior bare-string call using the same object wire schema."""
if is_string_tool(name, tools) and not (isinstance(value, dict) and TOOL_INPUT_FIELD in value):
return {TOOL_INPUT_FIELD: value}
return value
30 changes: 29 additions & 1 deletion packages/genkit-amazon-bedrock/tests/converters_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
)

from genkit import FinishReason, GenkitError, Message, Part, Role
from genkit.model import ModelConfig, ModelRequest, ToolDefinition
from genkit.model import ModelConfig, ModelRequest, ToolDefinition, ToolRequest

PNG_BYTES = b'\x89PNG\r\n\x1a\nfakeimagedata'
PNG_B64 = base64.b64encode(PNG_BYTES).decode()
Expand Down Expand Up @@ -468,6 +468,34 @@ def test_tools_become_tool_specs() -> None:
assert 'toolChoice' not in kwargs['toolConfig']


def test_string_tool_input_round_trips_as_bare_string() -> None:
"""Converse sees an object, while Genkit receives the original string."""
tool = ToolDefinition(name='weather', description='Get weather', input_schema={'type': 'string'})
request = user_text_request(tools=[tool])
schema = build_converse_request('amazon.nova-lite-v1:0', request)['toolConfig']['tools'][0]['toolSpec'][
'inputSchema'
]['json']
assert schema['type'] == 'object'
assert schema['properties']['input'] == {'type': 'string'}
parts = content_blocks_to_parts(
[{'toolUse': {'toolUseId': 'tool_1', 'name': 'weather', 'input': {'input': 'Paris'}}}], [tool]
)
assert parts[0].tool_request.input == 'Paris'


def test_string_tool_history_uses_wire_envelope() -> None:
"""A previous bare-string call is valid Converse input on the next turn."""
tool = ToolDefinition(name='weather', description='Get weather', input_schema={'type': 'string'})
messages = [
Message(role=Role.USER, content=[Part.from_text('Weather in Paris?')]),
Message(role=Role.MODEL, content=[Part(tool_request=ToolRequest(name='weather', ref='old', input='Paris'))]),
Message(role=Role.TOOL, content=[Part.from_text('Sunny')]),
]
kwargs = build_converse_request('amazon.nova-lite-v1:0', ModelRequest(messages=messages, tools=[tool]))
assert kwargs['messages'][1]['content'][0]['toolUse']['input'] == {'input': 'Paris'}
assert messages[1].content[0].tool_request.input == 'Paris'


def test_tool_schema_defaults_injected() -> None:
tool = ToolDefinition(name='noop', description='')
schema = to_bedrock_tool(tool)['toolSpec']['inputSchema']['json']
Expand Down