Elffuss BraidHub

kikocis/continue public

Merge pull request #7462 from continuedev/tingwai/con-3668

feat: return usage for openai providers
Changeset825624809c0913161adf5de1d6cb4e2bf583bc97b8bf3a48552a91a65ed8eeeb
AuthorTing-Wai <40179554+tingwai@users.noreply.github.com> · 2025-09-05 10:13 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-05 10:13 -07:00
Parents5e7595cfd516, b350229dfa06

Browse the files at this changeset

6 files changed

modified packages/openai-adapters/src/apis/Gemini.ts +33 −2
@@ -10,6 +10,7 @@
1010 Completion,
1111 CompletionCreateParamsNonStreaming,
1212 CompletionCreateParamsStreaming,
13+ CompletionUsage,
1314 CreateEmbeddingResponse,
1415 EmbeddingCreateParams,
1516 Model,
@@ -22,6 +23,7 @@
2223 chatChunkFromDelta,
2324 customFetch,
2425 embedding,
26+ usageChatChunk,
2527 } from "../util.js";
2628 import {
2729 convertOpenAIToolToGeminiFunction,
@@ -37,6 +39,11 @@
3739 RerankCreateParams,
3840 } from "./base.js";
3941
42+type UsageInfo = Pick<
43+ CompletionUsage,
44+ "total_tokens" | "completion_tokens" | "prompt_tokens"
45+>;
46+
4047 export class GeminiApi implements BaseLlmApi {
4148 apiBase: string = "https://generativelanguage.googleapis.com/v1beta/";
4249
@@ -240,6 +247,7 @@
240247 signal: AbortSignal,
241248 ): Promise<ChatCompletion> {
242249 let completion = "";
250+ let usage: UsageInfo | undefined = undefined;
243251 for await (const chunk of this.chatCompletionStream(
244252 {
245253 ...body,
@@ -247,7 +255,12 @@
247255 },
248256 signal,
249257 )) {
250- completion += chunk.choices[0].delta.content;
258+ if (chunk.choices.length > 0) {
259+ completion += chunk.choices[0].delta.content || "";
260+ }
261+ if (chunk.usage) {
262+ usage = chunk.usage;
263+ }
251264 }
252265 return {
253266 id: "",
@@ -266,12 +279,13 @@
266279 },
267280 },
268281 ],
269- usage: undefined,
282+ usage,
270283 };
271284 }
272285
273286 async *handleStreamResponse(response: any, model: string) {
274287 let buffer = "";
288+ let usage: UsageInfo | undefined = undefined;
275289 for await (const chunk of streamResponse(response as any)) {
276290 buffer += chunk;
277291 if (buffer.startsWith("[")) {
@@ -300,6 +314,15 @@
300314 throw new Error(data.error.message);
301315 }
302316
317+ // Check for usage metadata
318+ if (data.usageMetadata) {
319+ usage = {
320+ prompt_tokens: data.usageMetadata.promptTokenCount || 0,
321+ completion_tokens: data.usageMetadata.candidatesTokenCount || 0,
322+ total_tokens: data.usageMetadata.totalTokenCount || 0,
323+ };
324+ }
325+
303326 // In case of max tokens reached, gemini will sometimes return content with no parts, even though that doesn't match the API spec
304327 const contentParts = data?.candidates?.[0]?.content?.parts;
305328 if (contentParts) {
@@ -338,6 +361,14 @@
338361 buffer = "";
339362 }
340363 }
364+
365+ // Emit usage at the end if we have it
366+ if (usage) {
367+ yield usageChatChunk({
368+ model,
369+ usage,
370+ });
371+ }
341372 }
342373
343374 async *chatCompletionStream(
modified packages/openai-adapters/src/apis/OpenAI.ts +5 −0
@@ -35,6 +35,11 @@
3535 });
3636 }
3737 modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T {
38+ // Add stream_options to include usage in streaming responses
39+ if (body.stream) {
40+ (body as any).stream_options = { include_usage: true };
41+ }
42+
3843 // o-series models - only apply for official OpenAI API
3944 const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/";
4045 if (isOfficialOpenAIAPI) {
modified packages/openai-adapters/src/apis/Relace.ts +29 −2
@@ -2,6 +2,7 @@
22 Completion,
33 CompletionCreateParamsNonStreaming,
44 CompletionCreateParamsStreaming,
5+ CompletionUsage,
56 } from "openai/resources/completions.mjs";
67 import {
78 CreateEmbeddingResponse,
@@ -16,7 +17,12 @@
1617 import { Model } from "openai/resources/models.mjs";
1718 import { z } from "zod";
1819 import { OpenAIConfigSchema } from "../types.js";
19-import { chatChunk, chatCompletion, customFetch } from "../util.js";
20+import {
21+ chatChunk,
22+ chatCompletion,
23+ customFetch,
24+ usageChatChunk,
25+} from "../util.js";
2026 import {
2127 BaseLlmApi,
2228 CreateRerankResponse,
@@ -24,6 +30,11 @@
2430 RerankCreateParams,
2531 } from "./base.js";
2632
33+type UsageInfo = Pick<
34+ CompletionUsage,
35+ "total_tokens" | "completion_tokens" | "prompt_tokens"
36+>;
37+
2738 // Relace only supports apply through a /v1/apply endpoint
2839 export class RelaceApi implements BaseLlmApi {
2940 private apiBase = "https://instantapply.endpoint.relace.run/v1/";
@@ -41,6 +52,7 @@
4152 signal: AbortSignal,
4253 ): Promise<ChatCompletion> {
4354 let content = "";
55+ let usage: UsageInfo | undefined = undefined;
4456
4557 // Convert the non-streaming params to streaming params
4658 const streamingBody: ChatCompletionCreateParamsStreaming = {
@@ -52,12 +64,18 @@
5264 streamingBody,
5365 signal,
5466 )) {
55- content += chunk.choices[0]?.delta?.content || "";
67+ if (chunk.choices.length > 0) {
68+ content += chunk.choices[0]?.delta?.content || "";
69+ }
70+ if (chunk.usage) {
71+ usage = chunk.usage;
72+ }
5673 }
5774
5875 return chatCompletion({
5976 content,
6077 model: body.model,
78+ usage,
6179 });
6280 }
6381
@@ -115,6 +133,15 @@
115133 content: mergedCode,
116134 model: body.model,
117135 });
136+
137+ yield usageChatChunk({
138+ model: body.model,
139+ usage: {
140+ prompt_tokens: result.usage.prompt_tokens || 0,
141+ completion_tokens: result.usage.completion_tokens || 0,
142+ total_tokens: result.usage.total_tokens,
143+ },
144+ });
118145 }
119146
120147 completionNonStream(
modified packages/openai-adapters/src/test/adapter-test-utils.ts +1 −0
@@ -258,6 +258,7 @@
258258 model: "gpt-4",
259259 messages: [{ role: "user", content: "hello" }],
260260 stream: true,
261+ stream_options: { include_usage: true },
261262 ...testConfig.customBodyOptions,
262263 },
263264 },
modified packages/openai-adapters/src/test/main.test.ts +58 −7
@@ -51,6 +51,20 @@
5151 model: "gpt-4o",
5252 apiKey: process.env.OPENAI_API_KEY!,
5353 roles: ["chat"],
54+ options: {
55+ skipTools: false,
56+ expectUsage: true,
57+ },
58+ },
59+ {
60+ provider: "openai",
61+ model: "gpt-4o-mini",
62+ apiKey: process.env.OPENAI_API_KEY!,
63+ roles: ["chat"],
64+ options: {
65+ skipTools: false,
66+ expectUsage: true,
67+ },
5468 },
5569 {
5670 provider: "anthropic",
@@ -67,15 +81,32 @@
6781 model: "gemini-1.5-flash-latest",
6882 apiKey: process.env.GEMINI_API_KEY!,
6983 roles: ["chat"],
84+ options: {
85+ skipTools: false,
86+ expectUsage: true,
87+ },
88+ },
89+ {
90+ provider: "gemini",
91+ model: "gemini-2.5-flash",
92+ apiKey: process.env.GEMINI_API_KEY!,
93+ roles: ["chat"],
94+ options: {
95+ skipTools: false,
96+ expectUsage: true,
97+ },
98+ },
99+ {
100+ provider: "mistral",
101+ model: "codestral",
102+ apiKey: process.env.MISTRAL_API_KEY!,
103+ roles: ["chat"],
104+ options: {
105+ skipTools: false,
106+ expectUsage: true,
107+ },
70108 },
71109 // {
72- // provider: "mistral",
73- // model: "codestral-latest",
74- // apiKey: process.env.MISTRAL_API_KEY!,
75- // apiBase: "https://api.mistral.ai/v1",
76- // roles: ["autocomplete"],
77- // },
78- // {
79110 // provider: "deepseek",
80111 // model: "deepseek-coder",
81112 // apiKey: process.env.DEEPSEEK_API_KEY!,
@@ -111,6 +142,26 @@
111142 apiKey: process.env.VOYAGE_API_KEY!,
112143 roles: ["rerank"],
113144 },
145+ {
146+ provider: "relace",
147+ model: "instant-apply",
148+ apiKey: process.env.RELACE_API_KEY!,
149+ roles: ["chat"],
150+ options: {
151+ skipTools: true,
152+ expectUsage: true,
153+ },
154+ },
155+ {
156+ provider: "inception",
157+ model: "mercury-coder",
158+ apiKey: process.env.INCEPTION_API_KEY!,
159+ roles: ["chat"],
160+ options: {
161+ skipTools: false,
162+ expectUsage: true,
163+ },
164+ },
114165 // {
115166 // provider: "cohere",
116167 // model: "rerank-v3.5",
modified packages/openai-adapters/src/test/util.ts +11 −3
@@ -106,9 +106,17 @@
106106 expect(usage).toBeDefined();
107107 expect(usage!.completion_tokens).toBeGreaterThan(0);
108108 expect(usage!.prompt_tokens).toBeGreaterThan(0);
109- expect(usage!.total_tokens).toEqual(
110- usage!.prompt_tokens + usage!.completion_tokens,
111- );
109+ // Gemini 2.5 models have thinking tokens, so total_tokens >= prompt + completion
110+ // Other models should have total_tokens = prompt + completion
111+ if (model.includes("gemini-2.5") || model.includes("gemini-2.0")) {
112+ expect(usage!.total_tokens).toBeGreaterThanOrEqual(
113+ usage!.prompt_tokens + usage!.completion_tokens,
114+ );
115+ } else {
116+ expect(usage!.total_tokens).toEqual(
117+ usage!.prompt_tokens + usage!.completion_tokens,
118+ );
119+ }
112120 }
113121 });
114122