Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions src/loop/adapter-openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,17 @@ function stripFinishReasonChunk(buf: Buffer): Buffer {
}
}

// OpenAI-wire upstreams disagree on where the cached-prompt count lives: the
// standard field is prompt_tokens_details.cached_tokens, while DeepSeek reports
// KV-cache hits as top-level prompt_cache_hit_tokens (#779). Both mean "input
// tokens served from cache", so normalize to one number.
function openaiCachedTokens(u: Record<string, unknown>): number | undefined {
const pd = u.prompt_tokens_details as Record<string, unknown> | undefined;
if (typeof pd?.cached_tokens === "number") return pd.cached_tokens;
if (typeof u.prompt_cache_hit_tokens === "number") return u.prompt_cache_hit_tokens;
return undefined;
}

export function createOpenaiAdapter(requestBody: Record<string, unknown>, clientSystem?: string, absorbName?: string): CompressLoopAdapter {
const model = (requestBody.model as string) ?? "unknown";
let responseId = `chatcmpl-proxy-${Date.now()}`;
Expand Down Expand Up @@ -327,12 +338,11 @@ export function createOpenaiAdapter(requestBody: Record<string, unknown>, client
if (!choice) {
if (parsed.usage) {
const u = parsed.usage as Record<string, unknown>;
const pd = u.prompt_tokens_details as Record<string, unknown> | undefined;
yield {
kind: "usage",
inputTokens: typeof u.prompt_tokens === "number" ? u.prompt_tokens : undefined,
outputTokens: typeof u.completion_tokens === "number" ? u.completion_tokens : undefined,
cachedTokens: typeof pd?.cached_tokens === "number" ? pd.cached_tokens : undefined,
cachedTokens: openaiCachedTokens(u),
} as ParsedStreamEvent;
// #589: include_usage clients (dsh, OpenAI SDK) read usage
// from this trailing empty-choices frame; raw tool-call rounds
Expand All @@ -352,12 +362,11 @@ export function createOpenaiAdapter(requestBody: Record<string, unknown>, client
const hadToolCalls = [...pending.values()].some((tc) => tc.name.length > 0 || tc.id.length > 0);
yield* settleToolCalls();
const u = parsed.usage as Record<string, unknown> | undefined;
const pd = u?.prompt_tokens_details as Record<string, unknown> | undefined;
yield {
kind: "usage",
inputTokens: typeof u?.prompt_tokens === "number" ? u.prompt_tokens : undefined,
outputTokens: typeof u?.completion_tokens === "number" ? u.completion_tokens : undefined,
cachedTokens: typeof pd?.cached_tokens === "number" ? pd.cached_tokens : undefined,
cachedTokens: u ? openaiCachedTokens(u) : undefined,
} as ParsedStreamEvent;
if (sawRealToolCall) {
// The raw finish chunk (provider-measured usage) reaches
Expand Down
8 changes: 6 additions & 2 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,9 @@ function usageFromSseEvent(obj: Record<string, unknown>): UsageSample | undefine
return {
inputTokens: num(usage["prompt_tokens"]),
outputTokens: num(usage["completion_tokens"]),
cachedTokens: num((usage["prompt_tokens_details"] as Record<string, unknown> | undefined)?.["cached_tokens"]),
// DeepSeek-style upstreams report KV-cache hits as top-level
// prompt_cache_hit_tokens instead of the standard details field (#779).
cachedTokens: num((usage["prompt_tokens_details"] as Record<string, unknown> | undefined)?.["cached_tokens"]) ?? num(usage["prompt_cache_hit_tokens"]),
};
}
return undefined;
Expand Down Expand Up @@ -1242,7 +1244,9 @@ export async function pipePluginJson(
cachedTokens:
num((usage["prompt_tokens_details"] as Record<string, unknown> | undefined)?.["cached_tokens"]) ??
num((usage["input_tokens_details"] as Record<string, unknown> | undefined)?.["cached_tokens"]) ??
num(usage["cache_read_input_tokens"]),
num(usage["cache_read_input_tokens"]) ??
// #779: DeepSeek-style top-level field (openai wire)
num(usage["prompt_cache_hit_tokens"]),
}, protocol);
markDirty(session);
}
Expand Down
8 changes: 6 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ export type WireProtocol = "anthropic" | "openai" | "responses";
* (`cache_read_input_tokens`) and cache-write (`cache_creation_input_tokens`)
* portions are reported as separate fields.
* - OpenAI Chat: `prompt_tokens` is the TOTAL — it ALREADY includes the
* `prompt_tokens_details.cached_tokens` subset.
* `prompt_tokens_details.cached_tokens` subset (DeepSeek-style upstreams
* carry that subset as top-level `prompt_cache_hit_tokens`; both are
* normalized here, #779).
* - Responses: `input_tokens` is the TOTAL — it ALREADY includes the
* `input_tokens_details.cached_tokens` subset.
*
Expand Down Expand Up @@ -79,7 +81,9 @@ export function usageTotals(
}
if (protocol === "openai") {
const prompt = num(usage["prompt_tokens"]);
const cached = num((usage["prompt_tokens_details"] as Record<string, unknown> | undefined)?.["cached_tokens"]);
// #779: DeepSeek-style upstreams carry the cached subset as top-level
// prompt_cache_hit_tokens instead of prompt_tokens_details.cached_tokens.
const cached = num((usage["prompt_tokens_details"] as Record<string, unknown> | undefined)?.["cached_tokens"]) ?? num(usage["prompt_cache_hit_tokens"]);
return {
total: prompt !== undefined ? promptInputTotal("openai", prompt, cached) : undefined,
cached,
Expand Down
37 changes: 37 additions & 0 deletions tests/host-usage-postfold.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,23 @@ test("#408: pipePluginChatWithStrip — split-semantics openai usage keeps lastI
});
});

test("#779: pipePluginChatWithStrip — DeepSeek top-level prompt_cache_hit_tokens counted (openai SSE)", async () => {
await withTempStore("pipe-ds-sse", async (_dir, store) => {
_setStoreForTest(store);
const session = makeSession("pipe-ds-sse");
const chunks: Buffer[] = [];
const res = makeRes(chunks);
const stream = streamOf([
`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { content: "Hi" } }] })}\n\n`,
`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", choices: [], usage: { prompt_tokens: 42, completion_tokens: 7, total_tokens: 49, prompt_cache_hit_tokens: 30 } })}\n\n`,
"data: [DONE]\n\n",
]);
await pipePluginChatWithStrip(stream, res, "openai", session);
assert.equal(session.stats.cachedTokens, 30, "DeepSeek hit tokens counted");
assert.equal(session.stats.cacheSamples, 1, "cache sample recorded");
});
});

test("#660: pipePluginResponsesWithStrip — response.completed usage forwarded verbatim", async () => {
await withTempStore("pipe-resp", async (_dir, store) => {
_setStoreForTest(store);
Expand Down Expand Up @@ -263,6 +280,26 @@ test("#660: pipePluginJson — openai JSON usage forwarded verbatim", async () =
});
});

test("#779: pipePluginJson — DeepSeek top-level prompt_cache_hit_tokens counted (openai JSON)", async () => {
await withTempStore("pipe-ds-json", async (_dir, store) => {
_setStoreForTest(store);
const session = makeSession("pipe-ds-json");
const chunks: Buffer[] = [];
const res = makeRes(chunks);
const body = JSON.stringify({
id: "c1",
object: "chat.completion",
created: 1,
model: "deepseek-chat",
choices: [{ index: 0, message: { role: "assistant", content: "Hi" }, finish_reason: "stop" }],
usage: { prompt_tokens: 42, completion_tokens: 7, total_tokens: 49, prompt_cache_hit_tokens: 30 },
});
await pipePluginJson(streamOf([body]), res, session, "openai");
assert.equal(session.stats.cachedTokens, 30, "DeepSeek hit tokens counted");
assert.equal(session.stats.cacheSamples, 1, "cache sample recorded");
});
});

test("#408: persist — negative lastInputTokens/contextTokens clamp to 0 on load and the stale file is migrated", async () => {
await withTempStore("neg-stats", async (dir, store) => {
const s = makeSession("neg1");
Expand Down
33 changes: 33 additions & 0 deletions tests/loop-adapters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,39 @@ test("openai adapter: separated usage chunk (choices:[] + usage) captured → la
assert.ok((ctx.session.stats.lastInputTokens ?? 0) > 0, "usage from choices:[] chunk captured (lastInputTokens > 0)");
});

test("openai adapter: DeepSeek prompt_cache_hit_tokens normalized into stats + completion usage (#779)", async () => {
const round1 = [
`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "gpt", choices: [{ index: 0, delta: { content: "Hi" }, finish_reason: null }] })}\n\n`,
`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "gpt", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\n`,
`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "gpt", choices: [], usage: { prompt_tokens: 42, completion_tokens: 7, prompt_cache_hit_tokens: 30 } })}\n\n`,
`data: [DONE]\n\n`,
].join("");
const ctx = makeCtx("openai-deepseek-cache");
const out = await drain(
new Response(round1, { status: 200 }).body!,
ctx,
createOpenaiAdapter({ model: "gpt" }),
{ model: "gpt", messages: [], stream: true },
);
assert.equal(ctx.session.stats.cachedTokens, 30, "top-level prompt_cache_hit_tokens counted");
assert.equal(ctx.session.stats.cacheSamples, 1, "cache sample recorded");
assert.ok(out.includes('"prompt_tokens_details":{"cached_tokens":30}'), `synthesized completion carries normalized cached_tokens: ${out}`);
});

test("openai adapter: finish-frame usage — standard field wins over prompt_cache_hit_tokens (#779)", async () => {
const adapter = createOpenaiAdapter({ model: "gpt" });
const stream = new Response([
`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "gpt", choices: [{ index: 0, delta: { content: "Hi" }, finish_reason: null }] })}\n\n`,
`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "gpt", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 42, completion_tokens: 7, prompt_tokens_details: { cached_tokens: 25 }, prompt_cache_hit_tokens: 30 } })}\n\n`,
`data: [DONE]\n\n`,
].join("")).body!;
let cached: number | undefined;
for await (const ev of adapter.parseStream(stream, 1)) {
if (ev.kind === "usage") cached = ev.cachedTokens;
}
assert.equal(cached, 25, "standard field wins when both present");
});

test("openai adapter: acp_status-only round → marker + re-request, no crash", async () => {
const round1 = [
`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", created: 1, model: "gpt", choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] })}\n\n`,
Expand Down
21 changes: 21 additions & 0 deletions tests/usage-totals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,24 @@ test("usageTotals: empty usage → undefined total", () => {
assert.equal(usageTotals("openai", {}).total, undefined);
assert.equal(usageTotals("anthropic", {}).total, undefined);
});

// #779: DeepSeek reports KV-cache hits as top-level prompt_cache_hit_tokens
// instead of prompt_tokens_details.cached_tokens — normalize both.
test("usageTotals: OpenAI — top-level prompt_cache_hit_tokens normalized (#779)", () => {
const { total, cached } = usageTotals("openai", {
prompt_tokens: 1000,
prompt_cache_hit_tokens: 850,
});
assert.equal(cached, 850);
assert.equal(total, 1000); // prompt already includes hit+miss — no double count
});

test("usageTotals: OpenAI — standard field wins when both are present (#779)", () => {
const { total, cached } = usageTotals("openai", {
prompt_tokens: 1000,
prompt_tokens_details: { cached_tokens: 900 },
prompt_cache_hit_tokens: 850,
});
assert.equal(cached, 900);
assert.equal(total, 1000);
});
Loading