Repository navigation
feat(models): add support for gemini server tools (#2241) - #2767
Conversation
0cc6be9 to
6eb4b10
Compare
|
CLA Not Signed The Contributor License Agreement (CLA) check is currently pending on this PR ( @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 Automated check by github-manager-bot |
oss-maintainer
left a comment
There was a problem hiding this comment.
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 asRUNNING; also appears unreachable given the newisServer()filter ingetPendingToolUseIds(). - [Warning]
GeminiResponseParser.java:227—ToolType::toStringproducesGOOGLE_SEARCH_WEB, butGeminiServerToolconstants aregoogle_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 appliesserverTools; primitiveboolean serverin@JsonCreatorthrows on explicit JSONnullfor persisted state. - [Info]
GeminiMessageConverter.java:126— document which producer may setserver=true, since it is persisted inAgentState. - [Info]
ReActAgent.java:3293— server call without an inline result relies onmaxItersas its only termination guard; worth a test asserting intended behaviour.
Next steps
- Rebase onto
mainand resolve the conflict (this PR touchesagentscope-coremessage model, which has moved recently — rebase, don't merge). - Sign the Contributor License Agreement (see the CLA reminder comment).
- 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()) { |
There was a problem hiding this comment.
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(""); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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:
- 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. - Any intermediate transformation of that text block (context compaction, memory flush, sanitisation, truncation of long grounding results) will break the re-parse. Since
ToolResultBlockis a general message model shared with harness/distribution, storing the raw map inmetadata(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()) |
There was a problem hiding this comment.
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()) { |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
This comment was marked as abuse.
This comment was marked as abuse.
…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]>
概述
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。executableCode/codeExecutionResult专用 part 解析,支持成功与失败结果。ToolResponseJSON,后续请求可恢复 Gemini 原始结果块,避免丢失 provider 专有字段。ChatResponse.metadata,便于上游消费。serverToolmetadata 协议:ReAct 跳过本地 toolkit 执行,pending tool 恢复也不包含 server tools。pause_turn。用法
URL Context、Google Maps、Code Execution 等同理:先用对应 Google GenAI SDK builder 构造
Tool,再交给GeminiServerTool.of(...)。