Add tool/function calling support for Google Gemini adapter#147
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
WalkthroughAdds ToolFormatter, integrates tool-call serialization and extraction into GoogleGeminiChatAdapter (request and streaming paths), expands EXPECTED_ROLES to include TOOL, updates PHPStan baseline, and adds unit tests covering formatting and adapter tool-call behavior. ChangesGemini tool-call support
Sequence DiagramsequenceDiagram
participant Client
participant GoogleGeminiChatAdapter
participant ToolFormatter
participant GoogleGeminiAPI
participant ResponseBuilder
Client->>GoogleGeminiChatAdapter: create(request with tools)
GoogleGeminiChatAdapter->>ToolFormatter: formatTools(tools)
ToolFormatter-->>GoogleGeminiChatAdapter: formatted functionDeclarations
GoogleGeminiChatAdapter->>GoogleGeminiAPI: generateContent(request with tools)
GoogleGeminiAPI-->>GoogleGeminiChatAdapter: GenerateContentResponse (parts)
GoogleGeminiChatAdapter->>GoogleGeminiChatAdapter: extractToolCalls(response)
GoogleGeminiChatAdapter->>ResponseBuilder: build AIChatResponseMessage(text, toolCalls)
ResponseBuilder-->>Client: AIChatResponseMessage (including tool calls)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/google-gemini-adapter/src/Chat/ToolFormatter.php`:
- Around line 158-164: The checks for $parameter->enum and $parameter->format
use loose truthy checks; update them to strict comparisons (e.g., !== null and
!== [] as appropriate) so that in the ToolFormatter logic you only set
$param['enum'] and $param['format'] when the parameter properties are explicitly
present—locate the code in ToolFormatter.php where $parameter->enum and
$parameter->format are inspected and replace the if ($parameter->enum) / if
($parameter->format) conditions with strict non-null/empty checks (referencing
the $parameter variable and $param array in that block).
🧹 Nitpick comments (4)
packages/google-gemini-adapter/src/Chat/GoogleGeminiChatAdapter.php (2)
80-87: TODO comments have misleading indentation.Lines 82-83 and 86-87 are logically inside their respective
elseifbranches but are flush-left, which makes them look like they sit between the branches rather than inside them. This could confuse future contributors trying to understand the control flow.🔧 Indent the TODO comments to match their enclosing block
} elseif ($part instanceof ToolCallsPart) { @\trigger_error('Tool calls are not yet supported by the Google Gemini PHP SDK. Tool calls will be ignored.', \E_USER_WARNING); - // TODO: Implement when SDK supports function calls - // Format: ['functionCall' => ['name' => $tool->name, 'args' => $tool->arguments]] + // TODO: Implement when SDK supports function calls + // Format: ['functionCall' => ['name' => $tool->name, 'args' => $tool->arguments]] } elseif ($part instanceof ToolCallPart) { @\trigger_error('Tool call results are not yet supported by the Google Gemini PHP SDK. Tool results will be ignored.', \E_USER_WARNING); - // TODO: Implement when SDK supports function responses - // Format: ['functionResponse' => ['name' => $part->toolName, 'response' => ['content' => $part->content]]] + // TODO: Implement when SDK supports function responses + // Format: ['functionResponse' => ['name' => $part->toolName, 'response' => ['content' => $part->content]]]
162-177: Suppress PHPMD warning for the intentionally unused$resultparameter.PHPMD flags
$resultas unused (static analysis hint confirms). Since this is a deliberate placeholder for future SDK support, consider suppressing the warning to keep the baseline clean.🔧 Add SuppressWarnings annotation
/** * Extract tool calls from the response. * * `@return` AIChatToolCall[] + * + * `@SuppressWarnings`(PHPMD.UnusedFormalParameter) */ private function extractToolCalls(GenerateContentResponse $result): arraypackages/google-gemini-adapter/src/Chat/ToolFormatter.php (2)
111-143: Use specific exception classes instead of generic\Exception.The coding guidelines require exception hierarchies with specific exception classes. Lines 113 and 142 throw generic
\Exception. Consider creating anInvalidParameterExceptionor using\InvalidArgumentExceptionwhich better describes the error condition (invalid input configuration).Proposed fix
- throw new \Exception('Array type parameter must have items description. Define a type or use the Parameter class for object.'); + throw new \InvalidArgumentException('Array type parameter must have items description. Define a type or use the Parameter class for object.');- throw new \Exception('Object type parameter must have properties description. You need to pass an array of Parameter.'); + throw new \InvalidArgumentException('Object type parameter must have properties description. You need to pass an array of Parameter.');Note: The test expectations in
ToolFormatterTest.php(lines 287 and 305) would also need updating to expect\InvalidArgumentException. As per coding guidelines: "Use exception hierarchies with specific exception classes for error handling."
174-181: Silent fallback toSTRINGfor unknown types may mask bugs.The
default => 'STRING'branch silently converts any unrecognized type (e.g.,number,float) toSTRING. Consider throwing an exception for unmapped types to surface configuration errors early, or at minimum add'number' => 'NUMBER'since it's a common JSON Schema type.
Implement function calling against the Google Gemini PHP SDK on top of the structured-output support from #148: - ToolFormatter converts ToolInfo into typed Gemini\Data\Tool / FunctionDeclaration / Schema objects (correct nullable handling via the Schema nullable flag, NUMBER type, and dropping formats Gemini rejects). - GoogleGeminiChatAdapter sends tools via withTool/withToolConfig, maps ToolCallsPart/ToolCallPart to functionCall/functionResponse parts, accepts the TOOL role (mapped to the Gemini user role), and parses functionCall parts from responses into AIChatToolCall. - Tool calls are extracted before reading text, so function-call responses no longer trip the single-part text() accessor and get misreported as blocked by safety settings. - Add unit tests for the typed formatter output and the tool round-trip.
5bfc317 to
587c9e1
Compare
This commit implements tool support for the Google Gemini adapter, preparing it for function calling capabilities once the SDK adds support.
Changes:
Note: The current Google Gemini PHP SDK (v1.0.15) does not yet support function calling. User warnings are triggered when tools are used until SDK support is available. The implementation is ready and will work immediately once the SDK is updated.
Summary by CodeRabbit
New Features
Tests
Chores