fix(backend): tag BYOK LLM errors by source
Summary
- add BYOK uid context propagation for HTTP, WebSocket, and background processing
- log LLM failures with platform vs BYOK source, provider, feature, model, operation, uid, status, and reason
- attach LangChain error callbacks to OpenAI, OpenRouter, Gemini, and embedding clients
- offload async Anthropic-agent error handling to the shared executor so logging work does not block the event loop
Closes #7290
Verification
- PATH=/tmp/omi-backend-py311/bin:$PATH ./test-preflight.sh
- PATH=/tmp/omi-backend-py311/bin:$PATH pytest tests/unit/test_byok_llm_logging.py -q
Greptile Summary
This PR adds structured BYOK vs. platform source tagging to LLM error logs across HTTP, WebSocket, and background processing paths. A new byok_errors module provides classify_byok_llm_error and handle_llm_error, a _LLMErrorCallback LangChain handler wires them into OpenAI/OpenRouter/Gemini/embedding clients, and a _byok_uid_ctx ContextVar propagates the authenticated uid through async tasks and thread-pool executors.
byok.py: adds_byok_uid_ctxContextVar with get/set helpers;BYOKMiddleware,validate_byok_request, andvalidate_byok_websocketall reset/set it correctly.byok_errors.py: new module classifies errors (401 →invalid, 403 →permission, 429+quota-keyword →quota) and logs a structured 10-field message;handle_llm_error_asyncoffloads work tostorage_executorviasubmit_with_contextto preserve request context.clients.py: introduces_with_llm_callbacksto uniformly attach the usage callback and the new error callback; wraps_OpenAIEmbeddingsProxyembedding methods directly sinceOpenAIEmbeddingshas no LangChain callback mechanism.
Confidence Score: 4/5
Safe to merge; changes are observability-only and do not alter any request path or data handling logic.
The ContextVar plumbing is correct across all three entry points. The main gaps are that Anthropic credit-exhaustion 429s don't contain the word 'quota' so they log reason='unknown', and platform client factories register callbacks without feature context so platform failures always log feature='unknown'. Neither affects correctness.
backend/utils/llm/byok_errors.py (quota keyword coverage) and backend/utils/llm/clients.py (feature context for platform callbacks)
Important Files Changed
| Filename | Overview |
|---|---|
| backend/utils/llm/byok_errors.py | New module: structured logging for LLM failures with BYOK/platform source tagging; classification logic may miss non-OpenAI quota error messages |
| backend/utils/llm/clients.py | Adds _LLMErrorCallback LangChain handler and _with_llm_callbacks helper; platform-level clients use feature='' losing feature context in error logs |
| backend/utils/byok.py | Adds _byok_uid_ctx ContextVar and get/set helpers; BYOKMiddleware correctly resets uid token on every request |
| backend/routers/pusher.py | Propagates uid to the byok context in _process_conversation_task when BYOK keys are present |
| backend/routers/sync.py | Background pipeline sets byok_uid when BYOK keys are present and always resets to None in the finally block |
| backend/utils/retrieval/agentic.py | Replaces bare logger.error with handle_llm_error_async for Anthropic agent errors |
| backend/tests/unit/test_byok_llm_logging.py | New unit tests cover classification, source tagging, uid recording, and callback wiring; only OpenAI-style error shapes are exercised |
Comments Outside Diff (1)
-
backend/utils/llm/clients.py, line 480-493 (link)Platform LLM errors always log
feature='unknown'_get_or_create_openai_llm,_get_or_create_openrouter_llm,_get_or_create_gemini_llm, andllm_miniall call_with_llm_callbackswith the defaultfeature='', whichhandle_llm_errormaps to'unknown'. Because client instances are cached before any request arrives, there is no opportunity to inject a per-feature callback at creation time. Every platform LLM failure in production logsfeature=unknown, significantly reducing the usefulness of the structured log field for platform-side triage.
Reviews (1): Last reviewed commit: "fix(backend): tag BYOK LLM errors by sou..." | Re-trigger Greptile
Thanks for this 🙏 — it needs a manual rebase before it can land. main has substantially rewritten _run_sync_pipeline since this PR was opened: the pipeline is now wrapped in a concurrency semaphore and every blocking call is offloaded via run_blocking(db_executor, …) / run_blocking(storage_executor, …). main also already sets/resets the core BYOK key context (set_byok_keys) in the pipeline.
The result is 3 large structural conflicts in backend/routers/sync.py where this PR's diff is against the old synchronous body. Auto-resolving would mean re-applying main's async refactor by hand while threading in the new set_byok_uid tagging — too error-prone to guess on the prod sync/LLM path. Could you rebase onto latest main and re-apply just the set_byok_uid source-tagging on top of the new structure? Happy to land it once it's clean. 🙏
Thanks for this, @apoorvdarshan — really clean observability work. 🙏
Confirming what kodjima noted: this needs a rebase onto latest main before it can land (currently showing conflicts in sync.py). The structural async refactor there means the set_byok_uid calls will need to be re-threaded onto the new pipeline shape.
A couple of minor things worth noting while rebasing (non-blocking):
-
Platform errors log
feature=unknown:_get_or_create_openai_llm,_get_or_create_openrouter_llm,_get_or_create_gemini_llm, andllm_miniregister the error callback withfeature=''at client-creation time (before any request). Since clients are cached, there's no per-request hook to inject feature context. BYOK errors are fine (source is detected at call time), but platform-side triage will lose feature granularity. Worth a follow-up if that matters for your alerting. -
Quota classification keyword coverage:
classify_byok_llm_erroronly flags 429s asquotawhen the error text contains "insufficient_quota" or "quota". Anthropic credit-exhaustion (e.g. "credit balance too low") won't match, so those logreason=unknown. Low impact, but widening the keyword set would catch more actionable cases.
The ContextVar plumbing across HTTP middleware, WebSocket validation, and the background pipeline (set in setup, cleared in finally) looks correct. Tests cover classification logic, source tagging, uid recording, and callback wiring well. Once rebased cleanly this should be good to go.
@Git-on-my-level addressed the test-secret point in c2521afe6.
Swapped the realistic omi_-prefixed ENCRYPTION_SECRET in test_byok_llm_logging.py for an obviously-fake placeholder (omi_test-fake-encryption-secret-for-unit-tests), consistent with the existing sk-test-fake-for-unit-tests / ant-test-fake-for-unit-tests keys (kept ≥32 chars so the utils/encryption.py import-time length check still passes).
Heads-up: the same placeholder value is shared across several other unit-test fixtures, so I scoped this change to the file flagged here — happy to do a follow-up sweep to replace it across the suite if you'd prefer it consistent everywhere.
The manual rebase onto main you and @kodjima33 mentioned is still pending and tracked separately.
Thanks @apoorvdarshan — really solid observability work, and the placeholder secret fix in c2521afe looks good. 🙏
Just confirming the rebase need that @kodjima33 and @Git-on-my-level flagged: this still shows conflicts in sync.py against the current async pipeline shape, so the set_byok_uid calls will need re-threading onto the refactored structure before it can land.
Two small items worth handling during that rebase (both non-blocking):
-
Sync embedding methods bypass the new wrapper.
_OpenAIEmbeddingsProxy.embed_query/embed_documentsare explicitly defined on the class, so Python resolves them directly and the__getattr__-basedhandle_llm_errorwrapper never fires for the sync path (only the asyncaembed_*variants get tagged). Callinghandle_llm_error(...)in the existingexceptblocks of those two methods would close the gap so sync embedding failures get the samesource=tagging. -
Async fallback sanitization. In
handle_llm_error_async, the fallbackexceptlogs the raw exception (...: %s,e) withoutsanitize(), unlike the main path. Applyingsanitize(str(e))there would keep log-sanitization consistent.
The ContextVar plumbing across HTTP middleware, WebSocket validation, and the background pipeline (set in setup, cleared in finally) looks correct, and the test coverage for classification/source/uid/callback wiring is thorough. Once rebased cleanly this should be in good shape.
@Git-on-my-level thanks — folded both non-blocking items into f4104b5b:
- Sync embedding tagging.
_OpenAIEmbeddingsProxy.embed_query/embed_documentsnow callhandle_llm_error(...)in theirexceptblocks before falling back to Omi's key, so the sync path gets the samesource=tagging as the asyncaembed_*variants. Added a regression test. - Async fallback sanitization.
handle_llm_error_async's fallback now logssanitize(str(e)), consistent with the main path.
The sync.py rebase onto current main is the remaining item — it's a refactor migration (main split clients.py into model_config.py/providers.py), so I'd rather land it with the full backend suite green than push a blind resolution. Tackling that next.
Thanks @apoorvdarshan — f4104b5b cleanly addresses both items (sync embedding tagging + async fallback sanitization), and the regression test covering the BYOK→default-key fallback path is a nice touch. 🙏
The ContextVar plumbing across the HTTP middleware, WebSocket validation, and the background pipeline (set in setup, cleared in finally) all look correct, and handle_llm_error_async's use of submit_with_context correctly propagates the BYOK context into the executor thread.
One small robustness note to consider during the rebase (non-blocking): in _OpenAIEmbeddingsProxy.embed_query / embed_documents, handle_llm_error(...) now runs inside the except before the default-key fallback check. If logging itself ever raises unexpectedly, it would bypass self._default.embed_query(...) and the original error would be masked. Wrapping that call in its own try/except would keep the graceful BYOK→Omi fallback airtight:
try:
handle_llm_error(e, 'openai', feature='embeddings', model=self._model, operation='embed_query')
except Exception:
logger.exception('BYOK embeddings error logging failed')
The sync.py rebase onto current main is the remaining gate. Once that is clean and the backend suite is green, this should be in good shape.
Addressed the latest cubic finding in a20a4f44: the handle_llm_error(...) tagging calls in the embedding paths are now wrapped in try/except, so a failure inside the tagging call can no longer propagate out of the except block and skip the BYOK→Omi-key fallback (or mask the original embedding error). The tagging stays best-effort; the fallback always runs.