Skip to content

feat(models): add support for gemini server tools (#2241) - #2767

Merged
jujn merged 5 commits into
agentscope-ai:mainfrom
pony-huang:issue-2241-support-gemini-server-tools
Sep 27, 2026
Merged

jujn merged 5 commits into
agentscope-ai:mainfrom
pony-huang:issue-2241-support-gemini-server-tools

Conversation

@pony-huang

@pony-huang pony-huang commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

概述

Fixes #2241。

为 Gemini API 内置 server tools 提供端到端支持:开发者可通过 Google GenAI SDK 的 Tool 定义启用官方内置工具,AgentScope 会解析模型返回的 tool_call / tool_response 以及 code execution 专用 part,并在 ReAct 循环中跳过本地执行。

描述

  • 新增 GeminiServerTool,包装 Google GenAI SDK 构建的 Tool。SDK 已建模的 server tools 可直接启用;自定义 function tool 会被拒绝。
  • GeminiChatModel.Builder 新增 serverTools(...)。本地 function tools 与 Gemini server tools 可共存,请求会自动开启 includeServerSideToolInvocations。
  • 流式与非流式响应均解析 tool_call / tool_response,并保留 thought signature。
  • code execution 使用 executableCode / codeExecutionResult 专用 part 解析,支持成功与失败结果。
  • server tool result 保留原始 ToolResponse JSON,后续请求可恢复 Gemini 原始结果块,避免丢失 provider 专有字段。
  • grounding metadata 与 URL context metadata 会进入 ChatResponse.metadata,便于上游消费。
  • 复用 core 的 serverTool metadata 协议:ReAct 跳过本地 toolkit 执行,pending tool 恢复也不包含 server tools。
  • 已完成的 server tool 会结束本轮;未返回 result 的 server tool 会继续 reasoning,用于 pause_turn。
  • 更新中英文 Gemini 文档,补充 server tools 用法。

用法

GeminiServerTool search =
        GeminiServerTool.of(
                Tool.builder()
                        .googleSearch(
                                GoogleSearch.builder()
                                        .excludeDomains(List.of("example.com"))
                                        .build())
                        .build());

GeminiChatModel model =
        GeminiChatModel.builder()
                .apiKey(...)
                .modelName("gemini-2.5-flash")
                .serverTools(List.of(search))
                .build();

URL Context、Google Maps、Code Execution 等同理:先用对应 Google GenAI SDK builder 构造 Tool,再交给 GeminiServerTool.of(...)。

@CLAassistant

CLAassistant commented Aug 18, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@pony-huang
pony-huang force-pushed the issue-2241-support-gemini-server-tools branch from 0cc6be9 to 6eb4b10 Compare August 18, 2026 17:18
@AgentScopeJavaBot AgentScopeJavaBot added enhancement New feature or request area/core/model Model providers and formatters area/extensions agentscope-extensions (general) area/docs Documentation labels Aug 19, 2026
@oss-maintainer

Copy link
Copy Markdown
Collaborator

CLA Not Signed

The Contributor License Agreement (CLA) check is currently pending on this PR (license/cla: Contributor License Agreement is not signed yet.). This PR cannot be merged until the CLA is signed.

@pony-huang please sign the CLA via the CLA assistant badge in the comment above, or visit https://cla-assistant.io/agentscope-ai/agentscope-java. Once signed, the license/cla status will turn green.


Automated check by github-manager-bot

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Adds first-class support for Gemini provider-executed (server-side) built-in tools — Google Search / Maps / URL Context / code execution — by introducing a server flag on ToolUseBlock/ToolResultBlock, parsing tool_call/tool_response parts, keeping server results inline in the model turn, short-circuiting them away from the local toolkit, and teaching ReActAgent to recognise an all-server-turn as finished. 23 files, ~2.0k additions, of which ~800 are tests.

This is a well-structured change: the core/extension split is clean, enrichToolUseBlockWithId and ToolCallsAccumulator were both updated so the new flags survive stream accumulation (an easy thing to miss), the parallel-functionResponse merging in appendFunctionResponses is a genuine correctness improvement, and test coverage is thorough. The ReAct-loop reasoning in the isFinished comment is exactly the right framing.

Overall verdict: direction is good, but the PR currently has a merge conflict with main and the CLA is not signed, so it cannot be approved or merged as-is. Beyond those blockers, the findings above cluster on two themes: (1) server is persisted state crossing version boundaries in a multi-module codebase, so its deserialisation and naming contracts need to be pinned down explicitly, and (2) two of the new code paths (the suspended-result short-circuit in ToolExecutor, and the unresolved-server-call loop in ReActAgent) have termination/resume semantics that look unintentional and deserve either a comment or a test.

Findings

  • [Warning] ToolExecutor.java:191 — suspended result implies "awaiting external resume" and is reported as RUNNING; also appears unreachable given the new isServer() filter in getPendingToolUseIds().
  • [Warning] GeminiResponseParser.java:227 — ToolType::toString produces GOOGLE_SEARCH_WEB, but GeminiServerTool constants are google_search; request/response naming namespaces diverge.
  • [Warning] GeminiMessageConverter.java:164 — structured data round-tripped through a JSON string; the raw-text fallback changes the payload shape silently, and any intermediate text transform breaks re-parse.
  • [Warning] GeminiChatModel.java:120 — confirm the non-streaming path also applies serverTools; primitive boolean server in @JsonCreator throws on explicit JSON null for persisted state.
  • [Info] GeminiMessageConverter.java:126 — document which producer may set server=true, since it is persisted in AgentState.
  • [Info] ReActAgent.java:3293 — server call without an inline result relies on maxIters as its only termination guard; worth a test asserting intended behaviour.

Next steps

  1. Rebase onto main and resolve the conflict (this PR touches agentscope-core message model, which has moved recently — rebase, don't merge).
  2. Sign the Contributor License Agreement (see the CLA reminder comment).
  3. Address the naming-namespace and non-streaming-path questions above; the others can be follow-ups.

Feel free to @mention me for a re-review once the conflicts are resolved — happy to look again.


Automated review by github-manager-bot

// Server-side (built-in) tools are executed by the model provider itself and their
// results (if any) already arrive in the model response. Never dispatch them to the
// local toolkit, even if a local tool happens to share the same name.
if (toolCall.isServer()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning a suspended result here has a semantic that doesn't match the situation. ToolResultBlock.suspended(...) sets METADATA_SUSPENDED, which in ReActAgent routes the call into pendingPairs -> buildSuspendedMsg(...) -> GenerateReason.TOOL_SUSPENDED, and determineToolResultState() reports it as RUNNING. That path means "a human/external executor must still produce this result", but a server-side tool call is already done from the provider's side and nobody will ever resume it, so the loop can park instead of making progress.

Also note this guard looks unreachable via the normal ReAct path: getPendingToolUseIds() in this same PR already filters out isServer() blocks, so extractPendingToolCalls() never hands a server call to the executor.

Suggest either (a) dropping the guard and keeping the isServer() filter as the single source of truth, or (b) returning an error-style result (like the existing "Tool not found" branch below) so the model gets a recoverable signal instead of a suspension. If (b) is chosen, a regression test asserting the ReAct loop still terminates would be valuable.

ToolCall toolCall, byte[] thoughtSignature, List<ContentBlock> blocks) {
try {
String id = toolCall.id().orElse("tool_call_" + System.currentTimeMillis());
String name = toolCall.toolType().map(ToolType::toString).orElse("");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ToolType::toString yields the SDK enum's UPPER_SNAKE name — your own tests assert "GOOGLE_SEARCH_WEB" / "GOOGLE_MAPS" — while GeminiServerTool uses lower-case wire constants (google_search, google_map, url_context, code_execution). So the value parsed out of the response is not the same namespace as the value configured on the request, and GeminiMessageConverter later echoes tub.getName() straight back into .toolType(...).

Could you confirm the round-trip is lossless, i.e. that a response parsed as GOOGLE_SEARCH_WEB re-serialises to a toolType the API accepts? A test that asserts emitted request part == parsed response part for each supported tool type would lock this down and prevent a silent "server tool call disappears on turn 2" bug. Ideally there would be a single canonical naming source shared by GeminiServerTool and the parser.

try {
// The parser serializes the tool response map to a JSON string, so
// parse it back rather than converting the raw string value.
responseMap = JsonUtils.getJsonCodec().fromJson(textOutput, Map.class);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This round-trips structured data through a JSON string: parseToolResponse serialises toolResponse.response() into a single TextBlock, and here you parse it back to satisfy Gemini's "response must be an object" contract.

Two concerns:

  1. The fallback Map.of("output", textOutput) silently changes the payload shape the provider expects, so a parse failure degrades into a wrong-but-valid request rather than a visible error. Worth at least distinguishing "text was not a JSON object" from "text was corrupted", or logging at error level.
  2. Any intermediate transformation of that text block (context compaction, memory flush, sanitisation, truncation of long grounding results) will break the re-parse. Since ToolResultBlock is a general message model shared with harness/distribution, storing the raw map in metadata (or as a dedicated block type) and only rendering text for display would be more robust.

Minor: fromJson(textOutput, Map.class) is a raw type and needs @SuppressWarnings("unchecked") or a TypeReference<Map<String, Object>> for consistency with the rest of the codebase.

ToolCall toolCall =
ToolCall.builder()
.id(tub.getId())
.toolType(tub.getName())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit on symmetry: for local calls you keep id/name, here toolType is fed from tub.getName() (see the parser comment about GOOGLE_SEARCH_WEB vs google_search). If a server tool call ever reaches this path without going through parseToolCall — e.g. a session restored from an older persisted state where server defaulted to false, or a locally registered tool that happens to share a built-in tool's name — the request shape silently changes between functionCall and toolCall.

Consider documenting which producer is allowed to set server=true, since it is persisted in AgentState and therefore crosses version boundaries.

// If there are tool calls (even non-existent ones), continue to acting phase
// where ToolExecutor will return "Tool not found" error for the model to see
return toolCalls.isEmpty();
if (toolCalls.isEmpty()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice that the mixed local/server case is handled. One edge to confirm: when a server tool call arrives without an inline result (the pause_turn case in your comment), isFinished returns false, getPendingToolUseIds() excludes it, so acting() sees an empty pendingToolCalls and falls through to executeIteration(iter + 1) — an extra model round-trip whose only termination guard is maxIters.

Is that intentional, and is it bounded in practice? If the provider can answer again with the same unresolved server call, this becomes maxIters wasted requests. A test covering "server call with no result" (asserting iteration count / final reason) would make the intended behaviour explicit, and the Javadoc here could state who is responsible for terminating the pause_turn loop.

GenerateOptions defaultOptions,
Formatter<Content, GenerateContentResponse, GenerateContentConfig.Builder> formatter) {
Formatter<Content, GenerateContentResponse, GenerateContentConfig.Builder> formatter,
List<GeminiServerTool> serverTools) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Plumbing check: serverTools is only applied inside buildGenerateContentConfig, which is reached solely from doStream. Please confirm the non-streaming path (streamEnabled == false) and any other request-building site (token counting, formatter defaults) go through the same method — otherwise built-in tools are configured on the model but silently ignored for non-streaming calls, which is a confusing failure mode given Builder.serverTools(...) advertises unconditional support.

Also: @JsonProperty("server") boolean server on the ToolUseBlock/ToolResultBlock @JsonCreator is a primitive. Missing field in old persisted state deserialises to false (good), but an explicit JSON null throws for primitives. Since these blocks are stored by AgentStateStore implementations across harness/distribution, a @Nullable Boolean normalised in the constructor would be safer — plus a deserialisation test for a pre-change state JSON document.

@oss-maintainer

This comment was marked as abuse.

oss-maintainer

This comment was marked as abuse.

@jujn
jujn merged commit f98a685 into agentscope-ai:main Sep 27, 2026
6 checks passed
@jujn jujn mentioned this pull request Sep 27, 2026
3 tasks done
wzl521 added a commit to wzl521/agentscope-java that referenced this pull request Oct 4, 2026
…tscope-ai#2767)

Integrate upstream server-side tool support with this branch's thinking +
thought-signature persistence:

- GeminiMessageConverter: keep both modelRole signature replay and
  upstream's functionResponseParts queue; ToolUseBlock signatures go
  through GeminiThoughtSignatureUtils.applyMetadata (tolerant of
  empty/corrupt values); upstream's applyThoughtSignature stays for the
  code-execution / server-tool result paths.
- GeminiResponseParser: port upstream's executableCode,
  codeExecutionResult, toolCall and toolResponse handling into the
  metadata-based parsePartsToBlocks flow; byte[] overloads kept as
  deprecated source-compat shims delegating to metadata variants.
- Docs: keep both the Thinking and Server-side tools sections (en/zh).

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core/model Model providers and formatters area/docs Documentation area/extensions agentscope-extensions (general) enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Gemini 内置工具支持

5 participants