Skip to content

Migrate to the Google GenAI SDK - #1260

Merged
isamu merged 1 commit into
receptron:mainfrom
masap:fix-1259
Jan 17, 2026
Merged

isamu merged 1 commit into
receptron:mainfrom
masap:fix-1259

Conversation

@masap

@masap masap commented Jan 17, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #1259.

According to official document [1], Google recommend us to migrate to new SDK.

[1] https://ai.google.dev/gemini-api/docs/migrate

Summary by CodeRabbit

  • Chores
    • Updated Gemini agent to use the Google GenAI SDK for improved compatibility and modernized API usage.
  • Bug Fixes
    • Improved streaming and non-stream response handling to ensure more reliable final responses and graceful fallbacks.
    • Normalized tool and safety configuration handling for consistent behavior.
  • Tests
    • Updated test types and callbacks to align with the new SDK behaviors.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 17, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Migrates the Gemini agent from the deprecated @google/generative-ai SDK to the new @google/genai SDK, updating imports, instantiation, response access (methods → properties), chat creation/streaming flows, tool handling, and test/schema usages across source, lib, package, and test files.

Changes

Cohort / File(s) Summary
Gemini Agent Source & Compiled
llm_agents/gemini_agent/src/gemini_agent.ts, llm_agents/gemini_agent/lib/gemini_agent.js
Replace @google/generative-ai with @google/genai; instantiate new GoogleGenAI({ apiKey }); convert response method calls to property access (text() → text, functionCalls() → functionCalls); build generationConfig (including tools) and use ai.chats.create(); update streaming to chat.sendMessageStream({ message }) with chunk iteration and finalResponse handling; normalize tool_calls and safety settings.
Gemini Agent Dependency
llm_agents/gemini_agent/package.json
Update dependency from @google/generative-ai@^0.24.1 to @google/genai@^1.37.0.
Gemini Agent Tests
llm_agents/gemini_agent/tests/run_gemini.ts
Replace SchemaType import with Type from @google/genai; adjust streamTokenCallback signature/logging to accept data: any; convert schema type references SchemaType.* → Type.*.

Sequence Diagram(s)

mermaid
sequenceDiagram
participant Client
participant GeminiAgent
participant GoogleGenAI
participant ToolRegistry
Client->>GeminiAgent: request with messages, tools, stream option
GeminiAgent->>GoogleGenAI: ai.chats.create(model, generationConfig)
Note over GoogleGenAI,ToolRegistry: generationConfig may include tools (function declarations)
GeminiAgent->>GoogleGenAI: sendMessageStream({ message }) --streaming-->
loop chunk stream
GoogleGenAI-->>GeminiAgent: chunk (text, partial metadata)
GeminiAgent->>Client: streamTokenCallback(progress token)
end
GoogleGenAI-->>GeminiAgent: finalResponse
GeminiAgent->>Client: convertOpenAIChatCompletion(finalResponse) / return result

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped from old SDKs through code so spry,
Swapped imports, trimmed methods, let properties fly,
Streams now chatter in tidy, flowing streams,
Tools tucked into configs to chase new dreams,
A little rabbit cheers — migration done with a sigh!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Migrate to the Google GenAI SDK' clearly and accurately describes the main objective of the changeset - replacing the Google Generative AI SDK with the Google GenAI SDK across multiple files.
Linked Issues check ✅ Passed The PR successfully implements the migration to Google GenAI SDK as required by issue #1259, including updated imports, API access patterns, configuration handling, and public API signatures across all affected files.
Out of Scope Changes check ✅ Passed All changes are directly related to the SDK migration objective. The modifications consistently update dependencies, imports, API calls, and type references from @google/generative-ai to @google/genai throughout the codebase with no extraneous changes detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
llm_agents/gemini_agent/src/gemini_agent.ts (1)

164-203: Streaming path loses earlier chunks due to incremental delta behavior.
The @google/genai SDK's sendMessageStream yields incremental deltas (each chunk contains only newly generated text since the previous chunk), not cumulative responses. The current code overwrites finalResponse on each iteration, keeping only the final chunk and losing all earlier content. This results in incomplete text and tool calls in the final conversion.

Accumulate text/function calls across chunks before converting, or verify if the SDK provides a final aggregated response object accessible after streaming completes.

🛠️ Potential fix (adjust to match actual SDK API)
     const result = await chat.sendMessageStream({ message: lastMessage.content });
 
     let finalResponse: GenerateContentResponse | undefined;
+    let fullText = "";
 
     for await (const chunk of result) {
       llmMetaDataFirstTokenTime(llmMetaData);
-      const chunkText = chunk.text;
+      const chunkText = chunk.text ?? "";
+      fullText += chunkText;
       // TODO: Fix to handle all the function calls
       finalResponse = chunk;
🤖 Fix all issues with AI agents
In `@llm_agents/gemini_agent/package.json`:
- Line 30: Package.json lists an invalid `@google/genai` version (^1.37.0); update
the dependency entry for "@google/genai" to "^1.34.0", run package manager to
regenerate the lockfile (npm/yarn/pnpm install) and commit the updated lockfile,
and verify the package.json "engines" field permits Node.js 20+ so `@google/genai`
can install and run correctly.
♻️ Duplicate comments (1)
llm_agents/gemini_agent/lib/gemini_agent.js (1)

119-155: Duplicate: streaming final-response aggregation issue.
Same concern as in llm_agents/gemini_agent/src/gemini_agent.ts; fix in source and recompile this file.

"homepage": "https://github.com/receptron/graphai/blob/main/llm_agents/gemini_agent/README.md",
"dependencies": {
"@google/generative-ai": "^0.24.1",
"@google/genai": "^1.37.0",

@coderabbitai coderabbitai Bot Jan 17, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🌐 Web query:

@google/genai npm latest version Node.js requirements

💡 Result:

As of January 17, 2026:

  • Latest @google/genai npm version: 1.34.0. [1]
  • Node.js requirement: Node.js 20 or later. [2]

References:
[1] Package info (registry/analysis): @google/genai — latest 1.34.0.
[2] Google Gen AI JS SDK docs — Prerequisites: Node.js version 20 or later.


🏁 Script executed:

# Find package.json files and check Node.js engine requirements
find . -name "package.json" -type f | head -20 | xargs grep -l "engines" 2>/dev/null

# Check the main gemini_agent package.json for engines field
cat llm_agents/gemini_agent/package.json | jq '.engines' 2>/dev/null || grep -A 2 '"engines"' llm_agents/gemini_agent/package.json

# Check for lockfiles
ls -la llm_agents/gemini_agent/package-lock.json llm_agents/gemini_agent/yarn.lock 2>/dev/null || echo "No lockfiles found in gemini_agent"

Repository: receptron/graphai

Length of output: 178


Version 1.37.0 does not exist—update to latest @google/genai 1.34.0.

The specified version ^1.37.0 is invalid; the latest available release is 1.34.0. Update the dependency to ^1.34.0 and ensure the lockfile is regenerated. Also verify that your Node.js engine constraint supports Node.js 20 or later, as required by @google/genai.

🤖 Prompt for AI Agents
In `@llm_agents/gemini_agent/package.json` at line 30, Package.json lists an
invalid `@google/genai` version (^1.37.0); update the dependency entry for
"@google/genai" to "^1.34.0", run package manager to regenerate the lockfile
(npm/yarn/pnpm install) and commit the updated lockfile, and verify the
package.json "engines" field permits Node.js 20+ so `@google/genai` can install
and run correctly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

🌐 Web query:

`@google/genai` npm latest version January 2026

💡 Result:

The latest @google/genai npm version (as of January 17, 2026) is 1.34.0. [1][2]

Sources:

  • Package listing (Socket): @google/genai — 1.34.0 (latest). [1]
  • Official Google Gen AI SDK docs / install instructions. [2]

@masap, you're absolutely right—I apologize for the incorrect review comment. Version 1.37.0 is indeed available and was just released. My search results were outdated and didn't reflect the latest npm registry data. Thank you for the correction and for providing the link!

The dependency version ^1.37.0 is correct as specified in the PR.

🐰💭
/)_/)
(o.o)
/>📦 learns to check npm directly!

@ystknsh

ystknsh commented Jan 17, 2026

Copy link
Copy Markdown
Contributor

@masap
Thank you for the pull request!

There are merge conflicts in yarn.lock that need to be resolved before we can merge.

Could you please resolve them?

Resolves receptron#1259.

According to official document [1], Google recommend us to migrate to new SDK.

[1] https://ai.google.dev/gemini-api/docs/migrate

Signed-off-by: Masashi Honma <[email protected]>
@masap

masap commented Jan 17, 2026

Copy link
Copy Markdown
Contributor Author

@ystknsh

There are merge conflicts in yarn.lock that need to be resolved before we can merge.
Could you please resolve them?

Sure, fixed.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
llm_agents/gemini_agent/src/gemini_agent.ts (2)

164-204: Use GenAI's aggregated final response instead of the last streaming chunk.

The sendMessageStream API returns both a stream of chunks and a response Promise that resolves to the final aggregated GenerateContentResponse. The current implementation discards this aggregated response and instead uses the last chunk, which may not be complete or correctly formatted for convertOpenAIChatCompletion. Await result.response and pass that to convertOpenAIChatCompletion rather than the last chunk.


112-154: Fix tools structure and add missing toolConfig for function-calling.

The code wraps tools in { functionDeclarations: ... }, but the @google/genai SDK expects tools to be a direct array of FunctionDeclaration objects. Additionally, a toolConfig with functionCallingConfig (mode, allowedFunctionNames) must be passed to ai.chats.create() for function-calling to work. Update:

const chat = ai.chats.create({
  model: model || "gemini-2.5-flash",
  config: generationConfig,
  tools: functions,  // Direct array, not wrapped
  toolConfig: {
    functionCallingConfig: {
      mode: FunctionCallingConfigMode.AUTO, // or other mode
    },
  },
  history: messagesCopy.map(...)
});

The response_format structure (responseMimeType + responseSchema) is valid and correctly positioned in generationConfig; consider uncommenting and implementing it to allow JSON schema validation.

🧹 Nitpick comments (2)
llm_agents/gemini_agent/lib/gemini_agent.js (2)

119-155: Use aggregated response from result.response instead of last stream chunk.
The @google/genai SDK exposes result.response as an aggregated final response promise. Prefer passing this to convertOpenAIChatCompletion() instead of the last chunk from the stream iteration. Additionally, the TODO flags incomplete function-call handling—ensure the aggregated response captures all tool calls.


70-110: Generation config and tools structure are correct; track the response_format TODO.

The generationConfig field names (temperature, maxOutputTokens, safetySettings) and the tools: [{ functionDeclarations }] structure match the official Google Generative AI JavaScript SDK specifications.

The response_format TODO is still valid—responseMimeType and responseSchema are supported GenerationConfig fields. If implementing structured output, note that the commented code references modelParams.generationConfig, which should be just generationConfig as shown in the rest of the code.

@ystknsh

ystknsh commented Jan 17, 2026

Copy link
Copy Markdown
Contributor

@masap Thanks for the quick fix!

@isamu
isamu merged commit e75f8b7 into receptron:main Jan 17, 2026
@masap
masap deleted the fix-1259 branch January 17, 2026 22:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Migrate to the Google GenAI SDK

3 participants