Skip to content
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

feat: support baidu model #4936

Merged
merged 11 commits into from
Jul 9, 2024
Merged

Conversation

Dogtiti
Copy link
Member

@Dogtiti Dogtiti commented Jul 6, 2024

Summary by CodeRabbit

  • New Features

    • Introduced Baidu API integration, supporting Baidu's Ernie model for chat interactions.
    • Added Baidu service provider settings, including API key, secret key, and endpoint configuration.
    • Enhanced model configuration with Baidu models in the settings menu.
  • Improvements

    • Updated model display logic to better handle custom names and display formats.
  • Documentation

    • Updated README and README_CN with new configuration options for Baidu API integration.

@Dogtiti Dogtiti requested a review from lloydzhou July 6, 2024 05:05
Copy link

vercel bot commented Jul 6, 2024

@Dogtiti is attempting to deploy a commit to the NextChat Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Jul 6, 2024

Walkthrough

The updates enhance the application's Baidu API integration by adding new components, configuration options, and conditional logic to handle the new model provider, ModelProvider.Ernie. This includes modifications to the client, server, and utility aspects, facilitating seamless authentication and interaction with Baidu's services.

Changes

Files Changed Summary
.gitignore Added pattern *.key.pub for ignoring specific file types.
app/api/auth.ts Introduced ModelProvider.Ernie in the auth function with new configuration.
app/api/baidu/[...path]/route.ts Introduced new file handling requests to the Baidu API, including endpoint setups.
app/client/api.ts Updated ClientApi class to integrate ErnieApi for Baidu platform.
app/client/platforms/baidu.ts Created new ErnieApi class implementing LLMApi to manage Baidu API interactions.
app/components/exporter.tsx Added ServiceProvider.Baidu case to PreviewActions.
app/components/home.tsx Enabled data loading support for ServiceProvider.Baidu in useLoadData function.
app/components/settings.tsx Added settings components for Baidu service provider, including endpoint and keys.
app/config/server.ts Introduced new configuration options and checks for Baidu and Anthropic services.
app/constant.ts Added constants for Baidu endpoints, models, and providers along with default settings.
app/locales/cn.ts Added localized strings for Baidu API keys, endpoints, and secret key configurations.
access.ts, chat.ts, model.ts in Enhanced functionality to support new Baidu API and updated logic for handling models.
README.md, README_CN.md Documented configuration parameters for Baidu API integration.
app/api/common.ts Updated the requestOpenai function to incorporate serverConfig.azureUrl checks.
app/utils/baidu.ts Created utility function getAccessToken for Baidu OAuth authentication.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Settings as Settings Component
    participant Auth as Auth Function
    participant ServerConfig as Server Configuration
    participant BaiduAPI as Baidu API

    User ->> Settings: Enter Baidu API Key and Secret Key
    Settings ->> Auth: Save the API Key and Secret Key
    Auth ->> ServerConfig: Initialize with Baidu configuration
    User ->> BaiduAPI: Make a request
    BaiduAPI ->> Auth: Authenticate request
    Auth ->> BaiduAPI: Return Access Token
    BaiduAPI ->> User: Return requested data
Loading
sequenceDiagram
    participant User
    participant API as Client API
    participant Platform as ErnieApi
    participant BaiduAPI as Baidu API

    User ->> API: Request using Ernie Provider
    API ->> Platform: Forward request to ErnieApi
    Platform ->> BaiduAPI: Make authenticated API call
    BaiduAPI ->> Platform: Return API response
    Platform ->> User: Deliver result
Loading

Poem

A Rabbit's Ode to Baidu's Code

In our codebase where features shine,
We now support Baidu fine,
Ernie comes to join the dance,
With new keys and paths for every chance.

The models sing, the settings set,
In Baidu's world, we do not fret.
Configuration now robust and bright,
Our features soar to a new height. 🌟🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@@ -24,10 +24,13 @@ export function collectModelTable(

// default models
models.forEach((m) => {
// supoort name=displayName eg:completions_pro=ernie-4.0-8k
const [name, displayName] = m.name?.split("=");
Copy link
Member Author

Choose a reason for hiding this comment

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

这里是支持内部模型的别名方式

Copy link
Contributor

Choose a reason for hiding this comment

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

不建议在这个地方还使用更复杂的逻辑。前面的别名,在ChatPath函数中处理即可

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2d1f522 and 785d374.

Files selected for processing (14)
  • .gitignore (1 hunks)
  • app/api/auth.ts (1 hunks)
  • app/api/baidu/[...path]/route.ts (1 hunks)
  • app/client/api.ts (2 hunks)
  • app/client/platforms/baidu.ts (1 hunks)
  • app/components/exporter.tsx (1 hunks)
  • app/components/home.tsx (1 hunks)
  • app/components/settings.tsx (2 hunks)
  • app/config/server.ts (3 hunks)
  • app/constant.ts (6 hunks)
  • app/locales/cn.ts (1 hunks)
  • app/store/access.ts (3 hunks)
  • app/store/chat.ts (2 hunks)
  • app/utils/model.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • .gitignore
Additional context used
Learnings (1)
app/store/access.ts (1)
Learnt from: lloydzhou
PR: ChatGPTNextWeb/ChatGPT-Next-Web#4925
File: app/store/access.ts:86-88
Timestamp: 2024-07-04T15:40:31.080Z
Learning: The function name `isValidaBaidu` in `app/store/access.ts` should be corrected to `isValidBaidu`.
Biome
app/api/auth.ts

[error] 79-79: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

app/utils/model.ts

[error] 28-28: Unsafe usage of optional chaining.

If it short-circuits with 'undefined' the evaluation will throw TypeError here:

(lint/correctness/noUnsafeOptionalChaining)

Additional comments not posted (29)
app/store/access.ts (3)

50-54: LGTM!

The addition of Baidu API configuration fields looks good.


91-93: LGTM!

The addition of the isValidBaidu method looks good. The function name is correctly spelled.


104-104: LGTM!

The addition of the isValidBaidu check in the isAuthorized method looks good.

app/config/server.ts (3)

38-47: LGTM!

The addition of configuration options for Baidu services looks good.


105-105: LGTM!

The addition of the isBaidu flag looks good.


137-141: LGTM!

The addition of Baidu-specific configurations in the getServerSideConfig function looks good.

app/api/baidu/[...path]/route.ts (3)

1-14: Imports and Constants Look Good

The imports and constants are well-organized and correctly defined. No issues found.


16-40: Verify Error Handling in handle Function

The handle function is well-structured, but ensure that the error handling covers all potential exceptions.

Please verify if there are any specific exceptions that need to be handled separately.


45-64: Constants for Runtime and Preferred Regions Look Good

The runtime and preferredRegion constants are correctly defined and useful for deployment configuration.

app/client/api.ts (3)

12-12: New Import for ErnieApi Looks Good

The import for ErnieApi from the Baidu platform is correctly added.


109-111: Switch Case for ErnieApi Looks Good

The switch case for ErnieApi has been correctly added to the ClientApi constructor.


109-111: Functions in ClientApi Class Look Good

The functions within the ClientApi class are well-defined and there are no issues found.

app/components/home.tsx (3)

178-179: Update in useLoadData Function Looks Good

The useLoadData function has been correctly updated to support ServiceProvider.Baidu.


Line range hint 1-177: Screen Component Looks Good

The Screen component is well-defined and there are no issues found.


Line range hint 1-177: Home Component Looks Good

The Home component is well-defined and there are no issues found.

app/constant.ts (3)

17-20: New Constants for Baidu Look Good

The new constants BAIDU_BASE_URL and BAIDU_OATUH_URL are correctly defined.


35-35: New Enums for Baidu Look Good

The new enums for Baidu in ApiPath, ServiceProvider, and ModelProvider are correctly defined.

Also applies to: 79-79, 86-86


189-197: New Default Models for Baidu Look Good

The new default models for Baidu are correctly defined.

app/client/platforms/baidu.ts (5)

50-73: LGTM! Ensure correct base URL construction.

The path method correctly constructs the base URL based on different configurations and logs the proxy endpoint. The code handles various scenarios, including custom configurations and default values.


76-78: LGTM! Ensure message extraction.

The extractMessage method correctly extracts the message content from the response.


80-239: Ensure robust chat interaction handling.

The chat method handles chat interactions, including constructing the request payload, managing streaming responses, and handling errors. The method appears to cover all necessary aspects, including logging and animation for smooth UX.


241-246: LGTM! Ensure correct usage reporting.

The usage method correctly returns a default usage object with used and total values set to 0.


248-250: LGTM! Ensure correct model fetching.

The models method correctly returns an empty array as a placeholder for the list of models.

app/locales/cn.ts (1)

350-365: LGTM! Ensure correct localization entries.

The new key-value pairs for Baidu-related API keys and endpoints are correctly added and follow the existing structure.

app/components/exporter.tsx (1)

324-325: LGTM! Ensure correct handling of Baidu service provider.

The new case for ServiceProvider.Baidu in the PreviewActions component correctly handles the Baidu service provider by assigning ModelProvider.Ernie to the api variable.

app/store/chat.ts (2)

371-372: LGTM! Ensure correct handling of Baidu service provider in onUserInput.

The new case for ServiceProvider.Baidu in the onUserInput method correctly handles the Baidu service provider by assigning ModelProvider.Ernie to the api variable.


557-558: LGTM! Ensure correct handling of Baidu service provider in summarizeSession.

The new case for ServiceProvider.Baidu in the summarizeSession method correctly handles the Baidu service provider by assigning ModelProvider.Ernie to the api variable.

app/components/settings.tsx (2)

56-56: Import statement for Baidu looks good.

The import statement for Baidu is correctly added.


1191-1251: Addition of Baidu settings looks good.

The settings for Baidu API configuration follow the existing pattern for other service providers and are correctly implemented.

app/api/auth.ts Show resolved Hide resolved
app/utils/model.ts Outdated Show resolved Hide resolved
app/api/baidu/[...path]/route.ts Outdated Show resolved Hide resolved
app/api/baidu/[...path]/route.ts Outdated Show resolved Hide resolved
app/api/auth.ts Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 785d374 and 9f7d137.

Files selected for processing (1)
  • app/client/api.ts (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • app/client/api.ts

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9f7d137 and f3e3f08.

Files selected for processing (1)
  • app/client/api.ts (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • app/client/api.ts


if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
baseUrl = isApp ? DEFAULT_API_HOST + "/api/proxy/baidu" : ApiPath.Baidu;
Copy link
Contributor

Choose a reason for hiding this comment

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

如果加了api/proxy/baidu
需要在next.config.mjs添加对应的转发路由,这实际上是用来处理app端发请求的。
这里百度的可以不用走proxy,直接请求。
所以,app内应该直接使用百度官方的地址

Copy link
Contributor

Choose a reason for hiding this comment

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

app/constant.ts Outdated
"ernie-4.0-8k-preview",
"completions_adv_pro=ernie-4.0-8k-preview-0518",
"ernie-4.0-8k-latest",
"completions=ernie-3.5-8k",
Copy link
Contributor

Choose a reason for hiding this comment

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

这里为什么配置方式不一样了?

}

async chat(options: ChatOptions) {
const visionModel = isVisionModel(options.config.model);
Copy link
Contributor

Choose a reason for hiding this comment

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

这里应该不用判断

app/constant.ts Outdated
export const Baidu = {
ExampleEndpoint: "https://aip.baidubce.com",
ChatPath: (modelName: string) =>
`/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${modelName}`,
Copy link
Contributor

Choose a reason for hiding this comment

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

是不是,下面的baiduModels还是按正常的方式配置,但是生成ChatPath的时候,处理一下就好了?

@@ -24,10 +24,13 @@ export function collectModelTable(

// default models
models.forEach((m) => {
// supoort name=displayName eg:completions_pro=ernie-4.0-8k
const [name, displayName] = m.name?.split("=");
Copy link
Contributor

Choose a reason for hiding this comment

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

不建议在这个地方还使用更复杂的逻辑。前面的别名,在ChatPath函数中处理即可

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f3e3f08 and f68cd2c.

Files selected for processing (3)
  • app/client/platforms/baidu.ts (1 hunks)
  • app/constant.ts (6 hunks)
  • app/utils/model.ts (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • app/client/platforms/baidu.ts
  • app/constant.ts
  • app/utils/model.ts

* 使用 AK,SK 生成鉴权签名(Access Token)
* @return 鉴权签名信息
*/
async function getAccessToken(): Promise<{
Copy link
Contributor

Choose a reason for hiding this comment

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

这个函数需要放一个公共的位置:

  1. 如果是app端运行,或者用户直接在前端配置了百度的密钥,这个时候,需要在前端生成access_token,直接发送给配置的地址。
  2. 如果用户没有在前端配置自己的密钥,这个时候,发到/api/baidu/的请求是不带access_token的,这个时候,需要node server生成这个并放到请求里面。

options.onController?.(controller);

try {
const chatPath = this.path(Baidu.ChatPath(modelConfig.model));
Copy link
Contributor

Choose a reason for hiding this comment

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

这里参考platform/google的逻辑,如果是app内,或者前端配置了app_id+app_secret,这里需要生成access_token并放到url中

app/client/platforms/baidu.ts Show resolved Hide resolved
app/locales/cn.ts Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Outside diff range and nitpick comments (1)
app/client/platforms/baidu.ts (1)

73-73: Remove console log statement.

The console log statement should be removed or replaced with a proper logging mechanism if needed for debugging.

-    console.log("[Proxy Endpoint] ", baseUrl, path);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f68cd2c and fadd7f6.

Files selected for processing (3)
  • app/api/baidu/[...path]/route.ts (1 hunks)
  • app/client/platforms/baidu.ts (1 hunks)
  • app/constant.ts (6 hunks)
Files skipped from review as they are similar to previous changes (2)
  • app/api/baidu/[...path]/route.ts
  • app/constant.ts
Additional context used
Biome
app/client/platforms/baidu.ts

[error] 120-120: Avoid redundant double-negation.

It is not necessary to use double-negation when a value will already be coerced to a boolean.
Unsafe fix: Remove redundant double-negation

(lint/complexity/noExtraBooleanCast)

Additional comments not posted (2)
app/client/platforms/baidu.ts (2)

84-90: Ensure message length is odd.

The logic to prepend an empty message if the message count is even is correct. Ensure this logic is tested to prevent errors from Baidu's API.


178-181: Ensure onFinish is called once.

The finish function should ensure that onFinish is called only once, which is correctly handled here.

app/client/platforms/baidu.ts Show resolved Hide resolved
app/client/platforms/baidu.ts Show resolved Hide resolved
app/client/platforms/baidu.ts Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fadd7f6 and b14a0f2.

Files selected for processing (2)
  • app/locales/cn.ts (1 hunks)
  • app/locales/en.ts (1 hunks)
Additional comments not posted (3)
app/locales/en.ts (3)

337-342: LGTM!

The localization strings for Baidu API Key are accurate and consistent with other entries.


343-347: LGTM!

The localization strings for Baidu Secret Key are accurate and consistent with other entries.


348-352: LGTM!

The localization strings for Baidu Endpoint are accurate and consistent with other entries.

app/locales/cn.ts Show resolved Hide resolved
app/locales/cn.ts Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b14a0f2 and f2a35f1.

Files selected for processing (5)
  • README.md (1 hunks)
  • README_CN.md (1 hunks)
  • app/api/baidu/[...path]/route.ts (1 hunks)
  • app/api/common.ts (2 hunks)
  • app/utils/baidu.ts (1 hunks)
Files skipped from review due to trivial changes (2)
  • README.md
  • README_CN.md
Files skipped from review as they are similar to previous changes (1)
  • app/api/baidu/[...path]/route.ts
Additional comments not posted (3)
app/api/common.ts (3)

Line range hint 73-85:
Verify Azure-specific deployment logic.

The Azure-specific logic for handling custom models and deployment names appears correct. Ensure that the serverConfig.customModels and serverConfig.azureUrl configurations are properly set and validated to avoid potential issues.


Line range hint 141-161:
Ensure correct handling of unauthorized model use.

The logic for preventing unauthorized use of certain models is essential for security. Verify that the function correctly identifies and handles these scenarios, returning appropriate error responses and logging relevant information for debugging.


Line range hint 163-200:
Ensure proper logging and resource cleanup.

The error handling for the fetch request appears adequate. Verify that the function logs relevant information for debugging and cleans up resources, such as clearing timeouts, to avoid potential memory leaks.

app/utils/baidu.ts Show resolved Hide resolved
@lloydzhou lloydzhou merged commit 47ea383 into ChatGPTNextWeb:main Jul 9, 2024
0 of 2 checks passed
@lloydzhou lloydzhou deleted the feat-baidu branch August 1, 2024 05:13
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.

2 participants