Skip to content

Commit 0ddf51c

Browse files
committed
fix(agents): preserve OpenAI reasoning token usage
1 parent 1a86255 commit 0ddf51c

10 files changed

Lines changed: 126 additions & 7 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ Docs: https://docs.openclaw.ai
3131
- CLI/agents: retry transient normal-close Gateway handshakes before falling back to embedded `openclaw agent` execution.
3232
- CLI/update: keep managed Gateway service stop/restart status lines out of `openclaw update --json` stdout so package-update automation can parse the JSON payload.
3333
- Plugins: resolve OpenClaw plugin SDK subpaths for native external plugin runtimes without mutating package installs or broadening process-wide module resolution.
34+
- Agents/OpenAI: preserve Responses and Chat Completions `reasoning_tokens` usage metadata without double-counting it in aggregate output tokens. (#85319)
3435
- Providers/Gemini: strip fractional seconds from web-search time range filters so Gemini accepts freshness-bound search requests. (#85071) Thanks @Noerr.
3536
- OpenAI Codex: preserve image input support for sparse `openai-codex/gpt-5.5` catalog rows. (#85095) Thanks @sercada.
3637
- Plugins/discovery: strip `-plugin` package suffixes when deriving plugin id hints so package names line up with manifest ids. (#85170) Thanks @JulyanXu.

‎src/agents/openai-transport-stream.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,7 @@ describe("openai transport stream", () => {
364364
output_tokens: 5,
365365
total_tokens: 7,
366366
input_tokens_details: { cached_tokens: 4 },
367+
output_tokens_details: { reasoning_tokens: 3 },
367368
},
368369
},
369370
},
@@ -377,6 +378,7 @@ describe("openai transport stream", () => {
377378
input: 0,
378379
output: 5,
379380
cacheRead: 4,
381+
reasoningTokens: 3,
380382
totalTokens: 9,
381383
});
382384
});
@@ -1119,7 +1121,7 @@ describe("openai transport stream", () => {
11191121
}
11201122
});
11211123

1122-
it("does not double-count reasoning tokens and clamps uncached prompt usage at zero", () => {
1124+
it("preserves reasoning tokens without double-counting them", () => {
11231125
const model = {
11241126
id: "gpt-5",
11251127
name: "GPT-5",
@@ -1148,9 +1150,25 @@ describe("openai transport stream", () => {
11481150
input: 7,
11491151
output: 20,
11501152
cacheRead: 3,
1153+
reasoningTokens: 7,
11511154
totalTokens: 30,
11521155
},
11531156
);
1157+
});
1158+
1159+
it("clamps uncached prompt usage at zero", () => {
1160+
const model = {
1161+
id: "gpt-5",
1162+
name: "GPT-5",
1163+
api: "openai-completions",
1164+
provider: "openai",
1165+
baseUrl: "https://api.openai.com/v1",
1166+
reasoning: true,
1167+
input: ["text"],
1168+
cost: { input: 1, output: 2, cacheRead: 0.5, cacheWrite: 0 },
1169+
contextWindow: 200000,
1170+
maxTokens: 8192,
1171+
} satisfies Model<"openai-completions">;
11541172

11551173
expectRecordFields(
11561174
parseTransportChunkUsage(

‎src/agents/openai-transport-stream.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ type MutableAssistantOutput = {
204204
output: number;
205205
cacheRead: number;
206206
cacheWrite: number;
207+
reasoningTokens?: number;
207208
totalTokens: number;
208209
cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
209210
};
@@ -1530,6 +1531,7 @@ async function processResponsesStream(
15301531
output_tokens?: number;
15311532
total_tokens?: number;
15321533
input_tokens_details?: { cached_tokens?: number };
1534+
output_tokens_details?: { reasoning_tokens?: number };
15331535
service_tier?: ResponseCreateParamsStreaming["service_tier"];
15341536
status?: string;
15351537
}
@@ -1538,12 +1540,16 @@ async function processResponsesStream(
15381540
const cachedTokens = usage.input_tokens_details?.cached_tokens || 0;
15391541
const inputTokens = usage.input_tokens || 0;
15401542
const outputTokens = usage.output_tokens || 0;
1543+
const reasoningTokens = usage.output_tokens_details?.reasoning_tokens;
15411544
const input = Math.max(0, inputTokens - cachedTokens);
15421545
output.usage = {
15431546
input,
15441547
output: outputTokens,
15451548
cacheRead: cachedTokens,
15461549
cacheWrite: 0,
1550+
...(typeof reasoningTokens === "number" && Number.isFinite(reasoningTokens)
1551+
? { reasoningTokens }
1552+
: {}),
15471553
totalTokens: input + outputTokens + cachedTokens,
15481554
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
15491555
};
@@ -3436,11 +3442,15 @@ export function parseTransportChunkUsage(
34363442
const promptTokens = rawUsage.prompt_tokens || 0;
34373443
const input = Math.max(0, promptTokens - cachedTokens);
34383444
const outputTokens = rawUsage.completion_tokens || 0;
3445+
const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens;
34393446
const usage = {
34403447
input,
34413448
output: outputTokens,
34423449
cacheRead: cachedTokens,
34433450
cacheWrite: 0,
3451+
...(typeof reasoningTokens === "number" && Number.isFinite(reasoningTokens)
3452+
? { reasoningTokens }
3453+
: {}),
34443454
totalTokens: input + outputTokens + cachedTokens,
34453455
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
34463456
};

‎src/agents/pi-embedded-runner/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ export type EmbeddedPiAgentMeta = {
3535
output?: number;
3636
cacheRead?: number;
3737
cacheWrite?: number;
38+
reasoningTokens?: number;
3839
total?: number;
3940
};
4041
/**
@@ -49,6 +50,7 @@ export type EmbeddedPiAgentMeta = {
4950
output?: number;
5051
cacheRead?: number;
5152
cacheWrite?: number;
53+
reasoningTokens?: number;
5254
total?: number;
5355
};
5456
};

‎src/agents/pi-embedded-runner/usage-accumulator.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ type UsageInput = NonNullable<Parameters<typeof mergeUsageIntoAccumulator>[1]>;
1212
const FIRST_USAGE: UsageInput = {
1313
input: 100,
1414
output: 50,
15+
reasoningTokens: 12,
1516
cacheRead: 80_000,
1617
cacheWrite: 5_000,
1718
total: 85_150,
@@ -28,6 +29,7 @@ const SECOND_USAGE: UsageInput = {
2829
const FINAL_USAGE: UsageInput = {
2930
input: 150,
3031
output: 40,
32+
reasoningTokens: 7,
3133
cacheRead: 84_000,
3234
cacheWrite: 0,
3335
total: 84_190,
@@ -53,6 +55,7 @@ describe("usage-accumulator", () => {
5355

5456
expect(acc.input).toBe(370);
5557
expect(acc.output).toBe(120);
58+
expect(acc.reasoningTokens).toBe(19);
5659
expect(acc.cacheRead).toBe(246_000);
5760
expect(acc.cacheWrite).toBe(5_000);
5861
expect(acc.total).toBe(251_490);
@@ -63,6 +66,7 @@ describe("usage-accumulator", () => {
6366

6467
expect(acc.lastInput).toBe(150);
6568
expect(acc.lastOutput).toBe(40);
69+
expect(acc.lastReasoningTokens).toBe(7);
6670
expect(acc.lastCacheRead).toBe(84_000);
6771
expect(acc.lastCacheWrite).toBe(0);
6872
expect(acc.lastTotal).toBe(84_190);
@@ -100,6 +104,7 @@ describe("usage-accumulator", () => {
100104
mergeUsageIntoAccumulator(acc, {
101105
input: 100,
102106
output: 50,
107+
reasoningTokens: 4,
103108
cacheRead: 80_000,
104109
cacheWrite: 5_000,
105110
});
@@ -119,6 +124,7 @@ describe("usage-accumulator", () => {
119124
expect(toNormalizedUsage(acc)).toEqual({
120125
input: 370,
121126
output: 120,
127+
reasoningTokens: 4,
122128
cacheRead: 246_000,
123129
cacheWrite: 5_000,
124130
total: 251_490,
@@ -146,6 +152,7 @@ describe("usage-accumulator", () => {
146152
expect(toLastCallUsage(acc)).toEqual({
147153
input: 150,
148154
output: 40,
155+
reasoningTokens: 7,
149156
cacheRead: 84_000,
150157
cacheWrite: undefined,
151158
total: 84_190,
@@ -169,6 +176,7 @@ describe("usage-accumulator", () => {
169176
{
170177
inputTokens: 99,
171178
outputTokens: 12,
179+
completion_tokens_details: { reasoning_tokens: 8 },
172180
cache_read_input_tokens: 456,
173181
cache_creation_input_tokens: 3,
174182
totalTokens: 570,
@@ -178,6 +186,7 @@ describe("usage-accumulator", () => {
178186
).toEqual({
179187
input: 99,
180188
output: 12,
189+
reasoningTokens: 8,
181190
cacheRead: 456,
182191
cacheWrite: 3,
183192
total: 570,
@@ -190,6 +199,7 @@ describe("usage-accumulator", () => {
190199
expect(resolveLastCallUsage(undefined, acc)).toEqual({
191200
input: 150,
192201
output: 40,
202+
reasoningTokens: 7,
193203
cacheRead: 84_000,
194204
cacheWrite: undefined,
195205
total: 84_190,
@@ -202,6 +212,7 @@ describe("usage-accumulator", () => {
202212
expect(resolveLastCallUsage({ responseId: "abc" } as never, acc)).toEqual({
203213
input: 150,
204214
output: 40,
215+
reasoningTokens: 7,
205216
cacheRead: 84_000,
206217
cacheWrite: undefined,
207218
total: 84_190,

‎src/agents/pi-embedded-runner/usage-accumulator.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@ export type UsageAccumulator = {
55
output: number;
66
cacheRead: number;
77
cacheWrite: number;
8+
reasoningTokens: number;
89
total: number;
910
/** Exact usage snapshot from the most recent API call. */
1011
lastInput: number;
1112
lastOutput: number;
1213
lastCacheRead: number;
1314
lastCacheWrite: number;
15+
lastReasoningTokens: number;
1416
lastTotal: number;
1517
};
1618

@@ -19,21 +21,28 @@ export const createUsageAccumulator = (): UsageAccumulator => ({
1921
output: 0,
2022
cacheRead: 0,
2123
cacheWrite: 0,
24+
reasoningTokens: 0,
2225
total: 0,
2326
lastInput: 0,
2427
lastOutput: 0,
2528
lastCacheRead: 0,
2629
lastCacheWrite: 0,
30+
lastReasoningTokens: 0,
2731
lastTotal: 0,
2832
});
2933

3034
type MaybeUsage = NormalizedUsage | undefined;
3135

3236
const hasUsageValues = (usage: MaybeUsage): usage is NormalizedUsage =>
3337
!!usage &&
34-
[usage.input, usage.output, usage.cacheRead, usage.cacheWrite, usage.total].some(
35-
(value) => typeof value === "number" && Number.isFinite(value) && value > 0,
36-
);
38+
[
39+
usage.input,
40+
usage.output,
41+
usage.cacheRead,
42+
usage.cacheWrite,
43+
usage.reasoningTokens,
44+
usage.total,
45+
].some((value) => typeof value === "number" && Number.isFinite(value) && value > 0);
3746

3847
export const mergeUsageIntoAccumulator = (target: UsageAccumulator, usage: MaybeUsage) => {
3948
if (!hasUsageValues(usage)) {
@@ -46,11 +55,13 @@ export const mergeUsageIntoAccumulator = (target: UsageAccumulator, usage: Maybe
4655
target.output += usage.output ?? 0;
4756
target.cacheRead += usage.cacheRead ?? 0;
4857
target.cacheWrite += usage.cacheWrite ?? 0;
58+
target.reasoningTokens += usage.reasoningTokens ?? 0;
4959
target.total += callTotal;
5060
target.lastInput = usage.input ?? 0;
5161
target.lastOutput = usage.output ?? 0;
5262
target.lastCacheRead = usage.cacheRead ?? 0;
5363
target.lastCacheWrite = usage.cacheWrite ?? 0;
64+
target.lastReasoningTokens = usage.reasoningTokens ?? 0;
5465
target.lastTotal = callTotal;
5566
};
5667

@@ -60,6 +71,7 @@ export const toNormalizedUsage = (usage: UsageAccumulator): NormalizedUsage | un
6071
usage.output > 0 ||
6172
usage.cacheRead > 0 ||
6273
usage.cacheWrite > 0 ||
74+
usage.reasoningTokens > 0 ||
6375
usage.total > 0;
6476
if (!hasUsage) {
6577
return undefined;
@@ -69,6 +81,7 @@ export const toNormalizedUsage = (usage: UsageAccumulator): NormalizedUsage | un
6981
output: usage.output || undefined,
7082
cacheRead: usage.cacheRead || undefined,
7183
cacheWrite: usage.cacheWrite || undefined,
84+
...(usage.reasoningTokens > 0 ? { reasoningTokens: usage.reasoningTokens } : {}),
7285
total: usage.total || undefined,
7386
};
7487
};
@@ -79,6 +92,7 @@ export const toLastCallUsage = (usage: UsageAccumulator): NormalizedUsage | unde
7992
usage.lastOutput > 0 ||
8093
usage.lastCacheRead > 0 ||
8194
usage.lastCacheWrite > 0 ||
95+
usage.lastReasoningTokens > 0 ||
8296
usage.lastTotal > 0;
8397
if (!hasUsage) {
8498
return undefined;
@@ -88,6 +102,7 @@ export const toLastCallUsage = (usage: UsageAccumulator): NormalizedUsage | unde
88102
output: usage.lastOutput || undefined,
89103
cacheRead: usage.lastCacheRead || undefined,
90104
cacheWrite: usage.lastCacheWrite || undefined,
105+
...(usage.lastReasoningTokens > 0 ? { reasoningTokens: usage.lastReasoningTokens } : {}),
91106
total: usage.lastTotal || undefined,
92107
};
93108
};

‎src/agents/pi-embedded-subscribe.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@ export function subscribeEmbeddedPiSession(params: SubscribeEmbeddedPiSessionPar
201201
output: 0,
202202
cacheRead: 0,
203203
cacheWrite: 0,
204+
reasoningTokens: 0,
204205
total: 0,
205206
};
206207
let compactionCount = 0;
@@ -470,6 +471,7 @@ export function subscribeEmbeddedPiSession(params: SubscribeEmbeddedPiSessionPar
470471
usageTotals.output += usage.output ?? 0;
471472
usageTotals.cacheRead += usage.cacheRead ?? 0;
472473
usageTotals.cacheWrite += usage.cacheWrite ?? 0;
474+
usageTotals.reasoningTokens += usage.reasoningTokens ?? 0;
473475
const usageTotal =
474476
usage.total ??
475477
(usage.input ?? 0) + (usage.output ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
@@ -492,6 +494,7 @@ export function subscribeEmbeddedPiSession(params: SubscribeEmbeddedPiSessionPar
492494
usageTotals.output > 0 ||
493495
usageTotals.cacheRead > 0 ||
494496
usageTotals.cacheWrite > 0 ||
497+
usageTotals.reasoningTokens > 0 ||
495498
usageTotals.total > 0;
496499
if (!hasUsage) {
497500
return undefined;
@@ -503,6 +506,7 @@ export function subscribeEmbeddedPiSession(params: SubscribeEmbeddedPiSessionPar
503506
output: usageTotals.output || undefined,
504507
cacheRead: usageTotals.cacheRead || undefined,
505508
cacheWrite: usageTotals.cacheWrite || undefined,
509+
...(usageTotals.reasoningTokens > 0 ? { reasoningTokens: usageTotals.reasoningTokens } : {}),
506510
total: usageTotals.total || derivedTotal || undefined,
507511
};
508512
};

‎src/agents/usage.normalization.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ describe("normalizeUsage", () => {
9090
expect(hasNonzeroUsage(null)).toBe(false);
9191
expect(hasNonzeroUsage({})).toBe(false);
9292
expect(hasNonzeroUsage({ input: 0, output: 0 })).toBe(false);
93+
expect(hasNonzeroUsage({ reasoningTokens: 1 })).toBe(true);
9394
expect(hasNonzeroUsage({ input: 1 })).toBe(true);
9495
expect(hasNonzeroUsage({ total: 1 })).toBe(true);
9596
});

0 commit comments

Comments
 (0)