Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 11 additions & 0 deletions strands-py/src/strands/models/gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,17 @@ def _format_request_config(
# merged with, or replaced by, the narrower per-request choice.
config_params.setdefault("tool_config", tool_config)

# Server-side tool invocations is not supported in Vertex AI.
is_vertex = (
self._custom_client.vertexai if self._custom_client is not None else self.client_args.get("vertexai")
)
Comment thread
liramon2 marked this conversation as resolved.
Resolved
# Enable flag to mix function declarations with built-in tools.
needs_server_side_flag = tool_specs and self.config.get("gemini_tools") and not is_vertex
if needs_server_side_flag:
existing = config_params.setdefault("tool_config", genai.types.ToolConfig())
if isinstance(existing, genai.types.ToolConfig) and existing.include_server_side_tool_invocations is None:
existing.include_server_side_tool_invocations = True
Comment thread
liramon2 marked this conversation as resolved.
Resolved
Comment thread
liramon2 marked this conversation as resolved.
Resolved

return genai.types.GenerateContentConfig(
system_instruction=system_prompt,
tools=self._format_request_tools(tool_specs),
Expand Down
115 changes: 114 additions & 1 deletion strands-py/tests/strands/models/test_gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -1294,7 +1294,120 @@ async def test_stream_request_with_gemini_tools_and_function_tools(gemini_client
]
},
{"code_execution": {}},
]
],
"tool_config": {"include_server_side_tool_invocations": True},
},
"contents": [{"parts": [{"text": "test"}], "role": "user"}],
"model": model_id,
}
gemini_client.aio.models.generate_content_stream.assert_called_with(**exp_request)


@pytest.mark.parametrize(
("tool_choice", "exp_tool_config"),
[
(None, {"include_server_side_tool_invocations": True}),
({"auto": {}}, {"function_calling_config": {"mode": "AUTO"}, "include_server_side_tool_invocations": True}),
],
ids=["no-choice", "auto"],
)
@pytest.mark.asyncio
async def test_stream_gemini_tools_sets_server_side_flag(
gemini_client, messages, tool_spec, model_id, tool_choice, exp_tool_config
):
google_search_tool = genai.types.Tool(google_search=genai.types.GoogleSearch())
model = GeminiModel(model_id=model_id, gemini_tools=[google_search_tool])

await anext(model.stream(messages, tool_specs=[tool_spec], tool_choice=tool_choice))

exp_request = {
"config": {
"tools": [
{
"function_declarations": [
{
"description": tool_spec["description"],
"name": tool_spec["name"],
"parameters_json_schema": tool_spec["inputSchema"]["json"],
}
]
},
{"google_search": {}},
],
"tool_config": exp_tool_config,
},
"contents": [{"parts": [{"text": "test"}], "role": "user"}],
"model": model_id,
}
gemini_client.aio.models.generate_content_stream.assert_called_with(**exp_request)


@pytest.mark.asyncio
async def test_stream_gemini_tools_flag_skipped_on_vertex_ai(gemini_client, messages, tool_spec, model_id):
"""Vertex AI does not support include_server_side_tool_invocations, so the flag is omitted."""
google_search_tool = genai.types.Tool(google_search=genai.types.GoogleSearch())
model = GeminiModel(
model_id=model_id,
gemini_tools=[google_search_tool],
client_args={"api_key": "fake", "vertexai": True},
)

await anext(model.stream(messages, tool_specs=[tool_spec]))

exp_request = {
"config": {
"tools": [
{
"function_declarations": [
{
"description": tool_spec["description"],
"name": tool_spec["name"],
"parameters_json_schema": tool_spec["inputSchema"]["json"],
}
]
},
{"google_search": {}},
],
},
"contents": [{"parts": [{"text": "test"}], "role": "user"}],
"model": model_id,
}
gemini_client.aio.models.generate_content_stream.assert_called_with(**exp_request)


@pytest.mark.asyncio
async def test_stream_gemini_tools_flag_skipped_when_params_owns_tool_config(
gemini_client, messages, tool_spec, model_id
):
"""An explicit tool_config in params is not overwritten — the caller owns it."""
google_search_tool = genai.types.Tool(google_search=genai.types.GoogleSearch())
custom_tool_config = {
"function_calling_config": {"mode": "NONE"},
"include_server_side_tool_invocations": False,
}
model = GeminiModel(
model_id=model_id,
gemini_tools=[google_search_tool],
params={"tool_config": custom_tool_config},
)

await anext(model.stream(messages, tool_specs=[tool_spec]))

exp_request = {
"config": {
"tools": [
{
"function_declarations": [
{
"description": tool_spec["description"],
"name": tool_spec["name"],
"parameters_json_schema": tool_spec["inputSchema"]["json"],
}
]
},
{"google_search": {}},
],
"tool_config": custom_tool_config,
},
"contents": [{"parts": [{"text": "test"}], "role": "user"}],
"model": model_id,
Expand Down
59 changes: 58 additions & 1 deletion strands-ts/src/models/__tests__/google.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -972,7 +972,7 @@ describe('GoogleModel', () => {
})
)

const config = captured.config as { tools?: unknown[] }
const config = captured.config as { tools?: unknown[]; toolConfig?: Record<string, unknown> }
expect(config.tools).toHaveLength(2)
expect(config.tools![0]).toEqual({
functionDeclarations: [
Expand All @@ -984,6 +984,63 @@ describe('GoogleModel', () => {
],
})
expect(config.tools![1]).toEqual({ googleSearch: {} })
expect(config.toolConfig?.includeServerSideToolInvocations).toBe(true)
Comment thread
liramon2 marked this conversation as resolved.
Resolved
})

it('sets includeServerSideToolInvocations and preserves functionCallingConfig when toolChoice is set', async () => {
const { client, captured } = createMockClientWithCapture()
const provider = new GoogleModel({ client, builtInTools: [{ googleSearch: {} }] })
const messages = [new Message({ role: 'user', content: [new TextBlock('Hi')] })]

await collectIterator(
provider.stream(messages, {
toolSpecs: [{ name: 'read', description: 'read' }],
toolChoice: { auto: {} },
})
)

const config = captured.config as {
toolConfig?: { functionCallingConfig?: { mode?: string }; includeServerSideToolInvocations?: boolean }
}
expect(config.toolConfig?.functionCallingConfig?.mode).toBe(FunctionCallingConfigMode.AUTO)
expect(config.toolConfig?.includeServerSideToolInvocations).toBe(true)
})

it('does not set includeServerSideToolInvocations when only builtInTools are present', async () => {
const { client, captured } = createMockClientWithCapture()
const provider = new GoogleModel({ client, builtInTools: [{ codeExecution: {} }] })
const messages = [new Message({ role: 'user', content: [new TextBlock('Hi')] })]

await collectIterator(provider.stream(messages))

const config = captured.config as { toolConfig?: Record<string, unknown> }
expect(config.toolConfig).toBeUndefined()
})

it('does not set includeServerSideToolInvocations on Vertex AI', async () => {
const captured: Record<string, unknown> = {}
const client = {
vertexai: true,
models: {
generateContentStream: vi.fn(async (params: Record<string, unknown>) => {
Object.assign(captured, params)
return (async function* () {
yield { candidates: [{ finishReason: 'STOP' }] }
})()
}),
},
} as unknown as GoogleGenAI
const provider = new GoogleModel({ client, builtInTools: [{ googleSearch: {} }] })
const messages = [new Message({ role: 'user', content: [new TextBlock('Hi')] })]

await collectIterator(
provider.stream(messages, {
toolSpecs: [{ name: 'read', description: 'read' }],
})
)

const config = captured.config as { toolConfig?: Record<string, unknown> }
expect(config.toolConfig?.includeServerSideToolInvocations).toBeUndefined()
})

it('passes builtInTools when no toolSpecs provided', async () => {
Expand Down
9 changes: 9 additions & 0 deletions strands-ts/src/models/google/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,15 @@ export class GoogleModel extends Model<GoogleModelConfig> {
config.tools = []
}
config.tools.push(...this._config.builtInTools)

// Gemini Developer API requires this flag when mixing function declarations with built-in tools.
const needsServerSideFlag = options?.toolSpecs && options.toolSpecs.length > 0 && !this._client.vertexai
if (needsServerSideFlag) {
config.toolConfig = {
...config.toolConfig,
includeServerSideToolInvocations: true,
}
}
Comment thread
liramon2 marked this conversation as resolved.
Resolved
}

// Spread params object for forward compatibility
Expand Down
Loading