Skip to content

fix: useXAgent & x-request's XRequestOptions chenge #736

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 50 commits into from
Apr 16, 2025

Conversation

kimteayon
Copy link
Collaborator

@kimteayon kimteayon commented Apr 16, 2025

🤔 This is a ...

  • 🐞 Bug fix

useXAgent 和 x-request 基础配置变更不生效问题。

#413
#536

Summary by CodeRabbit

  • 新功能

    • 新增了“变更配置”演示示例,支持动态修改 baseURL、模型和 API key,并在 UI 上实时展示请求及响应过程。
    • 新增了相关中英文文档与代码示例,详细说明如何动态控制 XRequestOptions 配置参数。
  • 文档

    • 英文和中文文档中均新增了“变更配置”/“Control XRequestOptions”示例及说明。
    • 优化部分文档语句标点,提升阅读体验。
  • 修复与优化

    • useXAgent 钩子的依赖项调整,配置变化时可正确响应。
    • 移除 XRequest 的实例缓存机制,每次调用均返回新实例,行为更直观。
  • 测试

    • 移除了 XRequest 实例复用相关的测试用例。

Copy link
Contributor

coderabbitai bot commented Apr 16, 2025

📝 Walkthrough

Walkthrough

本次变更主要围绕 XRequestuseXAgent 两个组件及其相关文档和演示示例展开。移除了 XRequest 的实例缓存机制,每次初始化都返回新实例,并将其主类 XRequestClass 设为导出。新增了动态控制请求参数(如 baseURL、model、API key)的中英文文档及 React 示例,并在相关文档中补充了“变更配置”/“Control XRequestOptions”代码演示。useXAgent 内部的 useMemo 依赖由空数组改为依赖 config。部分演示文档标点做了微调,同时移除了关于实例复用的测试用例。

Changes

文件/路径分组 变更摘要
components/x-request/index.ts 移除实例缓存,XRequestClass 变为导出类,init 方法每次都返回新实例。
components/x-request/tests/index.test.tsx 移除关于 XRequest 实例复用的测试用例。
components/x-request/demo/request-options.md
components/use-x-agent/demo/request-options.md
新增中英文文档,介绍如何动态控制 XRequestOptions。
components/x-request/demo/request-options.tsx
components/use-x-agent/demo/request-options.tsx
新增 React 组件示例,演示如何动态切换请求参数并发起请求。
components/x-request/index.en-US.md
components/x-request/index.zh-CN.md
components/use-x-agent/index.en-US.md
components/use-x-agent/index.zh-CN.md
文档中新增“变更配置”/“Control XRequestOptions”演示代码引用。
components/use-x-agent/index.ts useMemo 依赖由空数组改为 [config],提升配置变更响应能力。
components/use-x-agent/demo/preset.md 中英文内容末尾补全句号。

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant DemoComponent as Demo (request-options.tsx)
    participant XRequest/XAgent

    User->>DemoComponent: 点击“变更配置”按钮
    DemoComponent->>DemoComponent: 切换 baseURL/model/API key
    User->>DemoComponent: 点击“发起请求”按钮
    DemoComponent->>XRequest/XAgent: 以当前配置发起请求(支持流式)
    XRequest/XAgent-->>DemoComponent: 返回流式响应/错误
    DemoComponent->>DemoComponent: 更新状态与 UI 展示
Loading

Suggested reviewers

  • afc163
  • YumoImer

Poem

小兔挥爪点代码,
配置切换乐开怀。
单例缓存说拜拜,
新例每次都精彩。
文档演示齐更新,
请求灵活任你来!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9824606 and ac82c68.

📒 Files selected for processing (1)
  • components/x-request/index.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • components/x-request/index.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build preview
  • GitHub Check: test / react component workflow
  • GitHub Check: size

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
🪧 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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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.

Copy link

github-actions bot commented Apr 16, 2025

Preview is ready

Copy link

Walkthrough

This pull request addresses a bug fix related to the useXAgent and x-request configurations not being applied correctly. The changes involve updating the configuration handling to ensure that changes to XRequestOptions are dynamically applied, allowing for modifications to baseURL, model, and API key settings.

Changes

Files Summary
components/use-x-agent/tests/snapshots/demo.test.ts.snap, components/x-request/tests/snapshots/demo.test.ts.snap Updated snapshot tests for useXAgent and x-request.
components/use-x-agent/demo/preset.md, components/x-request/demo/request-options.md Documentation updates for configuration changes in both English and Chinese.
components/use-x-agent/demo/request-options.tsx, components/x-request/demo/request-options.tsx Added new demo files to illustrate dynamic configuration changes for XRequestOptions.
components/use-x-agent/index.en-US.md, components/use-x-agent/index.zh-CN.md, components/x-request/index.en-US.md, components/x-request/index.zh-CN.md Updated documentation to include new demo links for XRequestOptions.
components/use-x-agent/index.ts Modified useXAgent to use React.useMemo with updated dependencies.
components/x-request/index.ts Refactored XRequestClass to remove instance buffering and ensure new instances are created with updated options.

Copy link

codecov bot commented Apr 16, 2025

Bundle Report

Bundle size has no change ✅

Copy link

codecov bot commented Apr 16, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 92.12%. Comparing base (5fa69bc) to head (ac82c68).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #736      +/-   ##
==========================================
- Coverage   92.14%   92.12%   -0.03%     
==========================================
  Files          66       66              
  Lines        1464     1460       -4     
  Branches      393      391       -2     
==========================================
- Hits         1349     1345       -4     
  Misses        115      115              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

🧹 Nitpick comments (6)
components/use-x-agent/demo/request-options.md (1)

1-7: 文档描述清晰明了,但英文版本中使用了中文标点符号

文档内容简洁地说明了如何控制和动态修改 XRequestOptions 的配置项,包括 baseURL、model 和 API key,信息传达清晰。但请注意英文版本使用了中文逗号(,)而不是英文逗号(,)。

建议将英文版本中的标点符号纠正为英文标点:

-Control change `XRequestOptions`,dynamically modify configuration items such as baseURL, model, and API key.
+Control change `XRequestOptions`, dynamically modify configuration items such as baseURL, model, and API key.
components/use-x-agent/demo/request-options.tsx (2)

8-16: 注意 API 密钥安全性问题

示例中使用了明文 API 密钥,这在实际应用中存在安全风险。虽然有相关警告注释,但建议增强安全提示。

- /** 🔥🔥 Its dangerously! */
+ /** 
+  * 🔥🔥 危险!永远不要在客户端代码中硬编码 API 密钥! 
+  * 这仅用于演示目的。在生产环境中,应通过安全的后端服务处理 API 请求。
+  */

45-65: Agent 请求实现与回调处理

请求函数实现了流式响应处理,并通过回调更新状态。但有一个细节需要注意:

在开始新请求前应该重置 lines 和 error 状态,确保界面不显示上一次请求的残留信息:

 async function request() {
   setStatus('pending');
+  setLines([]);
+  setError(undefined);
   agent.request(
     {
       messages: [{ role: 'user', content: 'hello, who are u?' }],
       stream: true,
     },
     {
       onSuccess: () => {
         setStatus('success');
       },
       onError: (error) => {
         setStatus('error');
         setError(error);
       },
       onUpdate: (msg) => {
         setLines((pre) => [...pre, msg]);
       },
     },
   );
 }
components/x-request/demo/request-options.tsx (3)

8-25: 配置和初始化状态

示例配置和状态初始化合理,但关于 API 密钥的安全提示可以进一步加强。

- /** 🔥🔥 Its dangerously! */
+ /** 
+  * 🔥🔥 危险!永远不要在客户端代码中硬编码 API 密钥! 
+  * 这仅用于演示目的。在生产环境中,应通过安全的后端服务处理 API 请求。
+  */

29-51: 请求功能实现

请求实现包含完整的状态管理和错误处理,但存在日志调试代码。

 onError: (error) => {
   setError(error);
-  console.log(error.message, 11);
   setStatus('error');
 },

72-72: 按钮文本不一致

按钮的文本内容与其功能不匹配,应修改为"发送请求"而非"Agent 请求",因为这是 XRequest 而不是 Agent 的示例。

- Agent Request
+ 发送请求
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc22253 and 9824606.

⛔ Files ignored due to path filters (2)
  • components/use-x-agent/__tests__/__snapshots__/demo.test.ts.snap is excluded by !**/*.snap
  • components/x-request/__tests__/__snapshots__/demo.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (12)
  • components/use-x-agent/demo/preset.md (1 hunks)
  • components/use-x-agent/demo/request-options.md (1 hunks)
  • components/use-x-agent/demo/request-options.tsx (1 hunks)
  • components/use-x-agent/index.en-US.md (1 hunks)
  • components/use-x-agent/index.ts (2 hunks)
  • components/use-x-agent/index.zh-CN.md (1 hunks)
  • components/x-request/__tests__/index.test.tsx (0 hunks)
  • components/x-request/demo/request-options.md (1 hunks)
  • components/x-request/demo/request-options.tsx (1 hunks)
  • components/x-request/index.en-US.md (1 hunks)
  • components/x-request/index.ts (2 hunks)
  • components/x-request/index.zh-CN.md (1 hunks)
💤 Files with no reviewable changes (1)
  • components/x-request/tests/index.test.tsx
🧰 Additional context used
🧬 Code Graph Analysis (1)
components/use-x-agent/demo/request-options.tsx (1)
components/use-x-agent/index.ts (1)
  • useXAgent (84-103)
🔇 Additional comments (19)
components/use-x-agent/index.ts (1)

84-101: 修复了配置变更不生效的问题,非常好的改进

将 useMemo 的依赖数组从空数组 [] 修改为 [config],确保了当配置对象发生变化时,XAgent 实例会被重新计算。这解决了 #413#536 中提到的配置变更不生效的问题。

components/x-request/index.ts (2)

94-94: 导出 XRequestClass 类,增加了库的灵活性

将 XRequestClass 从非导出类改为导出类,使得开发者可以直接使用这个类,增加了库的灵活性和可扩展性。


115-119: 移除实例缓存机制,确保配置更新能够正确应用

移除了实例缓存机制,现在 init 静态方法每次调用都会返回一个新的 XRequestClass 实例,不再复用之前创建的实例。这确保了当配置更新时,新的配置能够正确应用,修复了 PR 中提到的问题。

components/use-x-agent/demo/preset.md (2)

3-3: 标点符号修正

修正了句尾缺少句号的问题,提高了文档的规范性。


7-7: 标点符号修正

修正了英文描述句尾缺少句号的问题,提高了文档的规范性。

components/use-x-agent/index.zh-CN.md (1)

24-24: 新增“变更配置”示例提升了文档实用性,内容无误。

该示例有助于用户理解如何动态控制 XRequestOptions,建议保留。

components/x-request/index.en-US.md (1)

24-24: 新增“Control XRequestOptions”示例提升了英文文档的完整性。

该示例便于用户了解如何动态控制请求配置,建议保留。

components/x-request/index.zh-CN.md (1)

25-25: 新增“变更配置”示例提升了文档的实用性。

该示例便于用户了解如何动态控制请求配置,建议保留。

components/use-x-agent/index.en-US.md (1)

23-23: 新增“Control XRequestOptions”示例提升了英文文档的完整性。

该示例便于用户了解如何动态控制请求配置,建议保留。

components/x-request/demo/request-options.md (1)

1-8: 中英文说明简洁明了,内容准确。

该文档有助于用户快速理解动态配置 XRequestOptions 的能力,建议保留。

components/use-x-agent/demo/request-options.tsx (5)

1-6: 导入相关依赖

导入了必要的图标、组件和钩子函数,包括 ThoughtChainuseXAgent@ant-design/x 中导入,以及其他 Ant Design 组件。


17-34: 初始化 React 组件与状态

组件正确设置了必要的状态变量和 useXAgent 钩子,并根据当前 requestOptions 创建了 agent 实例。这是动态更新配置的关键部分,体现了此 PR 修复的问题。


36-43: 切换请求选项功能实现

changeBaseData 函数能够在不同的配置间切换,很好地展示了动态配置变更功能。


67-107: 用户界面实现

界面使用 Splitter 和 Flex 组件构建了清晰的布局,并通过 ThoughtChain 组件展示请求状态和结果。UI 交互设计合理,禁用了进行中请求的按钮。


109-112: 组件导出

组件正确导出为默认导出。

components/x-request/demo/request-options.tsx (4)

1-7: 导入相关依赖

导入了必要的组件和库,结构清晰。


27-27: XRequest 实例创建

每次 requestOptions 改变时都会创建新的 XRequest 实例,这正确演示了此 PR 修复的核心问题 - 确保配置更新能够正确应用。


62-101: 用户界面实现

界面实现合理,使用 Splitter 和 ThoughtChain 组件展示了配置和请求状态。按钮交互逻辑设置正确。


103-106: 组件导出

组件正确导出为默认导出。

Comment on lines +53 to +60
const changeBaseData = () => {
setRequestOptions((pre) => ({
baseURL: BASE_URL,
model: pre.model === MODEL ? 'gpt-4' : MODEL,
dangerouslyApiKey:
pre.dangerouslyApiKey === API_KEY ? 'Bearer sk-your-new-dangerouslyApiKey' : API_KEY,
}));
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

配置切换功能

changeBaseData 函数实现了配置切换,但注意 baseURL 没有进行动态切换,而是始终设回 BASE_URL 常量。

 const changeBaseData = () => {
   setRequestOptions((pre) => ({
-    baseURL: BASE_URL,
+    baseURL: pre.baseURL === BASE_URL ? 'https://api.example.com/chat/v2' : BASE_URL,
     model: pre.model === MODEL ? 'gpt-4' : MODEL,
     dangerouslyApiKey:
       pre.dangerouslyApiKey === API_KEY ? 'Bearer sk-your-new-dangerouslyApiKey' : API_KEY,
   }));
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const changeBaseData = () => {
setRequestOptions((pre) => ({
baseURL: BASE_URL,
model: pre.model === MODEL ? 'gpt-4' : MODEL,
dangerouslyApiKey:
pre.dangerouslyApiKey === API_KEY ? 'Bearer sk-your-new-dangerouslyApiKey' : API_KEY,
}));
};
const changeBaseData = () => {
setRequestOptions((pre) => ({
baseURL: pre.baseURL === BASE_URL ? 'https://api.example.com/chat/v2' : BASE_URL,
model: pre.model === MODEL ? 'gpt-4' : MODEL,
dangerouslyApiKey:
pre.dangerouslyApiKey === API_KEY ? 'Bearer sk-your-new-dangerouslyApiKey' : API_KEY,
}));
};

@kimteayon kimteayon linked an issue Apr 16, 2025 that may be closed by this pull request
@kimteayon kimteayon merged commit 47297dc into ant-design:main Apr 16, 2025
11 checks passed
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.

useXAgent 支持额外参数 传递
3 participants