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

added timeout for llm request #1594

Merged
merged 2 commits into from
Nov 13, 2024
Merged

added timeout for llm request #1594

merged 2 commits into from
Nov 13, 2024

Conversation

sfahad1414
Copy link
Collaborator

@sfahad1414 sfahad1414 commented Nov 13, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a customizable timeout parameter for HTTP requests, enhancing flexibility in request handling.
    • Added a default request_timeout of 30 seconds for LLM requests.
    • New email verification capabilities have been implemented.
    • Added support for real-time communication with live agents via a new WebSocket URL.
  • Bug Fixes

    • Corrected naming inconsistencies in email verification configuration.
  • Documentation

    • Updated documentation to reflect new parameters and configurations.

Copy link

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes introduce a new timeout parameter to the execute_request_async and __get_completion methods, enhancing HTTP request handling in the ActionUtility and LLMProcessor classes. The system.yaml and tests/testing_data/system.yaml files have been updated to include a default request_timeout configuration, along with other parameter adjustments for clarity and functionality. These modifications improve the flexibility of the system's configuration and error handling while maintaining existing control flows.

Changes

File Change Summary
kairon/shared/actions/utils.py Added timeout parameter to execute_request_async method; modified execute_http_request to use dynamic timeout logic. Updated documentation strings for both methods.
kairon/shared/llm/processor.py Added timeout parameter to __get_completion method; updated call to ActionUtility.execute_request_async to include the new timeout parameter sourced from environment configuration.
system.yaml Added request_timeout parameter under llm; corrected casing for VERIFY_EMAIL_ENABLE and VERIFY_EMAIL_TYPE; added support_mail and enable_onboarding parameters.
tests/testing_data/system.yaml Added request_timeout under llm; added enable and type for email verification; introduced live_agent_socket_url in live_agent section.

Poem

In the meadow where rabbits play,
New timeouts hop in, brightening the day.
With each request, they dance and prance,
Making sure our calls enhance!
So here’s to change, a joyful cheer,
For better requests, let’s all draw near! 🐇✨


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 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

@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

🧹 Outside diff range and nitpick comments (7)
tests/testing_data/system.yaml (1)

208-208: Document timeout behavior

Consider adding a comment in the YAML file to document the timeout behavior, including what happens when requests exceed the timeout and any retry mechanisms.

  url: ${LLM_SERVER_URL:http://localhost}
+ # Timeout in seconds for LLM API requests. Requests exceeding this duration will raise a timeout exception.
  request_timeout: ${LLM_REQUEST_TIMEOUT:30}
system.yaml (1)

212-212: LGTM! Consider documenting the timeout unit.

The addition of the request_timeout parameter with a default of 30 seconds is a good improvement for LLM request handling. Consider adding a comment to explicitly document that the timeout value is in seconds.

  url: ${LLM_SERVER_URL:http://localhost}
-  request_timeout: ${LLM_REQUEST_TIMEOUT:30}
+  # Timeout in seconds for LLM requests
+  request_timeout: ${LLM_REQUEST_TIMEOUT:30}
kairon/shared/llm/processor.py (2)

187-192: LGTM! Consider enhancing error logging for timeouts

The timeout implementation looks good. The default of 30 seconds is reasonable, and retrieving the value from environment configuration provides good flexibility.

Consider adding specific logging for timeout exceptions to help with debugging and monitoring. Example:

 http_response, status_code, elapsed_time, _ = await ActionUtility.execute_request_async(http_url=f"{Utility.environment['llm']['url']}/{urllib.parse.quote(self.bot)}/completion/{self.llm_type}",
                                                                request_method="POST",
                                                                request_body=body,
                                                                timeout=timeout)
+try:
+    http_response, status_code, elapsed_time, _ = await ActionUtility.execute_request_async(
+        http_url=f"{Utility.environment['llm']['url']}/{urllib.parse.quote(self.bot)}/completion/{self.llm_type}",
+        request_method="POST",
+        request_body=body,
+        timeout=timeout)
+except asyncio.TimeoutError:
+    logging.error(f"LLM request timed out after {timeout}s for bot: {self.bot}")
+    raise

188-188: Consider using a constant for the default timeout value

Move the default timeout value to a constant at the module level for better maintainability.

+DEFAULT_LLM_REQUEST_TIMEOUT = 30
-        timeout = Utility.environment['llm'].get('request_timeout', 30)
+        timeout = Utility.environment['llm'].get('request_timeout', DEFAULT_LLM_REQUEST_TIMEOUT)
kairon/shared/actions/utils.py (3)

59-59: Enhance parameter documentation.

Consider adding the parameter type and default value to the documentation:

-        @param timeout request timeout
+        @param timeout: Request timeout in seconds (default: None)

Line range hint 73-73: Add specific error handling for timeout exceptions.

The current implementation doesn't specifically handle timeout exceptions, which could make debugging timeout issues difficult.

Consider adding specific error handling:

         try:
             response = await client.request(request_method, http_url, request_body, headers, **kwargs)
             http_response = await response.json()
             response_headers = response.headers
+        except asyncio.TimeoutError as e:
+            logging.error(f"Request timed out after {timeout} seconds: {str(e)}")
+            raise ActionFailure(f"Request timed out after {timeout} seconds")
         except (ContentTypeError, ValueError) as e:
             logging.error(str(e))
             if response:
                 http_response = await response.text()

The execute_request_async calls are missing the timeout parameter.

Ensure all calls to execute_request_async include and correctly handle the timeout parameter.

  • kairon/shared/llm/processor.py
  • kairon/shared/live_agent/live_agent.py
  • kairon/actions/definitions/schedule.py
  • kairon/actions/definitions/http.py
🔗 Analysis chain

Line range hint 49-73: Verify timeout parameter usage across the codebase.

Let's ensure all callers of execute_request_async handle the new timeout parameter appropriately.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to execute_request_async to verify timeout parameter usage

# Search for execute_request_async calls
rg "execute_request_async\(" -A 2

Length of output: 2566

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 997fef9 and 4f31b37.

📒 Files selected for processing (4)
  • kairon/shared/actions/utils.py (2 hunks)
  • kairon/shared/llm/processor.py (1 hunks)
  • system.yaml (1 hunks)
  • tests/testing_data/system.yaml (1 hunks)
🔇 Additional comments (2)
tests/testing_data/system.yaml (1)

208-208: LGTM! Verify timeout sufficiency across LLM providers

The 30-second default timeout is reasonable for most LLM requests. However, please verify that this duration is sufficient across all supported LLM providers, especially during high-load scenarios.

kairon/shared/actions/utils.py (1)

49-50: LGTM! Method signature change is backward compatible.

The addition of the optional timeout parameter maintains backward compatibility and follows Python conventions.

Comment on lines +65 to +66
if not timeout:
timeout = Utility.environment['action'].get('request_timeout', 1)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Review default timeout value and add validation.

Issues identified:

  1. The default timeout of 1 second might be too short for many HTTP requests, potentially causing premature timeouts
  2. Missing validation for negative timeout values

Consider applying these changes:

         if not timeout:
-            timeout = Utility.environment['action'].get('request_timeout', 1)
+            timeout = Utility.environment['action'].get('request_timeout', 30)
+        if timeout is not None and timeout <= 0:
+            raise ValueError("Timeout must be a positive number")
📝 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
if not timeout:
timeout = Utility.environment['action'].get('request_timeout', 1)
if not timeout:
timeout = Utility.environment['action'].get('request_timeout', 30)
if timeout is not None and timeout <= 0:
raise ValueError("Timeout must be a positive number")

Copy link
Collaborator

@hiteshghuge hiteshghuge left a comment

Choose a reason for hiding this comment

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

approved

@hiteshghuge hiteshghuge merged commit 8632333 into master Nov 13, 2024
8 checks passed
@sfahad1414 sfahad1414 deleted the llm-timeout branch December 13, 2024 03:39
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