Skip to content

refactor: 使用Google官方SDK重构gemini_source #1228

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Apr 15, 2025

Conversation

Raven95676
Copy link
Member

@Raven95676 Raven95676 commented Apr 10, 2025

Motivation

优化gemini原生调用在astrbot的表现

Modifications

使用Google官方SDK重构gemini_source

Check

  • 我的 Commit Message 符合良好的规范
  • 我新增/修复/优化的功能经过良好的测试

好的,这是翻译成中文的 pull request 总结:

Sourcery 总结

重构 Gemini 源代码实现,使用官方 Google SDK 以改进集成和可靠性

增强功能:

  • 使用 Google 官方 genai SDK 替换自定义 HTTP 客户端实现
  • 改进错误处理和安全设置映射
  • 增强 Gemini API 交互的类型处理

杂项:

  • 更新 import 语句
  • 简化客户端初始化和方法调用
Original summary in English

Summary by Sourcery

Refactor the Gemini source implementation to use the official Google SDK for improved integration and reliability

Enhancements:

  • Replace custom HTTP client implementation with Google's official genai SDK
  • Improve error handling and safety settings mapping
  • Enhance type handling for Gemini API interactions

Chores:

  • Update import statements
  • Simplify client initialization and method calls

Copy link

sourcery-ai bot commented Apr 10, 2025

Sourcery 评审指南

此拉取请求重构了 Gemini 源代码实现,以使用官方 Google genai SDK。此更改提高了 Gemini 提供程序的集成性、可靠性和可维护性。它包括对错误处理、安全设置和会话有效负载准备的增强。这些更改还确保与 Gemini API 的多模态输出和工具调用功能兼容。

与 Google Gemini API 进行文本聊天的序列图

sequenceDiagram
    participant User
    participant ProviderGoogleGenAI
    participant GoogleGenAIClient
    participant GeminiAPI

    User->>ProviderGoogleGenAI: text_chat(prompt, image_urls, func_tool, contexts, system_prompt, tool_calls_result, **kwargs)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: assemble_context(prompt, image_urls)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _prepare_query_config(tools, system_instruction, temperature, modalities)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _prepare_conversation(payloads)
    ProviderGoogleGenAI->>GoogleGenAIClient: models.generate_content(model, contents, config)
    GoogleGenAIClient->>GeminiAPI: generateContent(model, contents, config)
    GeminiAPI-->>GoogleGenAIClient: Response
    GoogleGenAIClient-->>ProviderGoogleGenAI: GenerateContentResponse
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _process_content_parts(result, llm_response)
    ProviderGoogleGenAI-->>User: LLMResponse
Loading

与 Google Gemini API 进行流式文本聊天的序列图

sequenceDiagram
    participant User
    participant ProviderGoogleGenAI
    participant GoogleGenAIClient
    participant GeminiAPI

    User->>ProviderGoogleGenAI: text_chat_stream(prompt, image_urls, func_tool, contexts, system_prompt, tool_calls_result, **kwargs)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: assemble_context(prompt, image_urls)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _prepare_query_config(tools, system_instruction, temperature)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _prepare_conversation(payloads)
    ProviderGoogleGenAI->>GoogleGenAIClient: models.generate_content_stream(model, contents, config)
    GoogleGenAIClient->>GeminiAPI: generateContentStream(model, contents, config)
    GeminiAPI-->>GoogleGenAIClient: Stream of responses
    loop For each chunk in stream
        GoogleGenAIClient-->>ProviderGoogleGenAI: Chunk
        ProviderGoogleGenAI->>ProviderGoogleGenAI: _process_content_parts(chunk, llm_response)
        ProviderGoogleGenAI-->>User: LLMResponse (chunk)
    end
    ProviderGoogleGenAI-->>User: LLMResponse (final)
Loading

ProviderGoogleGenAI 的更新类图

classDiagram
    class ProviderGoogleGenAI {
        -api_keys: List[str]
        -chosen_api_key: str
        -timeout: int
        -api_base: Optional[str]
        -client: genai.Client
        -safety_settings: List[types.SafetySetting]
        +__init__(provider_config: dict, db_helper: BaseDatabase, default_persona: Personality)
        +_init_client() : void
        +_init_safety_settings() : void
        +_handle_api_error(e: APIError, keys: List[str]) : bool
        +_prepare_query_config(tools: Optional[FuncCall], system_instruction: Optional[str], temperature: Optional[float], modalities: Optional[List[str]]) : types.GenerateContentConfig
        +_prepare_conversation(payloads: Dict) : List[types.Content]
        +_process_content_parts(result: types.GenerateContentResponse, llm_response: LLMResponse) : MessageChain
        +_query(payloads: dict, tools: FuncCall, temperature: float) : LLMResponse
        +_query_stream(payloads: dict, tools: FuncCall, temperature: float) : AsyncGenerator[LLMResponse, None]
        +text_chat(prompt: str, session_id: str, image_urls: List[str], func_tool: FuncCall, contexts: List[Dict], system_prompt: str, tool_calls_result: ToolCallsResult, **kwargs) : LLMResponse
        +text_chat_stream(prompt: str, session_id: str, image_urls: List[str], func_tool: FuncCall, contexts: List[Dict], system_prompt: str, tool_calls_result: ToolCallsResult, **kwargs) : AsyncGenerator[LLMResponse, None]
        +get_models() : List[str]
        +get_current_key() : str
        +get_keys() : List[str]
        +set_key(key: str) : void
        +assemble_context(text: str, image_urls: List[str]) : Dict
        +terminate() : void
    }
    note for ProviderGoogleGenAI "Refactored to use Google's official genai SDK"
Loading

文件级别更改

变更 详情 文件
使用官方 Google genai SDK 替换了自定义 HTTP 客户端实现,以与 Gemini API 交互。
  • 删除了 SimpleGoogleGenAIClient 类。
  • 导入了 google.genai 库。
  • 使用 genai.Client 初始化了 Gemini 客户端。
  • 配置了客户端的 HTTP 选项,包括基本 URL 和超时。
  • 利用官方 SDK 方法生成内容和流式传输内容。
astrbot/core/provider/sources/gemini_source.py
改进了错误处理和 API 密钥管理。
  • 实现了 API 错误的错误处理,包括速率限制和无效的 API 密钥。
  • 添加了逻辑,以便在当前 API 密钥无效或受到速率限制时自动切换到其他 API 密钥。
  • 实现了 API 调用的重试逻辑。
  • 添加了 API 错误和密钥切换的日志记录。
astrbot/core/provider/sources/gemini_source.py
增强了安全设置配置和映射。
  • 创建了危害类别和阈值到 Google genai SDK 中相应的 types.HarmCategorytypes.HarmBlockThreshold 枚举的映射。
  • 根据提供程序配置初始化了安全设置。
  • 将安全设置应用于 GenerateContentConfig
astrbot/core/provider/sources/gemini_source.py
改进了 Gemini API 的会话有效负载的准备。
  • 创建了 _prepare_conversation 方法,以将内部消息格式转换为 Gemini SDK 要求的 types.Content 格式。
  • 适当地处理了不同的消息角色(用户、助手、工具)和内容类型(文本、图像)。
  • 添加了对工具调用和函数响应的支持。
  • 为空文本内容和助手消息添加了警告日志。
astrbot/core/provider/sources/gemini_source.py
重构了查询和流式查询方法以使用官方 Google genai SDK。
  • 用官方 SDK 方法替换了自定义 HTTP 客户端调用,以生成内容和流式传输内容。
  • 更新了方法签名以匹配 SDK 要求。
  • 处理了来自 API 的响应,并将其转换为内部 LLMResponse 格式。
  • 实现了处理多模态输出(文本和图像)的逻辑。
  • 实现了通过增加温度并重试请求来处理 RECITATION 完成原因的逻辑。
astrbot/core/provider/sources/gemini_source.py
更新了 assemble_context 方法以处理图像 URL 和文本提示。
  • 修改了 assemble_context 方法,以在仅提供图像 URL 时包含默认文本“[图片]”。
  • 更新了 entities.pyopenai_source.py 中的 assemble_context 方法,以在仅提供图像 URL 时包含默认文本“[图片]”。
astrbot/core/provider/sources/gemini_source.py
astrbot/core/provider/entities.py
astrbot/core/provider/sources/openai_source.py

提示和命令

与 Sourcery 互动

  • 触发新的审查: 在拉取请求上评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的审查评论。
  • 从审查评论生成 GitHub 问题: 要求 Sourcery 从审查评论创建一个问题,方法是回复它。您也可以回复审查评论并使用 @sourcery-ai issue 从该评论创建一个问题。
  • 生成拉取请求标题: 在拉取请求标题中的任何位置写入 @sourcery-ai 以随时生成标题。您也可以在拉取请求上评论 @sourcery-ai title 以随时(重新)生成标题。
  • 生成拉取请求摘要: 在拉取请求正文中的任何位置写入 @sourcery-ai summary 以随时在您想要的位置生成 PR 摘要。您也可以在拉取请求上评论 @sourcery-ai summary 以随时(重新)生成摘要。
  • 生成审查员指南: 在拉取请求上评论 @sourcery-ai guide 以随时(重新)生成审查员指南。
  • 解决所有 Sourcery 评论: 在拉取请求上评论 @sourcery-ai resolve 以解决所有 Sourcery 评论。如果您已经解决了所有评论并且不想再看到它们,这将非常有用。
  • 驳回所有 Sourcery 审查: 在拉取请求上评论 @sourcery-ai dismiss 以驳回所有现有的 Sourcery 审查。如果您想重新开始新的审查,这将特别有用 - 不要忘记评论 @sourcery-ai review 以触发新的审查!
  • 为问题生成行动计划: 在问题上评论 @sourcery-ai plan 以生成行动计划。

自定义您的体验

访问您的 仪表板 以:

  • 启用或禁用审查功能,例如 Sourcery 生成的拉取请求摘要、审查员指南等。
  • 更改审查语言。
  • 添加、删除或编辑自定义审查说明。
  • 调整其他审查设置。

获得帮助

Original review guide in English

Reviewer's Guide by Sourcery

This pull request refactors the Gemini source implementation to use the official Google genai SDK. This change improves the integration, reliability, and maintainability of the Gemini provider. It includes enhancements to error handling, safety settings, and conversation payload preparation. The changes also ensure compatibility with multi-modal outputs and tool calling features of the Gemini API.

Sequence diagram for text chat with Google Gemini API

sequenceDiagram
    participant User
    participant ProviderGoogleGenAI
    participant GoogleGenAIClient
    participant GeminiAPI

    User->>ProviderGoogleGenAI: text_chat(prompt, image_urls, func_tool, contexts, system_prompt, tool_calls_result, **kwargs)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: assemble_context(prompt, image_urls)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _prepare_query_config(tools, system_instruction, temperature, modalities)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _prepare_conversation(payloads)
    ProviderGoogleGenAI->>GoogleGenAIClient: models.generate_content(model, contents, config)
    GoogleGenAIClient->>GeminiAPI: generateContent(model, contents, config)
    GeminiAPI-->>GoogleGenAIClient: Response
    GoogleGenAIClient-->>ProviderGoogleGenAI: GenerateContentResponse
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _process_content_parts(result, llm_response)
    ProviderGoogleGenAI-->>User: LLMResponse
Loading

Sequence diagram for streaming text chat with Google Gemini API

sequenceDiagram
    participant User
    participant ProviderGoogleGenAI
    participant GoogleGenAIClient
    participant GeminiAPI

    User->>ProviderGoogleGenAI: text_chat_stream(prompt, image_urls, func_tool, contexts, system_prompt, tool_calls_result, **kwargs)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: assemble_context(prompt, image_urls)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _prepare_query_config(tools, system_instruction, temperature)
    ProviderGoogleGenAI->>ProviderGoogleGenAI: _prepare_conversation(payloads)
    ProviderGoogleGenAI->>GoogleGenAIClient: models.generate_content_stream(model, contents, config)
    GoogleGenAIClient->>GeminiAPI: generateContentStream(model, contents, config)
    GeminiAPI-->>GoogleGenAIClient: Stream of responses
    loop For each chunk in stream
        GoogleGenAIClient-->>ProviderGoogleGenAI: Chunk
        ProviderGoogleGenAI->>ProviderGoogleGenAI: _process_content_parts(chunk, llm_response)
        ProviderGoogleGenAI-->>User: LLMResponse (chunk)
    end
    ProviderGoogleGenAI-->>User: LLMResponse (final)
Loading

Updated class diagram for ProviderGoogleGenAI

classDiagram
    class ProviderGoogleGenAI {
        -api_keys: List[str]
        -chosen_api_key: str
        -timeout: int
        -api_base: Optional[str]
        -client: genai.Client
        -safety_settings: List[types.SafetySetting]
        +__init__(provider_config: dict, db_helper: BaseDatabase, default_persona: Personality)
        +_init_client() : void
        +_init_safety_settings() : void
        +_handle_api_error(e: APIError, keys: List[str]) : bool
        +_prepare_query_config(tools: Optional[FuncCall], system_instruction: Optional[str], temperature: Optional[float], modalities: Optional[List[str]]) : types.GenerateContentConfig
        +_prepare_conversation(payloads: Dict) : List[types.Content]
        +_process_content_parts(result: types.GenerateContentResponse, llm_response: LLMResponse) : MessageChain
        +_query(payloads: dict, tools: FuncCall, temperature: float) : LLMResponse
        +_query_stream(payloads: dict, tools: FuncCall, temperature: float) : AsyncGenerator[LLMResponse, None]
        +text_chat(prompt: str, session_id: str, image_urls: List[str], func_tool: FuncCall, contexts: List[Dict], system_prompt: str, tool_calls_result: ToolCallsResult, **kwargs) : LLMResponse
        +text_chat_stream(prompt: str, session_id: str, image_urls: List[str], func_tool: FuncCall, contexts: List[Dict], system_prompt: str, tool_calls_result: ToolCallsResult, **kwargs) : AsyncGenerator[LLMResponse, None]
        +get_models() : List[str]
        +get_current_key() : str
        +get_keys() : List[str]
        +set_key(key: str) : void
        +assemble_context(text: str, image_urls: List[str]) : Dict
        +terminate() : void
    }
    note for ProviderGoogleGenAI "Refactored to use Google's official genai SDK"
Loading

File-Level Changes

Change Details Files
Replaced the custom HTTP client implementation with the official Google genai SDK for interacting with the Gemini API.
  • Removed the SimpleGoogleGenAIClient class.
  • Imported the google.genai library.
  • Initialized the Gemini client using genai.Client.
  • Configured HTTP options for the client, including the base URL and timeout.
  • Utilized the official SDK methods for generating content and streaming content.
astrbot/core/provider/sources/gemini_source.py
Improved error handling and API key management.
  • Implemented error handling for API errors, including rate limits and invalid API keys.
  • Added logic to automatically switch to a different API key if the current one is invalid or rate-limited.
  • Implemented retry logic for API calls.
  • Added logging for API errors and key switching.
astrbot/core/provider/sources/gemini_source.py
Enhanced safety settings configuration and mapping.
  • Created mappings for harm categories and thresholds to the corresponding types.HarmCategory and types.HarmBlockThreshold enums from the Google genai SDK.
  • Initialized safety settings based on the provider configuration.
  • Applied safety settings to the GenerateContentConfig.
astrbot/core/provider/sources/gemini_source.py
Improved the preparation of conversation payloads for the Gemini API.
  • Created the _prepare_conversation method to convert the internal message format to the types.Content format required by the Gemini SDK.
  • Handled different message roles (user, assistant, tool) and content types (text, image) appropriately.
  • Added support for tool calls and function responses.
  • Added warning logs for empty text content and assistant messages.
astrbot/core/provider/sources/gemini_source.py
Refactored the query and stream query methods to use the official Google genai SDK.
  • Replaced the custom HTTP client calls with the official SDK methods for generating content and streaming content.
  • Updated the method signatures to match the SDK requirements.
  • Handled the response from the API and converted it to the internal LLMResponse format.
  • Implemented logic to handle multi-modal outputs (text and image).
  • Implemented logic to handle the RECITATION finish reason by increasing the temperature and retrying the request.
astrbot/core/provider/sources/gemini_source.py
Updated the assemble_context method to handle image URLs and text prompts.
  • Modified the assemble_context method to include a default text of '[图片]' when only image URLs are provided.
  • Updated the assemble_context method in entities.py and openai_source.py to include a default text of '[图片]' when only image URLs are provided.
astrbot/core/provider/sources/gemini_source.py
astrbot/core/provider/entities.py
astrbot/core/provider/sources/openai_source.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @Raven95676 - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Found hardcoded API key. (link)
  • Found hardcoded API key. (link)

Overall Comments:

  • Consider adding error handling for API calls, especially for network-related issues.
  • The code could benefit from more comments explaining the purpose and functionality of different sections, especially the complex logic in _query.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🔴 Security: 2 blocking issues
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@Raven95676 Raven95676 changed the title refactor: 使用Google官方SDK重构gemini_source [WIP]refactor: 使用Google官方SDK重构gemini_source Apr 10, 2025
@AstrBotDevs AstrBotDevs deleted a comment from sourcery-ai bot Apr 11, 2025
@AstrBotDevs AstrBotDevs deleted a comment from sourcery-ai bot Apr 11, 2025
@AstrBotDevs AstrBotDevs deleted a comment from sourcery-ai bot Apr 11, 2025
@AstrBotDevs AstrBotDevs deleted a comment from sourcery-ai bot Apr 11, 2025
@Raven95676 Raven95676 changed the title [WIP]refactor: 使用Google官方SDK重构gemini_source refactor: 使用Google官方SDK重构gemini_source Apr 13, 2025
@Raven95676
Copy link
Member Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @Raven95676 - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Detected hardcoded API key. (link)
  • Detected hardcoded API key. (link)

Overall Comments:

  • Consider adding a method to validate the provider configuration during initialization.
  • The error handling and retry logic for API calls is good, but could be refactored into a separate utility function to reduce code duplication.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🔴 Security: 2 blocking issues
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@Raven95676 Raven95676 requested review from Soulter and anka-afk April 13, 2025 04:44
llm_response.role = "tool"
llm_response.tools_call_name.append(part.function_call.name)
llm_response.tools_call_args.append(part.function_call.args)
llm_response.tools_call_ids.append(part.function_call.id)
Copy link
Member

Choose a reason for hiding this comment

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

这里返回的 id 可能是 None,导致多轮函数调用的时候报错:

AstrBot 请求失败。
错误类型: ClientError
错误信息: 400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': '* GenerateContentRequest.contents[32].parts[0].function_[response.name](https://response.name/): Name cannot be empty.\n', 'status': 'INVALID_ARGUMENT'}}

Copy link
Member

Choose a reason for hiding this comment

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

我修改了一下,这里如果 id 是 None 就直接存 name

43ee943#diff-b0a8d0933e85a0e991ee059844c35a11974fe6aed17b856f20330e7cb79343d1L275-L277

@Soulter
Copy link
Member

Soulter commented Apr 15, 2025

LGTM

@Soulter Soulter merged commit 784dcf2 into AstrBotDevs:master Apr 15, 2025
2 checks passed
@Raven95676 Raven95676 deleted the gemini branch April 16, 2025 03:47
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.

3 participants