Skip to content

Commit fe3df5a

Browse files
Git-on-my-levelcursoragentmultica-agent
authored
SCA-365: route remaining HTTP LLM surfaces through the gateway (BasedHardware#12337)
* fix(backend): replace sunset Assistants file-chat with Chat Completions OpenAI retired Assistants on 2026-08-26, so every /v1/threads create 404s and non-vision file chat is down. Stream PDFs as Chat Completions file parts on gpt-4.1 (documented file-input contract) and keep images on the verified gpt-5.6-luna vision lane. Failure-Class: FC-pinned-vendor-request-contract-retired Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]> * fix(backend): satisfy Chat Completions typecheck without kwargs spread Unpacking a token-budget dict into create() is untyped and fails pyright. Failure-Class: FC-pinned-vendor-request-contract-retired Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]> * test(backend): make isolated file-chat CI unit stubs non-flaky CI ran each unit file in its own process; incomplete BYOK/LLM stubs and a duration-guard race on desktop transcribe failed the backend suite. Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]> * fix(stt): mark Soniox re-exports for strict pyright Upstream 7c900a9 moved the Soniox client into utils.stt.soniox but left SafeSonioxSocket / process_audio_soniox imported in streaming.py without a re-export marker; receiver.py and test_soniox_streaming.py import them through utils.stt.streaming, so strict pyright fails main and every PR merge ref. Carry the one-line marker so this backend CI lane can go green; matches the existing SafeDeepgramSocket compat re-export convention on the previous line. Co-authored-by: multica-agent <[email protected]> * feat(backend): route remaining LLM HTTP through gateway File-chat completions, company-paid desktop Vertex traffic (text + single embed), and both embedding surfaces now hop backend/llm_gateway so accounting (build_accounting_event / gateway metrics) is the single spend ledger when OMI_LLM_GATEWAY_FEATURE_MODE=gateway: - gateway: OpenAI-shaped /v1/embeddings surface (omi:auto:openai-embeddings, omi:auto:gemini-embeddings) with accounting; desktop-vertex-* chat lanes generated from vertex_pt_routing; VertexGeminiProvider owns the PT policy (pin, promotion latch, overflow ladder, reachability, capacity header, regional vs multi-region host split) and gains tools/toolConfig translation plus :predict embeddings; validator accepts file parts, json_object, and the extra_body-style google options field. - backend: chat_file streams/sync completions through the file-chat lanes (OpenAI Files upload/download stays direct by design); the OpenAI embeddings proxy and gemini_embed_query hop the gateway lanes with BYOK kept on documented thin direct paths; desktop_proxy stays the BFF (auth/metering/limits) and translates Gemini JSON via utils/llm/desktop_gemini_gateway.py, keeping BYOK and batchEmbedContents direct. - FEATURE_MODE=off keeps every legacy direct path (kill switch unchanged); inventory + guardrails updated; omni WS stays blocked. * refactor(backend): split vertex wire/policy and desktop gateway hop out of the ratcheted files providers.py and desktop_proxy.py grew past the product line-count ratchet; the vertex adapter's pure wire translation (vertex_wire.py), the PT policy mixin (vertex_pt_policy.py), shared provider types (provider_types.py), and the desktop BFF's gateway hop + Gemini body sanitization (utils/llm/desktop_gemini_gateway.py) move into focused modules with the original call sites and test seams preserved via re-exports. * fix(backend): keep Vertex token refresh on wall clock and attribute file-chat spend The gateway Vertex provider was sharing the PT monotonic clock with ADC token expiry, so tokens never refreshed after the first fetch. File-chat hops also omitted the user uid, leaving ledger rows unattributed, and the desktop tool-loop minted a new tool_call_id after the ordinal advanced. Failure-Class: none Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]> * fix(backend): restore embeddings BYOK async fallback and temporal test stubs Direct-path aembed_query/aembed_documents now notify and fall back to the Omi key on BYOK 401 like the sync methods. Hermetic app-integration harnesses stub utils.llm.temporal so collection survives the main merge that imports current_date_for_uid. Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]> * fix(backend): pin file-chat documents to gpt-5.6-luna Live probe confirmed Luna accepts the Chat Completions file-part contract, so the documents lane leaves gpt-4.1. Keep the separate file-chat-documents lane because the request shape still differs. Failure-Class: none Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]> --------- Co-authored-by: David Zhang <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: multica-agent <[email protected]>
1 parent 82a67a6 commit fe3df5a

49 files changed

Lines changed: 4598 additions & 1008 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎backend/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ STT provider/surface policy and model order live in `config/stt_provider_policy.
128128

129129
- **backend** (`main.py`) — REST API. Streams audio to pusher via WebSocket (`utils/pusher.py`). Calls diarizer for speaker embeddings (`utils/stt/speaker_embedding.py`). Calls vad for voice activity detection and speaker identification (`utils/stt/vad.py`, `utils/stt/speech_profile.py`). Live STT prefers Deepgram (`DEEPGRAM_API_KEY`), falling back to Modulate then Parakeet; self-hosted Deepgram replaces the hosted endpoint when `DEEPGRAM_SELF_HOSTED_*` is set (`utils/stt/streaming.py`). Calls NLLB translation when `HOSTED_TRANSLATION_API_URL` is set and NLLB is selected (`utils/translation.py`).
130130
- **hosted MCP OAuth** (`routers/mcp_sse.py`) — Provider-neutral OAuth for `/v1/mcp/sse`. Configure public or confidential clients with `MCP_OAUTH_CLIENTS_JSON`; allowlist the exact connector callback URI from the provider. The temporary `MCP_OAUTH_CHATGPT_*` envs still define the legacy confidential ChatGPT test client, and `MCP_OAUTH_PUBLIC_*` can expose a no-secret PKCE public client. Also set `MCP_AUTHORIZATION_SERVER_URL`, optional `MCP_RESOURCE_URL`, and token TTL env vars.
131-
- **llm-gateway** (`llm_gateway/main.py`) — Internal FastAPI service for Omi-managed LLM auto lanes. Called by backend with service auth for `omi:auto:*` chat-completions routes; not exposed to clients. Public shared-conversation chat uses only the dedicated `omi:auto:public-shared-conversation-chat` lane and returns unavailable on every gateway fault.
131+
- **llm-gateway** (`llm_gateway/main.py`) — Internal FastAPI service for Omi-managed LLM auto lanes. Called by backend with service auth for `omi:auto:*` chat-completions routes; not exposed to clients. Public shared-conversation chat uses only the dedicated `omi:auto:public-shared-conversation-chat` lane and returns unavailable on every gateway fault. Also owns the `/v1/embeddings` surface and the company-paid desktop-Vertex lanes (see `docs/llm/model_endpoint_inventory.yaml`).
132132
- Conversation notes v2 is independently dogfood-gated by `CONVERSATION_NOTES_V2_ENABLED`, `CONVERSATION_APPS_OPT_IN_ONLY`, `CONVERSATION_CALENDAR_CONTEXT_READ_ENABLED`, and `CONVERSATION_OCR_CONTEXT_ENABLED`; all runtime-manifest defaults stay off until promoted.
133133
- Meeting identity reaches the summarization prompt through `utils/conversations/meeting_context.resolve_meeting_context`, called before `_get_structured`. Sources, best first: stored calendar-backed meeting (exact `redis_db` conversation→meeting mapping, else a time-overlap query over `users/{uid}/meetings`) → `calendar_meeting_context` on the create request → overlapping Google Calendar event (read-only) → stored on-device screen-derived identity → server-side conferencing-window OCR. Every layer degrades to no context; none may fail the conversation. The stored-meeting layer is on by default with `CONVERSATION_STORED_MEETING_CONTEXT_ENABLED` as its kill switch. Calendar **write-back** stays behind `GOOGLE_CALENDAR_AUTO_LINK_ENABLED` and still runs only after summarization.
134134
- `users/{uid}/meetings` is populated only through `POST /v1/calendar/meetings`. The macOS client writes flag-gated EventKit identity as `system_calendar` and minimum on-device OCR-derived identity as `screen_activity` before conversation processing; the resolver always ranks a real calendar event above `screen_activity`.

‎backend/database/chat.py‎

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -804,18 +804,6 @@ def add_files_to_chat_session(uid: str, chat_session_id: str, file_ids: List[str
804804
_update_chat_session_if_exists(uid, chat_session_id, {"file_ids": firestore.ArrayUnion(file_ids)}, "file link")
805805

806806

807-
def update_chat_session_openai_ids(uid: str, chat_session_id: str, thread_id: str, assistant_id: str) -> None:
808-
"""Update OpenAI thread and assistant IDs for a chat session"""
809-
update_data: Dict[str, str] = {}
810-
if thread_id:
811-
update_data['openai_thread_id'] = thread_id
812-
if assistant_id:
813-
update_data['openai_assistant_id'] = assistant_id
814-
815-
if update_data and _update_chat_session_if_exists(uid, chat_session_id, update_data, "openai id link"):
816-
logger.info(f"Updated session {chat_session_id} with thread {thread_id} and assistant {assistant_id}")
817-
818-
819807
# **************************************
820808
# ********* MIGRATION HELPERS **********
821809
# **************************************
@@ -877,7 +865,7 @@ def migrate_chats_level_batch(uid: str, message_doc_ids: List[str], target_level
877865
# CHAT SESSIONS (v2)
878866
#
879867
# v2 sessions support: title, preview, message_count, starred, updated_at.
880-
# v1 sessions store: message_ids, file_ids, openai_thread_id.
868+
# v1 sessions store: message_ids, file_ids (legacy docs may still carry openai_thread_id).
881869
# Both schemas coexist in the same Firestore collection.
882870
# Both MUST write plugin_id alongside app_id for cross-platform query compat.
883871
# ============================================================================

‎backend/docs/llm/model_endpoint_inventory.yaml‎

Lines changed: 40 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,8 @@
11
schema_version: llm_model_endpoint_inventory.v1
22
scope:
3-
in_scope: backend chat/completion/generation/model calls, including streaming, tool calling, image generation, file chat, realtime relay, and provider web search
4-
out_of_scope: embeddings/vector APIs only
5-
out_of_scope_surfaces:
6-
- surface: openai_embeddings
7-
code_path: backend/utils/llm/clients.py:OpenAIEmbeddings,generate_embedding
8-
provider_model: openai/text-embedding-3-large
9-
request_shape: embedding
10-
reason: Embeddings are explicitly out of scope for this phase.
11-
- surface: gemini_screen_activity_query_embedding
12-
code_path: backend/utils/llm/clients.py:gemini_embed_query
13-
provider_model: gemini/embedding-001
14-
request_shape: embedding
15-
reason: Embeddings are explicitly out of scope for this phase.
3+
in_scope: backend chat/completion/generation/model calls, including streaming, tool calling, image generation, file chat, realtime relay, provider web search, and embeddings
4+
out_of_scope: none
5+
out_of_scope_surfaces: []
166
model_config_features:
177
status: gateway_lane_generated_from_model_config
188
source_of_truth: backend/utils/llm/model_config.py
@@ -72,11 +62,14 @@ model_config_features:
7262
tool_calling:
7363
- chat_agent
7464
- memory_l2
65+
file_chat:
66+
- file_chat_vision
67+
- file_chat_documents
7568
provider_search:
7669
- web_search
7770
pinned:
7871
- fair_use
79-
gateway_capability_needed: OpenAI-compatible chat-completions lane with provider refs for openai, native Vertex Gemini, openrouter, perplexity, and anthropic.
72+
gateway_capability_needed: OpenAI-compatible chat-completions lane with provider refs for openai, native Vertex Gemini, openrouter, perplexity, and anthropic; OpenAI-compatible /v1/embeddings surface with openai and native Vertex :predict adapters.
8073
migration_status: get_llm centrally switches Omi-managed feature traffic to generated gateway lanes with OMI_LLM_GATEWAY_FEATURE_MODE=gateway and does not retain a direct-provider fallback; gateway Gemini uses native Vertex generateContent authenticated by GKE Workload Identity; Gemini BYOK remains unsupported and fails closed.
8174
test_guardrail_coverage:
8275
- backend/tests/unit/test_llm_gateway_coverage_guardrails.py::test_every_model_config_feature_has_inventory_and_gateway_lane
@@ -125,19 +118,40 @@ surfaces:
125118
migration_status: gateway_only_fail_closed
126119
test_guardrail_coverage: backend/tests/unit/test_llm_gateway_client_config.py::test_app_icon_generation_always_uses_gateway
127120
- surface: file_chat_vision
128-
code_path: backend/utils/other/chat_file.py:_ask_vision_stream
129-
current_provider_model: openai/gpt-5.6-luna
130-
request_shape: streaming vision chat completion
131-
gateway_lane_capability_needed: gateway-owned vision chat lane or file-chat replacement retrieval path
132-
migration_status: acknowledged_direct_file_lifecycle_surface; intentionally remains direct during OMI_LLM_GATEWAY_FEATURE_MODE=gateway and records direct-exception telemetry without raising (PR #11419)
133-
test_guardrail_coverage: backend/tests/unit/test_llm_gateway_coverage_guardrails.py
134-
- surface: file_chat_assistants
121+
code_path: backend/utils/other/chat_file.py:_ask_files_stream
122+
current_provider_model: gateway lane omi:auto:file-chat-vision (openai/gpt-5.6-luna); direct OpenAI only when OMI_LLM_GATEWAY_FEATURE_MODE is off
123+
request_shape: streaming vision chat completion (image_url data URIs)
124+
gateway_lane_capability_needed: generated omi:auto:file-chat-vision lane with image_url content parts
125+
migration_status: gateway_routed_file_chat; OpenAI Files upload/download stays direct by design (file bytes/file_id lifecycle, no model tokens) and the completions call hops the gateway in feature mode; BYOK OpenAI is not used (Files file_id namespace is company-owned, so completions stay Omi-paid)
126+
test_guardrail_coverage: backend/tests/unit/test_chat_file_gateway_surface.py and backend/tests/unit/test_chat_file_completions.py
127+
- surface: file_chat_completions
135128
code_path: backend/utils/other/chat_file.py:FileChatTool
136-
current_provider_model: openai/gpt-4.1 with Assistants, Threads, Files, File Search
137-
request_shape: file upload, assistants, file_search, streaming run deltas
138-
gateway_lane_capability_needed: gateway-owned file/assistant lifecycle or replacement retrieval path
139-
migration_status: acknowledged_direct_file_lifecycle_surface; intentionally remains direct during OMI_LLM_GATEWAY_FEATURE_MODE=gateway and records direct-exception telemetry without raising (PR #11419)
140-
test_guardrail_coverage: backend/tests/unit/test_llm_gateway_coverage_guardrails.py
129+
current_provider_model: gateway lane omi:auto:file-chat-documents (openai/gpt-5.6-luna file parts for PDFs); direct OpenAI only when OMI_LLM_GATEWAY_FEATURE_MODE is off
130+
request_shape: file upload purpose=user_data, streaming chat completion file input parts
131+
gateway_lane_capability_needed: generated omi:auto:file-chat-documents lane with OpenAI file content parts
132+
migration_status: gateway_routed_file_chat; Assistants/Threads retired after the 2026-08-26 sunset; OpenAI Files upload/download stays direct by design; BYOK OpenAI is not used (same company-owned file_id namespace as vision)
133+
test_guardrail_coverage: backend/tests/unit/test_chat_file_gateway_surface.py and backend/tests/unit/test_chat_file_completions.py
134+
- surface: desktop_gemini_proxy
135+
code_path: backend/routers/desktop_proxy.py:_proxy_unobserved
136+
current_provider_model: gateway lanes omi:auto:desktop-vertex-{flash,pro,target,flash-lite} and omi:auto:gemini-embeddings for company-paid generateContent/streamGenerateContent/embedContent; Gemini BYOK keeps a thin direct AI Studio path; batchEmbedContents stays direct AI Studio
137+
request_shape: Gemini JSON proxied for desktop clients; translated to OpenAI shape at the BFF (utils/llm/desktop_gemini_gateway.py) and back to Gemini native in the gateway Vertex adapter
138+
gateway_lane_capability_needed: desktop vertex lanes with PT pin/overflow and multi-region host policy in VertexGeminiProvider; OpenAI-shaped /v1/embeddings with task_type pass-through
139+
migration_status: gateway_routed_desktop_vertex; the BFF keeps auth, trial paywall, redis metering, body limits, and model allowlist; PT pin/overflow/host policy moved into the gateway provider via vertex_pt_routing (no second policy); FEATURE_MODE=off keeps the legacy direct Vertex path
140+
test_guardrail_coverage: backend/tests/unit/test_desktop_proxy.py and backend/tests/unit/test_vertex_pt_routing.py
141+
- surface: openai_embeddings
142+
code_path: backend/utils/llm/clients.py:_OpenAIEmbeddingsProxy
143+
current_provider_model: gateway lane omi:auto:openai-embeddings (openai/text-embedding-3-large); BYOK OpenAI keys are forwarded to the gateway with the omi-paid lane as fallback; direct OpenAIEmbeddings only when OMI_LLM_GATEWAY_FEATURE_MODE is off
144+
request_shape: OpenAI embeddings (embed_query/embed_documents, sync and async) for vector_db, mcp, app integrations, and conversation structuring
145+
gateway_lane_capability_needed: OpenAI-compatible /v1/embeddings surface on the gateway with accounting
146+
migration_status: gateway_routed_embeddings; FEATURE_MODE=off keeps the direct LangChain OpenAIEmbeddings kill-switch path
147+
test_guardrail_coverage: backend/tests/unit/test_llm_gateway_coverage_guardrails.py and backend/tests/unit/test_embeddings_gateway.py
148+
- surface: gemini_screen_activity_query_embedding
149+
code_path: backend/utils/llm/clients.py:gemini_embed_query
150+
current_provider_model: gateway lane omi:auto:gemini-embeddings (Vertex gemini-embedding-001 :predict) in feature mode; Gemini BYOK keys keep the thin direct AI Studio embedding-001 path because the gateway Vertex adapter fail-closes BYOK
151+
request_shape: single RETRIEVAL_QUERY embedding for screen-activity search
152+
gateway_lane_capability_needed: OpenAI-shaped /v1/embeddings with task_type/title pass-through onto the Vertex predict adapter
153+
migration_status: gateway_routed_embeddings; FEATURE_MODE=off keeps the direct AI Studio kill-switch path
154+
test_guardrail_coverage: backend/tests/unit/test_llm_gateway_coverage_guardrails.py and backend/tests/unit/test_embeddings_gateway.py
141155
- surface: omni_realtime_relay
142156
code_path: backend/routers/omni_relay.py
143157
current_provider_model: openai realtime or gemini live selected by client query

‎backend/docs/vertex-pt-flash.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,25 @@ same commit is the regression.
3838
BYOK Gemini stays on the user's key / AI Studio, and is never remapped: the
3939
user pays for the model they asked for.
4040

41+
42+
## Where the policy runs since the gateway move (2026-08)
43+
44+
Company-paid desktop `generateContent` / `streamGenerateContent` /
45+
`embedContent` now hop the LLM gateway (`OMI_LLM_GATEWAY_FEATURE_MODE=gateway`):
46+
`routers/desktop_proxy.py` stays the BFF (auth, trial paywall, redis metering,
47+
body limits, model allowlist) and translates Gemini JSON ↔ the gateway's
48+
OpenAI surface (`utils/llm/desktop_gemini_gateway.py`). The PT policy itself —
49+
pin, promotion latch, overflow ladder, reachability table, the capacity
50+
header, and the regional vs multi-region host split — lives in the gateway's
51+
`VertexGeminiProvider` (`backend/llm_gateway/gateway/providers.py`), driven by
52+
the same `backend/utils/llm/vertex_pt_routing.py` this document describes:
53+
there is no second policy. The desktop proxy keeps its in-process copy only
54+
for the `FEATURE_MODE=off` kill-switch path. The gateway deployment must
55+
therefore keep `GOOGLE_CLOUD_PROJECT` and `GCP_LOCATION` set on the
56+
`llm_gateway` service too, and the operator env pins
57+
(`OMI_VERTEX_PT_MODEL`, `OMI_GEMINI_OVERFLOW_MODEL`,
58+
`OMI_GEMINI_OVERFLOW_ENABLED`, `OMI_VERTEX_GLOBAL_LOCATION`) apply to the
59+
**gateway** process once feature mode is on.
4160
## Model prices (Vertex list, captured 2026-08-18)
4261

4362
| Model | Input $/1M | Output $/1M |

0 commit comments

Comments
 (0)