diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index f0efcb9c6..f1e8940b4 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -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; + 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 { + 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 { + 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, diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 1e8944e40..680ea410a 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -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; + private openaiProvider?: any; private useVercelSDK: boolean; constructor(protected config: z.infer) { 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(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 { + 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 { + 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, diff --git a/packages/openai-adapters/src/convertToolsToVercel.ts b/packages/openai-adapters/src/convertToolsToVercel.ts index 3f1e97455..a3f529da9 100644 --- a/packages/openai-adapters/src/convertToolsToVercel.ts +++ b/packages/openai-adapters/src/convertToolsToVercel.ts @@ -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: {} }, + ), }; } } diff --git a/packages/openai-adapters/src/test/vercel-sdk.test.ts b/packages/openai-adapters/src/test/vercel-sdk.test.ts index b70f0d8b6..051750990 100644 --- a/packages/openai-adapters/src/test/vercel-sdk.test.ts +++ b/packages/openai-adapters/src/test/vercel-sdk.test.ts @@ -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,