Devr.AI icon indicating copy to clipboard operation
Devr.AI copied to clipboard

feat: Implement LLM call caching

Open vaishcodescape opened this issue 10 months ago • 3 comments

Closes #241

📝 Description

This PR fixes the unnecessary LLM API calls made by the user either in the Discord or GitHub channels by implementing a multi-layer caching and optimization system for message classification.

🔧 Changes Made

cache_helpers.py

  • Simplified hashing: Replaced with single XXHash128, reducing CPU overhead and reducing collision
  • Added MAX_MESSAGE_LENGTH (10KB): Truncates oversized messages before processing to prevent DoS attacks and excessive memory usage patches security issues
  • Bounded in-flight tracking: Replaced unbounded _inflight dict with TTLCache(maxsize=1000, ttl=120) to prevent memory leaks from orphaned requests
  • Fixed orphaned future bug: Added asyncio.CancelledError handling to prevent request hangs when tasks are cancelled

classification_router.py

  • Added LLM concurrency limiter: Implemented asyncio.Semaphore(10) to limit concurrent LLM API calls, preventing rate limit errors and cost explosions during traffic spikes
  • Added message length validation: Early return for messages exceeding MAX_MESSAGE_LENGTH with fallback classification

Impact

Optimization Summary

Optimization Impact
Pattern matching fast-path 30-50% cached messages skip LLM entirely
Result caching Repeated questions served instantly
In-flight deduplication Concurrent identical requests share one LLM call
Concurrency limiter Max 10 simultaneous LLM calls

✅ Checklist

  • [x] I have read the contributing guidelines.
  • [x] I have added tests that prove my fix is effective or that my feature works.
  • [x] I have added necessary documentation (if applicable).
  • [x] Any dependent changes have been merged and published in downstream modules.

Summary by CodeRabbit

  • New Features
    • Added an asynchronous caching layer for message classification to speed repeated or similar requests.
    • Added pattern-based fast-path detection to return immediate results for common messages.
    • Deduplicated concurrent identical requests so only one backend call is performed.
    • Implemented concurrency limits and message-size safeguards to protect system stability.
    • Exposed runtime metrics for total requests, cache hits/misses, and skipped LLM calls.

✏️ Tip: You can customize this high-level summary in your review settings.

vaishcodescape avatar Jan 15 '26 10:01 vaishcodescape

📝 Walkthrough

Walkthrough

Adds a new asynchronous LLM caching layer (TTL LRU + in‑flight dedupe), message normalization and regex fast‑path classification, and integrates these into ClassificationRouter with concurrency limiting, message length guards, metrics, and fallback triage behavior.

Changes

Cohort / File(s) Summary
Caching Infrastructure
backend/app/classification/cache_helpers.py
New module: TTL LRU cache and in‑flight dedupe, stable key generation (XXHash or blake2b fallback), message normalization, regex pattern fast‑path classification, cache get/set helpers, async cached_llm_call orchestration, and metrics counters.
Classification Router Integration
backend/app/classification/classification_router.py
Integrates cache_helpers: adds a global semaphore for concurrency control, message length guard, normalization, fast‑path skip, normalized cache lookup/store, metrics increments, guarded LLM invocation, JSON parse of LLM payload, and fallback triage on error.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Message Request
    participant Router as ClassificationRouter
    participant Helper as cache_helpers
    participant Cache as TTL Cache
    participant Inflight as In‑flight Registry
    participant LLM as LLM Service

    Client->>Router: should_process_message(message, context)
    Router->>Helper: normalize_message(message)
    Helper-->>Router: normalized
    Router->>Helper: is_simple_message(normalized)
    Helper-->>Router: fast‑path result or None

    alt fast‑path
        Router-->>Client: return classification
    else
        Router->>Helper: key_for_normalized(normalized,...)
        Router->>Helper: get_cached_by_normalized(...)
        Helper->>Cache: lookup
        Cache-->>Helper: cached payload or miss
        Helper-->>Router: payload or None

        alt cache hit
            Router-->>Client: return cached classification
        else cache miss
            Router->>Inflight: check/register future for key
            alt another inflight exists
                Inflight-->>Router: await shared future -> result
            else owner:
                Router->>LLM: ainvoke(triage prompt) (guarded by semaphore)
                LLM-->>Router: response
                Router->>Helper: set_cached_by_normalized(..., payload)
                Router->>Inflight: resolve future + cleanup
            end
            Router-->>Client: return classification
        end
    end

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • AOSSIE-Org/Devr.AI#90 — Modifies classification subsystem and ClassificationRouter/triage logic in the same backend/app/classification area; likely related.

Suggested reviewers

  • chandansgowda

Poem

🐰 Hopping through prompts, I tidy and sort,

Keys clack and futures wait in a cozy fort.
Greetings answered quick, repeated asks spared,
One cached nibble saved many a call dared.
A rabbit's small hop and tokens are spared.

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: Implement LLM call caching' directly and accurately describes the primary change: adding caching functionality for LLM calls.
Linked Issues check ✅ Passed All coding requirements from issue #241 are implemented: pattern matching for simple messages, LRU cache with TTL, message normalization, in-flight deduplication, concurrency limiting, and metrics tracking.
Out of Scope Changes check ✅ Passed All changes are scoped to the caching and optimization objectives from issue #241. No unrelated modifications detected beyond the stated enhancement goals.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • [ ] 📝 Generate docstrings

🧹 Recent nitpick comments
backend/app/classification/cache_helpers.py (2)

14-19: Refine exception type to ImportError.

The xxhash import is correctly moved inside the try block, but catching broad Exception is overly permissive. Use ImportError for precision and to satisfy the static analysis hint (BLE001).

♻️ Proposed fix
 try:
     import xxhash
     _HAS_XXHASH = True
-except Exception:
+except ImportError:
     xxhash = None
     _HAS_XXHASH = False

101-104: Consider logging when JSON serialization fails.

The fallback to str(params) is reasonable but could produce inconsistent cache keys if params contains objects with unstable __str__ representations. Adding a debug log would help identify problematic inputs.

♻️ Proposed fix
     try:
         params_blob = json.dumps(params or {}, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")
-    except Exception:
+    except (TypeError, ValueError) as e:
+        logger.debug(f"JSON serialization failed for params, using str fallback: {e}")
         params_blob = str(params).encode("utf-8")

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9d1db32f30c6362be866cdfcf44d367c8df69156 and c66b9fb37ab833bc7ca10867d16778d16ea62a94.

📒 Files selected for processing (1)
  • backend/app/classification/cache_helpers.py
🧰 Additional context used
🪛 Ruff (0.14.11)
backend/app/classification/cache_helpers.py

17-17: Do not catch blind exception: Exception

(BLE001)


103-103: Do not catch blind exception: Exception

(BLE001)


188-188: Consider moving this statement to an else block

(TRY300)

🔇 Additional comments (5)
backend/app/classification/cache_helpers.py (5)

21-58: LGTM!

The configuration constants are sensible and the regex patterns are well-structured for fast-path classification. The patterns cover a good range of common message types including Discord-specific patterns.


82-87: LGTM!

Good use of bounded TTLCache for both the main cache and in-flight deduplication. The TTL on _inflight prevents memory leaks from orphaned requests.


141-224: Well-implemented async caching with proper task management.

The in-flight deduplication logic is solid:

  • Atomic future installation via setdefault correctly handles race conditions.
  • The owner task reference is stored and tracked.
  • Done callback propagates exceptions to waiting callers.
  • Cancellation is properly handled by cancelling the owner task and awaiting it.

The elapsed variable is now used for logging, and the task reference is properly managed.


226-231: LGTM!

The normalize_message function correctly handles truncation for DoS prevention, trims whitespace, lowercases, and collapses multiple whitespace characters into single spaces.


238-247: LGTM!

Simple and effective cache accessor functions with proper KeyError handling.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jan 15 '26 10:01 coderabbitai[bot]

@smokeyScraper @chandansgowda Can you review this I think I have implemented it the best I could any insights from you guys ?

vaishcodescape avatar Jan 15 '26 10:01 vaishcodescape

Hey, @smokeyScraper if you get the time can you please review this ?

vaishcodescape avatar Jan 20 '26 06:01 vaishcodescape