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 #17: Add rate limit to the Core class #19

Closed
wants to merge 2 commits into from

Conversation

frontboat
Copy link
Collaborator

@frontboat frontboat commented Jan 20, 2025

feat(core/env, llm-client): add optional ANTHROPIC_MIN_DELAY_MS env and minTimeBetweenRequestsMs config

  • Adds optional 'ANTHROPIC_MIN_DELAY_MS' in env.ts, defaulting to 0 if blank.
  • Extends LLMClient to accept and enforce minTimeBetweenRequestsMs from env.
  • Logs debug info when delaying for rate-limit prevention.
  • Ensures an empty env variable does not break the default behavior.

Summary by CodeRabbit

  • New Features

    • Added configuration for minimum delay between Anthropic API requests to help prevent rate limits
    • Introduced logging functionality for LLM client interactions
  • Improvements

    • Enhanced request management with configurable time intervals between API calls
    • Improved error handling and logging for LLM client

Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Walkthrough

This pull request introduces a new configuration mechanism to manage request delays when interacting with the Anthropic API. The changes span across multiple files, adding an environment variable ANTHROPIC_MIN_DELAY_MS and implementing a corresponding delay enforcement mechanism in the LLM client. The modification aims to help prevent potential rate limiting by introducing a configurable minimum time interval between API requests.

Changes

File Change Summary
.env.example Added ANTHROPIC_MIN_DELAY_MS configuration variable
packages/core/src/core/env.ts Added optional ANTHROPIC_MIN_DELAY_MS to envSchema with integer parsing
packages/core/src/core/llm-client.ts Updated LLMClientConfig interface, added enforceMinDelay method, modified constructor to support logging and delay management

Sequence Diagram

sequenceDiagram
    participant Client as LLMClient
    participant API as Anthropic API
    
    Client->>Client: Check last request timestamp
    alt Time since last request < min delay
        Client-->>Client: Wait remaining time
    end
    
    Client->>API: Send request
    API-->>Client: Receive response
    Client->>Client: Update last request timestamp
Loading

Possibly related PRs

Poem

🐰 Hop, hop, delay we'll track,
API requests on a measured track,
Milliseconds dancing, neat and clean,
No rate limit shall break our coding dream!
Rabbit's wisdom in each request's pace 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

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

🧹 Nitpick comments (2)
packages/core/src/core/env.ts (1)

15-18: Consider adding input validation for ANTHROPIC_MIN_DELAY_MS.

The implementation looks good, but consider adding validation to ensure the delay is non-negative and reasonable (e.g., not exceeding 60000ms).

   ANTHROPIC_MIN_DELAY_MS: z
   .string()
   .optional()
-  .transform((val: string | undefined) => (val ? parseInt(val, 10) : 0)),
+  .transform((val: string | undefined) => (val ? parseInt(val, 10) : 0))
+  .refine((val) => val >= 0 && val <= 60000, {
+    message: "ANTHROPIC_MIN_DELAY_MS must be between 0 and 60000ms"
+  }),
.env.example (1)

16-17: Enhance documentation for ANTHROPIC_MIN_DELAY_MS.

The comment is helpful but could be more specific about the configuration details.

-# Optional: Set a minimum delay between Anthropic requests to prevent rate limits (eg 2000 and increase until resolved)
+# Optional: Minimum delay between Anthropic API requests in milliseconds
+# - Default: 0 (no delay)
+# - Recommended range: 1000-5000ms
+# - Increase if you encounter rate limits
+# - Note: Higher values will impact response times
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 14f6369 and e615f21.

📒 Files selected for processing (3)
  • .env.example (1 hunks)
  • packages/core/src/core/env.ts (1 hunks)
  • packages/core/src/core/llm-client.ts (5 hunks)
🔇 Additional comments (1)
packages/core/src/core/llm-client.ts (1)

26-26: LGTM: Config handling is well-implemented.

Good implementation of the config with proper fallback to env variable when not explicitly provided in the config.

Also applies to: 63-67

Comment on lines +48 to +49
private lastRequestTimestamp = 0;
private logger: Logger;
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

Potential race condition in rate limiting implementation.

The current implementation of rate limiting might not work correctly in concurrent scenarios. The lastRequestTimestamp could be modified by another request between the delay check and the timestamp update.

Consider using a mutex or moving the timestamp update into the enforceMinDelay method:

 private async enforceMinDelay(): Promise<void> {
   if (this.config.minTimeBetweenRequestsMs > 0) {
     const now = Date.now();
     const elapsed = now - this.lastRequestTimestamp;
     const remaining = this.config.minTimeBetweenRequestsMs - elapsed;
     if (remaining > 0) {
       this.logger.debug(
         "LLMClient.enforceMinDelay",
         `Waiting ${remaining} ms to respect minTimeBetweenRequestsMs`,
         {
           lastRequestTimestamp: this.lastRequestTimestamp,
           now,
         }
       );
       await setTimeout(remaining);
     }
+    this.lastRequestTimestamp = Date.now();
   }
 }

And remove the timestamp update from the complete method:

 public async complete(prompt: string): Promise<LLMResponse> {
   await this.enforceMinDelay();
   let lastError: Error | null = null;
   for (let attempt = 1; attempt <= this.config.maxRetries; attempt++) {
     try {
       const result = await this.executeCompletion(prompt);
-      this.lastRequestTimestamp = Date.now();
       return result;

Also applies to: 128-145

packages/core/src/core/llm-client.ts Show resolved Hide resolved
Comment on lines +63 to +67
// Pull from config if set, otherwise from env if not explicitly provided:
minTimeBetweenRequestsMs:
typeof config.minTimeBetweenRequestsMs === "number"
? config.minTimeBetweenRequestsMs
: env.ANTHROPIC_MIN_DELAY_MS, // fallback to env value
Copy link
Contributor

Choose a reason for hiding this comment

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

default should be an amount - i'm not sure we need to have this as an ENV var. It should just be a config when you make your dream chain

Copy link
Contributor

@ponderingdemocritus ponderingdemocritus left a comment

Choose a reason for hiding this comment

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

one comment

@frontboat
Copy link
Collaborator Author

10-4. Will reopen after fetching and updating

@frontboat frontboat closed this Jan 21, 2025
@frontboat frontboat deleted the fix-issue-17 branch January 21, 2025 15:25
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