Skip to content

fix(gateway): report real token usage from the OpenAI-compatible embeddings endpoint - #154721

Merged
steipete merged 9 commits into
openclaw:mainfrom
xialonglee:fix/gap-embeddings-usage-zero-passthrough
Oct 10, 2026
Merged

steipete merged 9 commits into
openclaw:mainfrom
xialonglee:fix/gap-embeddings-usage-zero-passthrough

Conversation

@xialonglee

@xialonglee xialonglee commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: /v1/embeddings reports zero token usage even when the embedding provider returns actual token counts.

User Impact

Clients receive provider-reported counts through native Ollama and OpenAI-compatible embedding transports. Providers that report zero keep zero; missing or incomplete counts remain zero without estimates. Existing embedding plugins retain their vector-only return values. No configuration, stored data, or migration changes are required.

Why This Change Was Made

Usage was discarded by response parsers, and the Gateway hard-coded both usage fields. The existing embedding call options now carry an optional onUsage observer. Parsers validate external counts, providers report each successful upstream response, and the Gateway sums complete reports. The same call path preserves model preload, service leases, cancellation, and deadlines; separate detailed-batch methods and their duplicate lifecycle wrappers are removed.

This preserves @xialonglee's original commits and contribution while merging current main and simplifying the implementation. Production: +95/−84 (net +11, reduced from the original net +178); tests/support: +123/−30; docs: +9/−0; assertion baseline: −1 for the removed Ollama cast. The remaining production growth supplies the optional typed observer and validates provider counts.

Evidence

Baseline captured before repair: ea6022cae60c509d8c0e8029ad8030557a917617, real isolated Gateway on loopback port 19232. With ["alpha","beta"], direct Ollama reports 7 tokens for bge-m3 and 6 for nomic-embed-text; both the native and /v1 Gateway paths returned 0/0. LM Studio text-embedding-nomic-embed-text-v1.5 reports upstream 0/0.

The existing Gateway regression failed on main production at its usage assertion (upstream 777/778, Gateway 0/0; wall 264.23s), then passed after the repair. All 116 tests across five files passed, combined wrapper wall 226.87s:

File Passing tests Vitest duration
Gateway embeddings HTTP 32 93.87s
OpenAI-compatible provider 9 31.59s
Native Ollama provider 43 61.98s
Remote response parsing 29 0.532s
Remote provider grouping 3 2.75s

The Gateway tests reuse the existing suite server. The changed HTTP usage assertion took 59ms; the new split-usage cases exercise complete totals and missing reports without additional Gateway boots. Provider tests cover singleton/batch reporting, zero, missing counts, and invalid counts.

Core and Ollama package typechecks, Gateway/plugins/packages test type graphs, scoped core/Ollama lint, SDK export checks, and all required baseline ratchets passed. Broad extension typechecking could not resolve QA Lab's crabbox-provider under the gateway-only dependency profile; the affected Ollama package was checked separately. An initial regression attempt overlapped setup and failed before test discovery on a generated-asset ENOENT; the settled run supplied the actual failing-before proof.

Live after proof on b645ca800f3f17035796406f5f73cf9f14b5480e, through the real isolated Gateway HTTP endpoint:

Local provider/model Before usage After usage Upstream count Vector dimensions
Ollama native / bge-m3 0/0 7/7 7 1024
Ollama native / nomic-embed-text 0/0 6/6 6 768
Ollama OpenAI-compatible / bge-m3 0/0 7/7 7/7 1024
Ollama OpenAI-compatible / nomic-embed-text 0/0 6/6 6/6 768
LM Studio / nomic-embed-text-v1.5 0/0 0/0 0/0 768

Every successful response contained two vectors. Example request (the native agent selects Ollama's native transport; compat selects its /v1 transport):

curl -sS http://127.0.0.1:19232/v1/embeddings \
  -H 'Authorization: Bearer YOUR_GATEWAY_TOKEN' \
  -H 'Content-Type: application/json' \
  -H 'x-openclaw-model: bge-m3' \
  -d '{"model":"openclaw/native","input":["alpha","beta"]}'

The isolated Gateway was stopped after proof. Shared Ollama and LM Studio services were left running. Slash-containing overrides are handled separately in #161170.

Full pnpm build passed on the live-tested head b645ca800f3f17035796406f5f73cf9f14b5480e (wall 1694.45s). The first full build reached final stamping but detected input changes while checks and maintenance were running; the successful retry was serialized with no concurrent writers. The earlier review preparation also refused changing artifacts, so the final independent review runs only after build and live proof settle.

Independent Codex branch autoreview was scoped-clean through P2 on the live-tested head, with final source verification passed.

Final merge resolution

Main advanced while verification ran and introduced caller-owned HTTP deadlines in the generic embedding transport. Merged main 9c241fea9080083518a64a2b3278d3e7f391167e without rewriting contributor history. The only conflict resolution preserves its fetchWithCallerDeadline dispatcher and reads the signal from callOptions?.signal instead of the removed params.signal. Merge-resolution head: 5c34c17e9d316bcb20981019ef5d5f5586f5eb18.

On the resolved head, all 11 generic-provider tests passed, including both new deadline cases (wall 287.61s); core typechecking (41.23s), scoped type-aware core lint, and affected line-cap, max-lines, and assertion ratchets passed. The earlier lint invocation unnecessarily entered plugin declaration preparation and hit its timeout; the canonical core config completed without that unrelated preparation.

The real Gateway matrix and full build above belong to b645ca8; they were reused for unchanged usage mapping, and no live run is claimed for the mechanical merge resolution. ClawSweeper's first exact-head review found no code issues, accepted the live proof, and requested only this main-conflict repair.

Fresh independent Codex branch autoreview on 5c34c17e9d316bcb20981019ef5d5f5586f5eb18: scoped-clean, no actionable P0–P2 findings; final source verification passed. The review explicitly checked the merged signal/deadline integration.

Repair inherited CI fixture

CI run 38009841853 on 5c34c17 exposed a deterministic 120 s timeout in memory-runtime.owners.test.ts's late-probe case. Main commit 603f60a38cfe (#167891) switched availability probes from embedBatch to embed, but the fixture still signaled its entry gate only from embedBatch. The real probe returned while the test waited forever for an unused stub. The exact new-main control also failed; older main passed.

Fixture-repair head eb710ad903121ff3f0cea0b8406e4cb5a91b9d48 moves the existing gate and probe-call assertions to an embed mock returning a flat vector, while retaining a batch-shaped embedBatch fallback. This is a six-line test-only correction with no budget increase, retry, production seam, or weakened assertion. The ownership file passes 17/17 (wall 150.81s), and the original seven-file/two-worker CI selection passes 101/101 (wall 195.43s). Scoped test types, type-aware lint, and affected line-cap, timeout-race, and mock-export ratchets pass.

Fresh independent Codex branch autoreview on eb710ad903121ff3f0cea0b8406e4cb5a91b9d48: scoped-clean through P2; final source verification passed. The reviewer also checked the ownership-fixture correction.

Preserve current response diagnostics

Main subsequently added contextual embedding errors in #168035. Final head 4f5fece0f60e1c1441bf80b0f0bbac5485d194b7 merges main a0197f4921be56a09126b9b96f583c84423de342, retaining its unknown-payload parsing, vector diagnostics, request/response logs, error mapping, and caller-abort behavior. Each adapter validates vectors before reporting usage. Usage assertions now use main's real HTTP Response fixture, including a valid JSON number that parses to infinity.

Both affected suites pass 43/43 (32 remote-response cases and 11 generic-provider cases), combined wall 266.85s. Core typechecking (56.15s), canonical type-aware scoped lint, and affected line-cap/max-lines/assertion/mock-export ratchets pass. The proven ownership fixture remains intact. These integrations use focused proof; the full build and real local-model matrix remain explicitly attributed to b645ca8.

Fresh independent Codex branch autoreview on 4f5fece0f60e1c1441bf80b0f0bbac5485d194b7: scoped-clean through P2; final source verification passed. Immediately before publication, a read-only merge against live main e09f3ecd491db23f4fdc6e79b4349808d010f394 was clean.

Final-head openclaw/ci-gate passed in run 38018085761. ClawSweeper’s exact-head review found no code issues and accepted the live proof and focused integration checks. Its requested maintainer direction is recorded below. No merge has been requested.

Maintainer direction

Use the additive, optional EmbeddingProviderCallOptions.onUsage callback as the supported public SDK contract for this repair. This is the requested design for propagating upstream embedding usage through the existing call contract. Preserve the vector return values of embed and embedBatch, compatibility with existing providers/callers, and zero usage when counts are unavailable. The callback adds no configuration, persistence, retention, or authority.

Main conflict repair (current head)

Current head d98e79d71fb13f7dbe0e0d4c6ca9c215034e5d22 merges main 2d6f7a3052a03867896f10d521969c78c4555d9a into the contributor branch without rewriting history. The only manual conflict resolution combines the HTTP helper's optional model-override header with its upstream usage assertion. Both slash-containing model coverage and usage coverage remain; production code merged automatically.

Focused embeddings validation passed 123/123 tests across five files, wall 590.51s. After reconciling the worktree's stale dependencies with the merged frozen lockfile, core types passed (160.66s), Gateway test types passed (55.32s), and scoped type-aware lint passed (84.11s). Line-cap, max-lines, assertion-safety, database-worker, test-timeout-race, test-mock-exports, config-docs, and plugin-inventory checks all passed. Independent Codex review of the frozen merge candidate was scoped-clean through P2.

A supplemental HTTP rerun after dependency reconciliation failed during the existing beforeAll Gateway startup hook at its 180-second deadline; all 34 cases were skipped, and teardown then encountered the uncreated server. Its wall time was 766.67s, including a cold compiled-worker rebuild. The setup/teardown path is unchanged by this PR and the conflict repair, but the local startup timeout remains unresolved; it is not represented as passing proof. No timeout increase or retry was used. Earlier live/build proof remains attached to its stated prior head. Current-head openclaw/ci-gate passed in run 38024880303; all 86 jobs completed successfully.

@clawsweeper

clawsweeper Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: lmstudio extensions: llama-cpp size: M labels Sep 21, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 21, 2026
@clawsweeper

clawsweeper Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR forwards provider-reported embedding token counts to the Gateway through an optional callback while preserving vector returns.

Example: POST /v1/embeddings with input ["alpha", "beta"] using native Ollama bge-m3.

  • Before: The provider reports 7 tokens, but the Gateway returns prompt_tokens: 0 and total_tokens: 0.
  • After: The Gateway returns prompt_tokens: 7 and total_tokens: 7 alongside two 1024-dimensional vectors.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, owner-approved repair with real Gateway proof, meaningful regression coverage, successful exact-head CI, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied live HTTP results exercise the real isolated Gateway with native Ollama, OpenAI-compatible Ollama, and LM Studio on b645ca8; source comparison and focused later checks preserve the usage behavior through the reviewed head. The supplemental startup timeout is disclosed and is not counted as passing evidence.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Embeddings clients receive zero token counts even when their provider supplies actual usage.
Reason: Accurate provider accounting has clear value, and the verified repository admin approved the additive SDK design without expanding configuration or persistence.

Merge readiness

✅ Ready for maintainer review

Keep this PR open for landing: current main still reports zero embedding usage, and this approved, proven repair has no actionable review findings.

Priority: P2
Reviewed head: d98e79d71fb13f7dbe0e0d4c6ca9c215034e5d22

Before merge

None.

Findings

None.

Agent review details

How this fits together

The authenticated Gateway embeddings endpoint selects the configured provider, sends text through its existing transport and lifecycle owners, and returns vectors plus reported usage.

flowchart LR
  A[HTTP client] --> B[Gateway authentication and routing]
  B --> C[Existing embedding provider call]
  C --> D[Provider HTTP transport]
  D --> E[Vector and usage parsing]
  E --> F[Gateway usage aggregation]
  F --> G[Embedding response]
Loading

Technical review

Best possible solution:

Land the approved optional observer repair through the existing provider contract, retaining zero when usage is unavailable.

Do we have a high-confidence way to reproduce the issue?

Current-main source discards provider usage and emits 0/0; supplied baseline Gateway results and the failing HTTP usage assertion independently establish the failure.

Is this the best way to solve the issue?

The optional observer fixes the shared parsing and call contract without a competing embedding path, while preserving cancellation, deadlines, service leases, and existing callers.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against fdb73933b276.

Provenance checked

  • Gateway usage response changes intended behavior with a stated reason (eaad4ad: The endpoint introduction supplied an OpenAI-compatible response with zero-valued usage placeholders.)
  • Canonical embedding provider and remote orchestration keeps the original intent (67d22a5: The merged refactor established one generic provider contract while preserving provider-specific batching and lifecycle behavior.)
  • Shared remote request grouping keeps the original intent (7475087: The shared factory owns canonical model/input fields, query grouping, cancellation, and vector validation.)
  • Local-service readiness and caller deadlines keeps the original intent (6dd7b2e: Managed readiness waits retain their separate budget while calls preserve caller cancellation and service leases.)
  • Availability-probe test fixture keeps the original intent (603f60a: Main moved availability probes to embed; this PR moves the existing fixture gate to that entry point without weakening ownership assertions.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still contains the bug: Fetched main hard-codes both usage fields to zero after provider.embedBatch; the central repair remains absent. (src/gateway/embeddings-http.ts:288, fdb73933b276)
  • Introduced repair: The pinned introduced diff adds usage reporting to the existing call options, validates external counts, and aggregates complete reports without changing vector return types. (src/gateway/embeddings-http.ts:271, d98e79d71fb1)
  • Verified owner direction: steipete explicitly approved the optional onUsage SDK contract in comment 6093161362; GitHub's collaborator-permission endpoint independently confirms repository admin access despite the comment's CONTRIBUTOR association. (src/plugins/embedding-provider-types.ts:28, d98e79d71fb1)
  • Supplied real Gateway proof: The PR body records before/after HTTP results on b645ca8 for native Ollama and Ollama's OpenAI-compatible transport: bge-m3 returns 7/7 and nomic-embed-text 6/6; LM Studio retains its upstream 0/0. Later integrations preserve the usage mapping and have focused validation. (b645ca800f3f)
  • Exact-head CI and mergeability: GitHub reports the reviewed head cleanly mergeable. Paginated checks contain no unfinished or failed runs, and openclaw/ci-gate succeeded on this exact head. (d98e79d71fb1)
  • Feature provenance: The zero-valued usage response appears in the endpoint introduction commit; subsequent provider-contract and orchestration refactors retain it. (src/gateway/embeddings-http.ts, eaad4ad1be38)

Likely related people:

  • Peter Steinberger: Raw commit 603f60a adds src/plugins/openai-compatible-embedding-provider.ts:303 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 603f60a38cfe; files: src/plugins/openai-compatible-embedding-provider.ts)
  • Vincent Koc: Raw commit e62c216 adds src/plugins/openai-compatible-embedding-provider.ts:357 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e62c216d75c9; files: src/plugins/openai-compatible-embedding-provider.ts)
  • wangmiao0668000666: Raw commit 6dd7b2e adds extensions/ollama/src/embedding-provider.runtime.ts:375 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6dd7b2e00b3e; files: extensions/ollama/src/embedding-provider.runtime.ts)
  • Peter Lee: Raw commit b90a911 adds src/gateway/embeddings-http.ts:147 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: b90a911280ad; files: src/gateway/embeddings-http.ts)

PR surface

Source +11, Tests +93, Docs +9, Other -1. Total +112 across 19 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 95 84 +11
Tests 7 123 30 +93
Docs 2 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 19 227 115 +112

Review metrics

Metric Value Why it matters
Production versus tests Production +95/-84; tests and support +123/-30 The small net production increase supplies typed usage reporting and validation; tests cover parsing, transport forwarding, and HTTP aggregation.
Public SDK addition One optional onUsage call option The approved additive observer preserves existing embed and embedBatch return types and requires no configuration or migration.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Incorrect token accounting affects embeddings API clients while vector delivery continues to work.
  • merge-risk: 🚨 compatibility: The public embedding SDK gains an optional callback; verified owner approval, documented semantics, and preserved vector contracts resolve the direction concern.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (14 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-29T06:59:17.397Z sha 934667a :: blocked before merge. :: none
  • reviewed 2026-10-09T23:58:03.829Z sha b645ca8 :: needs changes before merge. :: none
  • reviewed 2026-10-10T00:44:31.678Z sha 5c34c17 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T01:54:50.813Z sha eb710ad :: needs changes before merge. :: none
  • reviewed 2026-10-10T02:53:08.558Z sha 4f5fece :: blocked before merge. :: none
  • reviewed 2026-10-10T03:07:47.378Z sha 4f5fece :: blocked before merge. :: none
  • reviewed 2026-10-10T03:16:26.184Z sha 4f5fece :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T04:50:14.535Z sha d98e79d :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 12:57 AM ET / 04:57 UTC (Revision 15).

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 22, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 22, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 22, 2026
@xialonglee
xialonglee force-pushed the fix/gap-embeddings-usage-zero-passthrough branch from fda52d5 to 24e758d Compare September 22, 2026 13:36
@xialonglee
xialonglee force-pushed the fix/gap-embeddings-usage-zero-passthrough branch from 24e758d to 0660e48 Compare September 29, 2026 03:28
@xialonglee xialonglee changed the title fix(gateway): /v1/embeddings reports zero token usage even when the provider returns real usage fix(gateway): report real token usage from the OpenAI-compatible embeddings endpoint Sep 29, 2026
@xialonglee
xialonglee force-pushed the fix/gap-embeddings-usage-zero-passthrough branch from 0660e48 to f2ccc7f Compare September 29, 2026 04:19
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 29, 2026
@clawsweeper clawsweeper Bot removed the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 10, 2026
The caller-deadline change in openclaw#167891 moved availability probes from embedBatch to embed. Move the existing fixture gate and call-count assertions to the current entry point so late-probe exercises retained ownership instead of waiting forever for an unused batch stub.
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

Maintainer direction: the additive, optional EmbeddingProviderCallOptions.onUsage observer is the approved public SDK contract for this repair. Use the existing embedding call contract, keep embed/embedBatch vector returns and existing callers compatible, and retain zero when counts are unavailable. This records the requested design; no configuration, persistence, retention, or authority expansion is involved.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 10, 2026
@steipete steipete self-assigned this Oct 10, 2026
Resolve the shared HTTP fixture by preserving slash-model override forwarding and upstream token usage assertions.
@steipete
steipete merged commit 3cfab51 into openclaw:main Oct 10, 2026
154 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…ddings endpoint (openclaw#154721)

* fix(gateway): report real token usage from the OpenAI-compatible embeddings endpoint

The /v1/embeddings bridge hardcoded usage to zero and dropped upstream
usage during response parsing, so token tracking and billing middleware
always saw $0 while the sibling chat completions surface reports real
usage.

- Parse OpenAI-style usage in the openai-compatible provider and the
  shared memory-host-sdk remote fetch path (covers openai, voyage,
  lmstudio, mistral, deepinfra)
- Add an additive optional EmbeddingProvider.embedBatchDetailed that
  returns vectors plus provider-reported usage; embedBatch stays the
  canonical vector-only contract for existing plugin implementations
- Prefer detailed usage in the embeddings handler and fall back to a
  char-based estimate so both usage fields are always present
- Forward the detailed path through the lmstudio lease wrapper and the
  llama-cpp facts wrapper without bypassing their lifecycle semantics

* fix(memory-host-sdk): keep embeddings-remote-fetch within the allowed core bridge files

The package boundary contract allows only the embeddings.types.ts alias
to reference the canonical embedding provider contract. Route the
EmbeddingUsage type import through that alias so the memory-host-sdk
core bridge list stays unchanged.

* fix(memory-host-sdk): omit batch usage when any query response lacks usage

A detailed query batch fans out to one upstream request per input. When any
constituent response omits usage, the aggregated batch usage used to silently
undercount by reporting only the sum of the responses that did report. Return
undefined instead so callers fall back to estimation, pin the semantics on the
embedBatchDetailed contract, and add a mixed-response regression case.

Addresses ClawSweeper review finding on PR openclaw#154721.

* chore(embeddings): prune removed assertion allowance

* test(memory): gate reload probes through embed

The caller-deadline change in openclaw#167891 moved availability probes from embedBatch to embed. Move the existing fixture gate and call-count assertions to the current entry point so late-probe exercises retained ownership instead of waiting forever for an unused batch stub.

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: xialonglee <[email protected]>
@xialonglee
xialonglee deleted the fix/gap-embeddings-usage-zero-passthrough branch November 4, 2026 01:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: ollama gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants