Fix review issues and Gemini compatibility
- Fix review issue #1: API timing in tests - Move API creation into beforeAll hook - Fix review issue #2: Undefined parameters - Add default empty schema for tools - Fix review issue #3: Timestamp format - Use seconds instead of milliseconds - Fix review issue #4: Stop sequences - Handle both string and array types - Fix Gemini compatibility: Convert to dynamic imports to prevent Vercel AI SDK from interfering with @google/genai All Vercel AI SDK imports are now lazy-loaded only when feature flags are enabled, preventing the 'getReader is not a function' error in Gemini tests.
This commit is contained in:
parent
536bc769ea
commit
d5f670fae4
4 changed files with 113 additions and 61 deletions
|
|
@ -51,15 +51,10 @@ import {
|
|||
FimCreateParamsStreaming,
|
||||
RerankCreateParams,
|
||||
} from "./base.js";
|
||||
import { createAnthropic } from "@ai-sdk/anthropic";
|
||||
import { streamText, generateText } from "ai";
|
||||
import { convertVercelStream } from "../vercelStreamConverter.js";
|
||||
import { convertOpenAIMessagesToVercel } from "../openaiToVercelMessages.js";
|
||||
import { convertToolsToVercelFormat } from "../convertToolsToVercel.js";
|
||||
|
||||
export class AnthropicApi implements BaseLlmApi {
|
||||
apiBase: string = "https://api.anthropic.com/v1/";
|
||||
private anthropicProvider?: ReturnType<typeof createAnthropic>;
|
||||
private anthropicProvider?: any;
|
||||
private useVercelSDK: boolean;
|
||||
|
||||
constructor(
|
||||
|
|
@ -73,28 +68,31 @@ export class AnthropicApi implements BaseLlmApi {
|
|||
}
|
||||
|
||||
this.useVercelSDK = process.env.USE_VERCEL_AI_SDK_ANTHROPIC === "true";
|
||||
}
|
||||
|
||||
private async initializeVercelProvider() {
|
||||
if (!this.anthropicProvider && this.useVercelSDK) {
|
||||
const { createAnthropic } = await import("@ai-sdk/anthropic");
|
||||
|
||||
if (this.useVercelSDK) {
|
||||
// New Vercel AI SDK implementation
|
||||
// Only use customFetch if we have request options that need it
|
||||
// Otherwise use native fetch (Vercel AI SDK requires Web Streams API)
|
||||
const hasRequestOptions =
|
||||
config.requestOptions &&
|
||||
(config.requestOptions.headers ||
|
||||
config.requestOptions.proxy ||
|
||||
config.requestOptions.caBundlePath ||
|
||||
config.requestOptions.clientCertificate ||
|
||||
config.requestOptions.extraBodyProperties);
|
||||
this.config.requestOptions &&
|
||||
(this.config.requestOptions.headers ||
|
||||
this.config.requestOptions.proxy ||
|
||||
this.config.requestOptions.caBundlePath ||
|
||||
this.config.requestOptions.clientCertificate ||
|
||||
this.config.requestOptions.extraBodyProperties);
|
||||
|
||||
this.anthropicProvider = createAnthropic({
|
||||
apiKey: config.apiKey ?? "",
|
||||
apiKey: this.config.apiKey ?? "",
|
||||
baseURL:
|
||||
this.apiBase !== "https://api.anthropic.com/v1/" &&
|
||||
this.apiBase !== "https://api.anthropic.com/v1"
|
||||
? this.apiBase.replace(/\/$/, "")
|
||||
: undefined,
|
||||
fetch: hasRequestOptions
|
||||
? customFetch(config.requestOptions)
|
||||
? customFetch(this.config.requestOptions)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
|
@ -366,7 +364,7 @@ export class AnthropicApi implements BaseLlmApi {
|
|||
id: completion.id,
|
||||
object: "chat.completion",
|
||||
model: body.model,
|
||||
created: Date.now(),
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
usage: {
|
||||
total_tokens: (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0),
|
||||
completion_tokens: usage?.output_tokens ?? 0,
|
||||
|
|
@ -396,10 +394,20 @@ export class AnthropicApi implements BaseLlmApi {
|
|||
body: ChatCompletionCreateParamsNonStreaming,
|
||||
signal: AbortSignal,
|
||||
): Promise<ChatCompletion> {
|
||||
await this.initializeVercelProvider();
|
||||
|
||||
if (!this.anthropicProvider) {
|
||||
throw new Error("Vercel AI SDK Anthropic provider not initialized");
|
||||
}
|
||||
|
||||
const { generateText } = await import("ai");
|
||||
const { convertOpenAIMessagesToVercel } = await import(
|
||||
"../openaiToVercelMessages.js"
|
||||
);
|
||||
const { convertToolsToVercelFormat } = await import(
|
||||
"../convertToolsToVercel.js"
|
||||
);
|
||||
|
||||
// Convert OpenAI messages to Vercel AI SDK CoreMessage format
|
||||
const vercelMessages = convertOpenAIMessagesToVercel(body.messages);
|
||||
|
||||
|
|
@ -427,7 +435,11 @@ export class AnthropicApi implements BaseLlmApi {
|
|||
temperature: body.temperature ?? undefined,
|
||||
maxTokens: body.max_tokens ?? undefined,
|
||||
topP: body.top_p ?? undefined,
|
||||
stopSequences: body.stop as string[] | undefined,
|
||||
stopSequences: body.stop
|
||||
? Array.isArray(body.stop)
|
||||
? body.stop
|
||||
: [body.stop]
|
||||
: undefined,
|
||||
tools: vercelTools,
|
||||
toolChoice: body.tool_choice as any,
|
||||
abortSignal: signal,
|
||||
|
|
@ -446,7 +458,7 @@ export class AnthropicApi implements BaseLlmApi {
|
|||
return {
|
||||
id: result.response?.id ?? "",
|
||||
object: "chat.completion",
|
||||
created: Date.now(),
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
|
|
@ -594,10 +606,21 @@ export class AnthropicApi implements BaseLlmApi {
|
|||
body: ChatCompletionCreateParamsStreaming,
|
||||
signal: AbortSignal,
|
||||
): AsyncGenerator<ChatCompletionChunk> {
|
||||
await this.initializeVercelProvider();
|
||||
|
||||
if (!this.anthropicProvider) {
|
||||
throw new Error("Vercel AI SDK Anthropic provider not initialized");
|
||||
}
|
||||
|
||||
const { streamText } = await import("ai");
|
||||
const { convertOpenAIMessagesToVercel } = await import(
|
||||
"../openaiToVercelMessages.js"
|
||||
);
|
||||
const { convertToolsToVercelFormat } = await import(
|
||||
"../convertToolsToVercel.js"
|
||||
);
|
||||
const { convertVercelStream } = await import("../vercelStreamConverter.js");
|
||||
|
||||
// Convert OpenAI messages to Vercel AI SDK CoreMessage format
|
||||
const vercelMessages = convertOpenAIMessagesToVercel(body.messages);
|
||||
|
||||
|
|
@ -625,7 +648,11 @@ export class AnthropicApi implements BaseLlmApi {
|
|||
temperature: body.temperature ?? undefined,
|
||||
maxTokens: body.max_tokens ?? undefined,
|
||||
topP: body.top_p ?? undefined,
|
||||
stopSequences: body.stop as string[] | undefined,
|
||||
stopSequences: body.stop
|
||||
? Array.isArray(body.stop)
|
||||
? body.stop
|
||||
: [body.stop]
|
||||
: undefined,
|
||||
tools: vercelTools,
|
||||
toolChoice: body.tool_choice as any,
|
||||
abortSignal: signal,
|
||||
|
|
|
|||
|
|
@ -36,45 +36,17 @@ import {
|
|||
FimCreateParamsStreaming,
|
||||
RerankCreateParams,
|
||||
} from "./base.js";
|
||||
import { createOpenAI } from "@ai-sdk/openai";
|
||||
import { streamText, generateText, streamObject } from "ai";
|
||||
import { convertVercelStream } from "../vercelStreamConverter.js";
|
||||
import { convertToolsToVercelFormat } from "../convertToolsToVercel.js";
|
||||
|
||||
export class OpenAIApi implements BaseLlmApi {
|
||||
openai: OpenAI;
|
||||
apiBase: string = "https://api.openai.com/v1/";
|
||||
private openaiProvider?: ReturnType<typeof createOpenAI>;
|
||||
private openaiProvider?: any;
|
||||
private useVercelSDK: boolean;
|
||||
|
||||
constructor(protected config: z.infer<typeof OpenAIConfigSchema>) {
|
||||
this.apiBase = config.apiBase ?? this.apiBase;
|
||||
this.useVercelSDK = process.env.USE_VERCEL_AI_SDK_OPENAI === "true";
|
||||
|
||||
if (this.useVercelSDK) {
|
||||
// New Vercel AI SDK implementation
|
||||
// Only use customFetch if we have request options that need it
|
||||
// Otherwise use native fetch (Vercel AI SDK requires Web Streams API)
|
||||
const hasRequestOptions =
|
||||
config.requestOptions &&
|
||||
(config.requestOptions.headers ||
|
||||
config.requestOptions.proxy ||
|
||||
config.requestOptions.caBundlePath ||
|
||||
config.requestOptions.clientCertificate ||
|
||||
config.requestOptions.extraBodyProperties);
|
||||
|
||||
this.openaiProvider = createOpenAI({
|
||||
apiKey: config.apiKey ?? "",
|
||||
baseURL:
|
||||
this.apiBase !== "https://api.openai.com/v1/"
|
||||
? this.apiBase
|
||||
: undefined,
|
||||
fetch: hasRequestOptions
|
||||
? customFetch(config.requestOptions)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
// Always create the original OpenAI client for fallback
|
||||
this.openai = new OpenAI({
|
||||
// Necessary because `new OpenAI()` will throw an error if there is no API Key
|
||||
|
|
@ -83,6 +55,33 @@ export class OpenAIApi implements BaseLlmApi {
|
|||
fetch: customFetch(config.requestOptions),
|
||||
});
|
||||
}
|
||||
|
||||
private async initializeVercelProvider() {
|
||||
if (!this.openaiProvider && this.useVercelSDK) {
|
||||
const { createOpenAI } = await import("@ai-sdk/openai");
|
||||
|
||||
// Only use customFetch if we have request options that need it
|
||||
// Otherwise use native fetch (Vercel AI SDK requires Web Streams API)
|
||||
const hasRequestOptions =
|
||||
this.config.requestOptions &&
|
||||
(this.config.requestOptions.headers ||
|
||||
this.config.requestOptions.proxy ||
|
||||
this.config.requestOptions.caBundlePath ||
|
||||
this.config.requestOptions.clientCertificate ||
|
||||
this.config.requestOptions.extraBodyProperties);
|
||||
|
||||
this.openaiProvider = createOpenAI({
|
||||
apiKey: this.config.apiKey ?? "",
|
||||
baseURL:
|
||||
this.apiBase !== "https://api.openai.com/v1/"
|
||||
? this.apiBase
|
||||
: undefined,
|
||||
fetch: hasRequestOptions
|
||||
? customFetch(this.config.requestOptions)
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T {
|
||||
// Add stream_options to include usage in streaming responses
|
||||
if (body.stream) {
|
||||
|
|
@ -177,10 +176,17 @@ export class OpenAIApi implements BaseLlmApi {
|
|||
body: ChatCompletionCreateParamsNonStreaming,
|
||||
signal: AbortSignal,
|
||||
): Promise<ChatCompletion> {
|
||||
await this.initializeVercelProvider();
|
||||
|
||||
if (!this.openaiProvider) {
|
||||
throw new Error("Vercel AI SDK provider not initialized");
|
||||
}
|
||||
|
||||
const { generateText } = await import("ai");
|
||||
const { convertToolsToVercelFormat } = await import(
|
||||
"../convertToolsToVercel.js"
|
||||
);
|
||||
|
||||
const modifiedBody = this.modifyChatBody({ ...body });
|
||||
const model = this.openaiProvider(modifiedBody.model);
|
||||
|
||||
|
|
@ -198,7 +204,11 @@ export class OpenAIApi implements BaseLlmApi {
|
|||
topP: modifiedBody.top_p ?? undefined,
|
||||
frequencyPenalty: modifiedBody.frequency_penalty ?? undefined,
|
||||
presencePenalty: modifiedBody.presence_penalty ?? undefined,
|
||||
stopSequences: modifiedBody.stop as string[] | undefined,
|
||||
stopSequences: modifiedBody.stop
|
||||
? Array.isArray(modifiedBody.stop)
|
||||
? modifiedBody.stop
|
||||
: [modifiedBody.stop]
|
||||
: undefined,
|
||||
tools: vercelTools,
|
||||
toolChoice: modifiedBody.tool_choice as any,
|
||||
abortSignal: signal,
|
||||
|
|
@ -217,7 +227,7 @@ export class OpenAIApi implements BaseLlmApi {
|
|||
return {
|
||||
id: result.response?.id ?? "",
|
||||
object: "chat.completion",
|
||||
created: Date.now(),
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: modifiedBody.model,
|
||||
choices: [
|
||||
{
|
||||
|
|
@ -286,10 +296,18 @@ export class OpenAIApi implements BaseLlmApi {
|
|||
body: ChatCompletionCreateParamsStreaming,
|
||||
signal: AbortSignal,
|
||||
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
|
||||
await this.initializeVercelProvider();
|
||||
|
||||
if (!this.openaiProvider) {
|
||||
throw new Error("Vercel AI SDK provider not initialized");
|
||||
}
|
||||
|
||||
const { streamText } = await import("ai");
|
||||
const { convertToolsToVercelFormat } = await import(
|
||||
"../convertToolsToVercel.js"
|
||||
);
|
||||
const { convertVercelStream } = await import("../vercelStreamConverter.js");
|
||||
|
||||
const modifiedBody = this.modifyChatBody({ ...body });
|
||||
const model = this.openaiProvider(modifiedBody.model);
|
||||
|
||||
|
|
@ -307,7 +325,11 @@ export class OpenAIApi implements BaseLlmApi {
|
|||
topP: modifiedBody.top_p ?? undefined,
|
||||
frequencyPenalty: modifiedBody.frequency_penalty ?? undefined,
|
||||
presencePenalty: modifiedBody.presence_penalty ?? undefined,
|
||||
stopSequences: modifiedBody.stop as string[] | undefined,
|
||||
stopSequences: modifiedBody.stop
|
||||
? Array.isArray(modifiedBody.stop)
|
||||
? modifiedBody.stop
|
||||
: [modifiedBody.stop]
|
||||
: undefined,
|
||||
tools: vercelTools,
|
||||
toolChoice: modifiedBody.tool_choice as any,
|
||||
abortSignal: signal,
|
||||
|
|
|
|||
|
|
@ -26,7 +26,9 @@ export function convertToolsToVercelFormat(
|
|||
if (tool.type === "function") {
|
||||
vercelTools[tool.function.name] = {
|
||||
description: tool.function.description,
|
||||
parameters: aiJsonSchema(tool.function.parameters as any),
|
||||
parameters: aiJsonSchema(
|
||||
tool.function.parameters ?? { type: "object", properties: {} },
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,22 +29,23 @@ function testVercelProvider(config: VercelTestConfig, featureFlag: string) {
|
|||
describe(`${config.provider}/${config.model} (Vercel SDK)`, () => {
|
||||
vi.setConfig({ testTimeout: 30000 });
|
||||
|
||||
// Set feature flag for this test suite
|
||||
let api: any;
|
||||
|
||||
// Set feature flag and create API instance AFTER flag is set
|
||||
beforeAll(() => {
|
||||
process.env[featureFlag] = "true";
|
||||
api = getLlmApi({
|
||||
provider: config.provider as any,
|
||||
apiKey: config.apiKey,
|
||||
apiBase: config.apiBase,
|
||||
env: config.env,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
delete process.env[featureFlag];
|
||||
});
|
||||
|
||||
const api = getLlmApi({
|
||||
provider: config.provider as any,
|
||||
apiKey: config.apiKey,
|
||||
apiBase: config.apiBase,
|
||||
env: config.env,
|
||||
});
|
||||
|
||||
testChat(api, model, {
|
||||
skipTools: skipTools ?? false,
|
||||
expectUsage: expectUsage ?? true,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue