Skip to content

fix: keep conversation notes working when BYOK falls back to Anthropic - #21415

Merged
Git-on-my-level merged 3 commits into
mainfrom
fix/errfix-1013-gcp-process-conversation-py-620-fastapi
Oct 14, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
fix/errfix-1013-gcp-process-conversation-py-620-fastapi

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Summary

Conversation processing returned HTTP 500 when a user's BYOK key fell back from OpenAI to Anthropic. Shaped notes only cloned ChatOpenAI, so the Anthropic client raised TypeError before the notes call, and _get_structured wrapped that as a generic 500.

Error group

{"source": "gcp", "service": "backend", "group": "process_conversation.py:620 | fastapi.exceptions.HTTPException: 500: Error processing conversation, please try again later", "count": 2, "id": "gcp:backend-process-conversation-py-620-fastapi-exceptions-httpexception-500-error-processing-conversation-please-", "fingerprint": "fp:9dd85ca8e8f50576"}

Root cause

The group frame is the catch-all in _get_structured. The chained exception in production logs is:

TypeError: Shaped notes requires the configured OpenAI-compatible notes lane

raised from isolated_notes_model after:

omi_fallback_event component=other from=openai to=anthropic reason=byok outcome=recovered

get_llm('conv_structure') correctly returned ChatAnthropic. Notes isolation rejected every non-ChatOpenAI model, so those conversations never reached the provider.

Fix

Give Anthropic BYOK the same loop-local HTTP client the OpenAI lane already gets: copy the model, attach a fresh httpx.AsyncClient for that worker loop, and leave the cached model untouched.

Verification

python3.11 -m py_compile backend/utils/llm/shaped_notes_transport.py backend/tests/unit/test_shaped_agent.py
# exit 0

pyright -p backend/pyrightconfig.json backend/utils/llm/shaped_notes_transport.py
# 0 errors, 0 warnings, 0 informations

pytest tests/unit/test_shaped_agent.py -q
# 60 passed

Failure-Class: none

View guided diff Turn on auto-fix

Git-on-my-level and others added 2 commits October 13, 2026 22:54
Shaped notes cloned only ChatOpenAI, so an OpenAI-to-Anthropic BYOK fallback raised TypeError and the conversation endpoint returned HTTP 500.

Co-authored-by: Cursor <[email protected]>
Pyright rejects reading ChatAnthropic's protected client-params cache, which blocked the BYOK notes isolation from typechecking.

Co-authored-by: Cursor <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-14T06:40:17.242616Z fa8e8ad New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…rocess-conversation-py-620-fastapi

Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	backend/tests/unit/test_shaped_agent.py
#	backend/utils/llm/shaped_notes_transport.py

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fa8e8ad9fa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +54 to +55
params['http_client'] = transport
isolated.__dict__['_async_client'] = anthropic.AsyncClient(**params)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the model timeout on the isolated transport

When an Anthropic notes request takes more than five seconds, injecting the plain httpx.AsyncClient() created below causes the request to use HTTPX's default five-second timeout rather than the model's configured 60-second conv_structure deadline. Passing timeout to anthropic.AsyncClient does not reconfigure a caller-supplied HTTP client, so longer conversation-note generations still fail with a timeout and HTTP 500. Construct the loop-local transport with model.default_request_timeout (or otherwise apply that timeout directly to it) before injecting it.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit c1119b6 into main Oct 14, 2026
64 of 66 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/errfix-1013-gcp-process-conversation-py-620-fastapi branch October 14, 2026 07:28
Git-on-my-level added a commit that referenced this pull request Oct 17, 2026
…1779)

# fix(backend): answer a spent BYOK provider account as a typed 429, not
the generic 500

## Error group

```
{"source": "gcp", "service": "backend", "group": "process_conversation.py:632 | fastapi.exceptions.HTTPException: 500: Error processing conversation, please try again later", "count": 8, "id": "gcp:backend-process-conversation-py-632-fastapi-exceptions-httpexception-500-error-processing-conversation-please-", "fingerprint": "fp:9dd85ca8e8f50576", "queued_pr": 21415, "queue_reason": "reopened"}
```

## Root cause

`_get_structured`'s composition boundary maps every unmapped failure to
the generic 500. The recurrence is driven by the direct Anthropic BYOK
notes lane (the lane #21415 repaired): when a user's own Anthropic
account runs out of prepaid credit, every notes call fails before
generation and retries can never succeed. Prod evidence (project
`based-hardware`, 2026-10-15):

- `ERROR:utils.llm.gateway_error_contract:Conversation processing
failed: BadRequestError` recurring for the same uids/conversations while
clients re-poll (`get_conversation_by_id` every minute for an hour).
- Notes receipts at each failure: `errors=1 latency_seconds≈0.5
words=13086` and `errors=1 latency_seconds=0.470 words=16573` — instant
provider rejection, no generation; successes run 5–13s at ≤3.3k words.
- Full chained traceback for the exact group frame
(`/app/utils/conversations/process_conversation.py:632`):
  ```
File "/app/utils/conversations/process_conversation.py", line 611, in
_get_structured
    structured = llm_input_dedupe.notes(
File "/app/utils/llm/conversation_processing.py", line 466, in
model_turn
    response = await call_model.ainvoke(messages)
anthropic.BadRequestError: Error code: 400 - {'type': 'error', 'error':
{'type': 'invalid_request_error',
'message': 'Your credit balance is too low to access the Anthropic API.
Please go to Plans &
Billing to upgrade or purchase credits.'}, 'request_id':
'req_011Cg4rH8bexiFHHMid3brWg'}
  ```

This account state is the same class the platform already treats as
"throttled BYOK, not a server bug": the gateway classifies it as
`byok_quota` and answers 429 (`_THROTTLED_FAILURE_CLASSES`, because
"answering 401 tells callers the key is invalid and makes a transient
failure look permanent"), and the composition boundary already carries
that typed contract for `byok_rate_limit` (#11112). Quota had no
detection, so it fell into the generic 500 bucket — the user gets an
unhelpful "try again later" for a state only they can fix, and this
error group keeps reopening.

## Fix

`backend/utils/llm/gateway_error_contract.py`:

- Add `BYOK_QUOTA_FAILURE_CLASS`/`BYOK_QUOTA_ERROR_DETAIL` mirroring the
rate-limit contract, and `is_byok_quota_error()`, which recognizes both
forms of the failure: the gateway's `credential_failure` + `byok_quota`
envelope (raised and SDK-unwrapped, HTTP 429) and direct Anthropic
BYOK's `BadRequestError` 400 whose provider message carries Anthropic's
stable "credit balance is too low" wording. Marker text is used only for
classification — never logged or echoed.
- `conversation_processing_http_exception()` now maps that class to
`429` with `{'code': 'byok_quota', 'message': ...}`, logging a bounded
warning like the rate-limit case. All other exceptions keep the existing
generic 500 and privacy-safe log.

No fallback to the managed lane is introduced: the gateway's fallback
policy deliberately never falls back on `byok_quota`-class account
state.

## Verification

- `py_compile` on both touched files: OK.
- New suite
`backend/tests/unit/test_conversation_structure_byok_quota.py` (built
from the live prod signature, real `anthropic.BadRequestError`
instances):
  ```
14 passed in 9.06s (test_conversation_structure_byok_quota.py +
test_conversation_structure_provider_timeout.py)
  ```
- Contract consumers unchanged:
  ```
82 passed (test_llm_gateway_openai_compatible.py +
test_process_conversation_usage_context.py)
  ```
- `black --line-length 120 --skip-string-normalization --check`: both
files unchanged.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/21779?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/21779?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F21779&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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.

1 participant