feat: return usage for openai providers

This commit is contained in:
Ting-Wai To 2025-08-28 11:46:05 -07:00
parent ca5aadda73
commit bad857a71e
3 changed files with 112 additions and 11 deletions

View file

@ -22,6 +22,7 @@ import {
chatChunkFromDelta,
customFetch,
embedding,
usageChatChunk,
} from "../util.js";
import {
convertOpenAIToolToGeminiFunction,
@ -37,6 +38,8 @@ import {
RerankCreateParams,
} from "./base.js";
type UsageInfo = { total_tokens: number; completion_tokens: number; prompt_tokens: number };
export class GeminiApi implements BaseLlmApi {
apiBase: string = "https://generativelanguage.googleapis.com/v1beta/";
@ -240,6 +243,7 @@ export class GeminiApi implements BaseLlmApi {
signal: AbortSignal,
): Promise<ChatCompletion> {
let completion = "";
let usage: UsageInfo | undefined = undefined;
for await (const chunk of this.chatCompletionStream(
{
...body,
@ -247,7 +251,12 @@ export class GeminiApi implements BaseLlmApi {
},
signal,
)) {
completion += chunk.choices[0].delta.content;
if (chunk.choices.length > 0) {
completion += chunk.choices[0].delta.content || "";
}
if (chunk.usage) {
usage = chunk.usage;
}
}
return {
id: "",
@ -266,12 +275,13 @@ export class GeminiApi implements BaseLlmApi {
},
},
],
usage: undefined,
usage,
};
}
async *handleStreamResponse(response: any, model: string) {
let buffer = "";
let usage: UsageInfo | undefined = undefined;
for await (const chunk of streamResponse(response as any)) {
buffer += chunk;
if (buffer.startsWith("[")) {
@ -300,6 +310,15 @@ export class GeminiApi implements BaseLlmApi {
throw new Error(data.error.message);
}
// Check for usage metadata
if (data.usageMetadata) {
usage = {
prompt_tokens: data.usageMetadata.promptTokenCount || 0,
completion_tokens: data.usageMetadata.candidatesTokenCount || 0,
total_tokens: data.usageMetadata.totalTokenCount || 0,
};
}
// In case of max tokens reached, gemini will sometimes return content with no parts, even though that doesn't match the API spec
const contentParts = data?.candidates?.[0]?.content?.parts;
if (contentParts) {
@ -338,6 +357,14 @@ export class GeminiApi implements BaseLlmApi {
buffer = "";
}
}
// Emit usage at the end if we have it
if (usage) {
yield usageChatChunk({
model,
usage,
});
}
}
async *chatCompletionStream(

View file

@ -16,7 +16,12 @@ import {
import { Model } from "openai/resources/models.mjs";
import { z } from "zod";
import { OpenAIConfigSchema } from "../types.js";
import { chatChunk, chatCompletion, customFetch } from "../util.js";
import {
chatChunk,
chatCompletion,
customFetch,
usageChatChunk,
} from "../util.js";
import {
BaseLlmApi,
CreateRerankResponse,
@ -24,6 +29,8 @@ import {
RerankCreateParams,
} from "./base.js";
type UsageInfo = { total_tokens: number; completion_tokens: number; prompt_tokens: number };
// Relace only supports apply through a /v1/apply endpoint
export class RelaceApi implements BaseLlmApi {
private apiBase = "https://instantapply.endpoint.relace.run/v1/";
@ -41,6 +48,7 @@ export class RelaceApi implements BaseLlmApi {
signal: AbortSignal,
): Promise<ChatCompletion> {
let content = "";
let usage: UsageInfo | undefined = undefined;
// Convert the non-streaming params to streaming params
const streamingBody: ChatCompletionCreateParamsStreaming = {
@ -52,12 +60,18 @@ export class RelaceApi implements BaseLlmApi {
streamingBody,
signal,
)) {
content += chunk.choices[0]?.delta?.content || "";
if (chunk.choices.length > 0) {
content += chunk.choices[0]?.delta?.content || "";
}
if (chunk.usage) {
usage = chunk.usage;
}
}
return chatCompletion({
content,
model: body.model,
usage,
});
}
@ -115,6 +129,15 @@ export class RelaceApi implements BaseLlmApi {
content: mergedCode,
model: body.model,
});
yield usageChatChunk({
model: body.model,
usage: {
prompt_tokens: result.usage.prompt_tokens || 0,
completion_tokens: result.usage.completion_tokens || 0,
total_tokens: result.usage.total_tokens,
},
});
}
completionNonStream(

View file

@ -51,6 +51,20 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
model: "gpt-4o",
apiKey: process.env.OPENAI_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "openai",
model: "gpt-4o-mini",
apiKey: process.env.OPENAI_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "anthropic",
@ -67,14 +81,31 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
model: "gemini-1.5-flash-latest",
apiKey: process.env.GEMINI_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "gemini",
model: "gemini-2.5-flash",
apiKey: process.env.GEMINI_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "mistral",
model: "codestral",
apiKey: process.env.MISTRAL_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
// {
// provider: "mistral",
// model: "codestral-latest",
// apiKey: process.env.MISTRAL_API_KEY!,
// apiBase: "https://api.mistral.ai/v1",
// roles: ["autocomplete"],
// },
// {
// provider: "deepseek",
// model: "deepseek-coder",
@ -111,6 +142,26 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
apiKey: process.env.VOYAGE_API_KEY!,
roles: ["rerank"],
},
{
provider: "relace",
model: "instant-apply",
apiKey: process.env.RELACE_API_KEY!,
roles: ["chat"],
options: {
skipTools: true,
expectUsage: true,
},
},
{
provider: "inception",
model: "mercury-coder",
apiKey: process.env.INCEPTION_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
// {
// provider: "cohere",
// model: "rerank-v3.5",