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

fix: AI chat request error #1059

Merged
merged 1 commit into from
Jan 23, 2025
Merged

Conversation

gene9831
Copy link
Collaborator

@gene9831 gene9831 commented Jan 22, 2025

English | 简体中文

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)
  • Built its own designer, fully self-validated

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

Background and solution

AI聊天框,第一次对话成功回复后,接着第二次对话会报错。
问题根因:后端返回的数据结构变更 tiny-engine-webservice commit 2993c4a。后端直接取了choices[0].message里面的内容
解决方法:适配后端返回的新的数据结构。直接去掉前端的choices[0].message

What is the current behavior?

output_image

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • UI Updates

    • Corrected label casing for AI model "文心一言:ERNIE-4.0-8K"
  • Code Improvements

    • Simplified AI response handling logic in the main component

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Walkthrough

The pull request involves two main changes: a modification to the AI response handling logic in Main.vue and a minor label casing update in robotSetting.js. In Main.vue, the sendRequest function's response extraction method has been simplified, directly accessing the AI response properties. The robotSetting.js change corrects the casing of an AI model label from "8k" to "8K", ensuring consistent terminology.

Changes

File Change Summary
packages/plugins/robot/src/Main.vue Simplified AI response extraction by directly accessing originalResponse properties instead of nested choices[0].message
packages/plugins/robot/src/js/robotSetting.js Updated AI model label from "文心一言:ERNIE-4.0-8k" to "文心一言:ERNIE-4.0-8K"

Possibly related PRs

Suggested reviewers

  • hexqi
  • chilingling

Poem

🤖 A rabbit's code review delight,
Responses now clear and bright!
From nested paths to direct view,
8K shines, our model true
Simplicity hops with pure might! 🐰


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>, 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. (Beta)
  • @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.

@github-actions github-actions bot added the bug Something isn't working label Jan 22, 2025
@gene9831 gene9831 marked this pull request as ready for review January 22, 2025 03:45
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

🧹 Nitpick comments (3)
packages/plugins/robot/src/Main.vue (3)

234-235: LGTM! Consider adding defensive programming.

The simplified response extraction aligns with the backend changes and fixes the reported issue. However, consider adding defensive checks to handle potential undefined properties or malformed responses.

-          const responseMessage = getAiRespMessage(originalResponse.role, originalResponse.content)
-          const respDisplayMessage = getAiRespMessage(originalResponse.role, replyWithoutCode)
+          const { role = 'assistant', content = '' } = originalResponse || {}
+          const responseMessage = getAiRespMessage(role, content)
+          const respDisplayMessage = getAiRespMessage(role, replyWithoutCode || '')

Line range hint 233-259: Enhance error handling with specific error cases.

The current error handling only covers connection failures. Consider adding specific error handling for different failure scenarios to improve the user experience.

         .then((res) => {
+          if (!res || typeof res !== 'object') {
+            throw new Error('Invalid response format')
+          }
           const { originalResponse, schema, replyWithoutCode } = res
           const responseMessage = getAiRespMessage(originalResponse.role, originalResponse.content)
           const respDisplayMessage = getAiRespMessage(originalResponse.role, replyWithoutCode)
           sessionProcess.messages.push(responseMessage)
           sessionProcess.displayMessages.push(respDisplayMessage)
           messages.value[messages.value.length - 1].content = replyWithoutCode
           setContextSession()
           if (schema?.schema) {
             createNewPage(schema.schema)
           }
           inProcesing.value = false
           connectedFailed.value = false
         })
-        .catch(() => {
-          messages.value[messages.value.length - 1].content = '连接失败'
+        .catch((error) => {
+          let errorMessage = '连接失败'
+          if (error.response) {
+            switch (error.response.status) {
+              case 429:
+                errorMessage = '请求过于频繁,请稍后再试'
+                break
+              case 408:
+                errorMessage = '请求超时,请重试'
+                break
+              default:
+                errorMessage = error.response.data?.message || '服务器错误'
+            }
+          } else if (error.message === 'Invalid response format') {
+            errorMessage = '响应格式错误'
+          }
+          messages.value[messages.value.length - 1].content = errorMessage
           localStorage.removeItem('aiChat')
           inProcesing.value = false
           connectedFailed.value = false
         })

233-233: Optimize request timeout configuration.

The current 10-minute timeout (600000ms) is excessive and could lead to poor user experience. Consider reducing it and implementing a retry mechanism.

+      const MAX_RETRIES = 3
+      const TIMEOUT = 60000 // 60 seconds
+      const retryRequest = async (retries = 0) => {
         getMetaApi(META_SERVICE.Http)
-          .post('/app-center/api/ai/chat', getSendSeesionProcess(), { timeout: 600000 })
+          .post('/app-center/api/ai/chat', getSendSeesionProcess(), { timeout: TIMEOUT })
           .then((res) => {
             // ... existing success handling
           })
           .catch((error) => {
+            if (retries < MAX_RETRIES && error.code === 'ECONNABORTED') {
+              messages.value[messages.value.length - 1].content = `请求超时,正在重试 (${retries + 1}/${MAX_RETRIES})...`
+              return retryRequest(retries + 1)
+            }
             // ... existing error handling
           })
+      }
+      retryRequest()
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd8ae42 and e1cbe1a.

📒 Files selected for processing (2)
  • packages/plugins/robot/src/Main.vue (1 hunks)
  • packages/plugins/robot/src/js/robotSetting.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/plugins/robot/src/js/robotSetting.js
🔇 Additional comments (1)
packages/plugins/robot/src/Main.vue (1)

234-235: Add test coverage for the response handling changes.

The changes fix the immediate issue, but lack test coverage. Consider adding tests for:

  • New response structure handling
  • Error cases and recovery
  • Timeout and retry mechanism

Would you like me to help create a test suite for these scenarios?

@hexqi hexqi added this to the v2.2.0 milestone Jan 23, 2025
@hexqi hexqi merged commit d8c78bd into opentiny:release/v2.2.0 Jan 23, 2025
11 checks passed
hexqi pushed a commit to hexqi/tiny-engine that referenced this pull request Jan 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants