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(llm-server): llm server timesout issue #173

Merged
merged 3 commits into from
Mar 9, 2025
Merged

Conversation

ZHallen122
Copy link
Collaborator

@ZHallen122 ZHallen122 commented Mar 8, 2025

Summary by CodeRabbit

  • New Features
    • Chat requests now include a configurable timeout (default: 200 seconds) to ensure timely responses and provide clearer feedback when delays occur.
  • Chores
    • Removed an outdated timeout limit in background operations to enhance flexibility for longer-running tasks.

@ZHallen122 ZHallen122 requested a review from Sma1lboy March 8, 2025 15:16
Copy link
Contributor

coderabbitai bot commented Mar 8, 2025

Walkthrough

The pull request updates the chat functionality in the LLMProvider by adding a new timeoutMs parameter to the chat method. The method now races the model's chat response against a timeout promise, triggering an error log with the timeout duration if exceeded. Additionally, the call in the App's handleChatRequest method is updated to pass a default timeout of 200,000 milliseconds. Separately, a previously set 120-second timeout in the remote model instance queue initialization is removed.

Changes

File(s) Summary of Changes
llm-server/.../llm-provider.ts
llm-server/.../main.ts
Updated the chat method to include a timeoutMs parameter and wrap the model call with a Promise.race against a timeout promise. The main file now passes a default timeout (200,000 ms) to the chat call.
llm-server/.../remote-model-instance.ts Removed the line setting a 120-second timeout for the PQueue in the initializeQueue method, eliminating the enforced timeout for long-running streaming tasks.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant LLMProvider
    participant Model
    App->>LLMProvider: chat(input, timeoutMs)
    note right of LLMProvider: Start timeoutPromise & model.chat call concurrently
    LLMProvider->>Model: chat(input.messages)
    alt Response received before timeout
        Model-->>LLMProvider: response
        LLMProvider-->>App: response
    else Timeout reached
        LLMProvider-->>App: timeout error (logged with duration)
    end
Loading

Possibly related PRs

Suggested reviewers

  • Sma1lboy

Poem

In a code field where ideas hop,
A new timeout waits at every stop.
The chat now races 'gainst the clock,
While logs record each timeout shock.
I'm a rabbit, hopping joyous and bright—coding changes are pure delight!
🐇

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

llm-server/src/main.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/llm-server".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "llm-server/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

llm-server/src/llm-provider.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/llm-server".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "llm-server/.eslintrc.cjs".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

✨ 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
🪧 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.

@ZHallen122 ZHallen122 changed the title remove timeout Fix llm server timesout issue Mar 8, 2025
@ZHallen122 ZHallen122 marked this pull request as ready for review March 8, 2025 15:22
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)
llm-server/src/main.ts (1)

140-141: Fix typo in the TODO comment and consider a configurable timeout

The comment has some grammar and spelling issues. Also, hardcoding the timeout value (200000ms = 200s) might not be flexible enough for different use cases.

-// TODO make it to dynamic Now is 200 second by defult.
+// TODO: Make timeout value dynamic. Currently set to 200 seconds by default.
-const response = await this.llmProvider.chat(input, 200000);
+const defaultTimeoutMs = parseInt(process.env.CHAT_TIMEOUT_MS || '200000', 10);
+const response = await this.llmProvider.chat(input, defaultTimeoutMs);

Consider making the timeout configurable via environment variables to allow better flexibility without code changes.

llm-server/src/llm-provider.ts (2)

107-126: Improve timeout handling with more context and better typing

The implementation of the timeout mechanism is good, but the error message could be more descriptive and the type handling could be improved.

async chat(input: MessageInput, timeoutMs: number): Promise<string> {
  try {
    const model = this.getModelInstance(input.model);

    // Set a timeout dynamically based on the provided value
    const timeoutPromise = new Promise<string>((_, reject) =>
      setTimeout(
-        () => reject(new Error('Chat request timed out')),
+        () => reject(new Error(`Chat request for model ${input.model} timed out after ${timeoutMs}ms`)),
        timeoutMs,
      ),
    );

    // Race between the actual model call and the timeout
    const completion = await Promise.race([
      model.chat(input.messages),
      timeoutPromise,
    ]);

-    return (completion as any).choices[0].message.content || '';
+    // Safely handle response structure
+    if (completion && 
+        typeof completion === 'object' && 
+        'choices' in completion &&
+        Array.isArray(completion.choices) &&
+        completion.choices.length > 0 &&
+        completion.choices[0].message?.content) {
+      return completion.choices[0].message.content;
+    }
+    return '';
  } catch (error) {

127-127: Enhance error logging to distinguish timeout errors

The current error logging doesn't distinguish between timeout errors and other types of errors.

-      this.logger.error(`Error in chat (Timeout: ${timeoutMs}ms):`, error);
+      if (error instanceof Error && error.message.includes('timed out')) {
+        this.logger.error(`Timeout occurred in chat (Timeout: ${timeoutMs}ms):`, error);
+      } else {
+        this.logger.error(`Error in chat (Timeout: ${timeoutMs}ms):`, error);
+      }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bf82dbf and 9bac071.

📒 Files selected for processing (3)
  • llm-server/src/llm-provider.ts (1 hunks)
  • llm-server/src/main.ts (1 hunks)
  • llm-server/src/model/remote-model-instance.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • llm-server/src/model/remote-model-instance.ts

@Sma1lboy Sma1lboy changed the title Fix llm server timesout issue fix(llm-server): llm server timesout issue Mar 9, 2025
@Sma1lboy Sma1lboy merged commit c97940b into main Mar 9, 2025
3 of 4 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.

2 participants