diff --git a/packages/openai-adapters/VERCEL_AI_SDK.md b/packages/openai-adapters/VERCEL_AI_SDK.md deleted file mode 100644 index 32e05a57e..000000000 --- a/packages/openai-adapters/VERCEL_AI_SDK.md +++ /dev/null @@ -1,494 +0,0 @@ -# Vercel AI SDK Integration - -## Why - -### The Problem - -The openai-adapters package contains ~50 provider implementations, each maintaining: - -- Custom SSE parsing and chunk buffering -- Provider-specific streaming protocols -- Tool call serialization logic -- Type definitions that must stay in sync with provider APIs -- Error handling for provider-specific edge cases - -This represents significant maintenance burden: - -- Provider API changes require manual updates -- Streaming bugs must be debugged per-provider -- New features need implementation across all providers -- Type safety requires constant vigilance - -### The Solution - -The [Vercel AI SDK](https://sdk.vercel.ai/) is a well-maintained, provider-agnostic abstraction that: - -- Handles streaming protocols automatically -- Tracks provider API changes -- Provides unified tool calling interface -- Maintains type safety -- Offers comprehensive error handling - -By offloading this work to Vercel, we reduce ~60% of our maintenance burden while preserving all existing functionality. - -## How It Works - -### Feature-Flagged Implementation - -The integration is feature-flagged for gradual rollout: - -```typescript -// Enable for OpenAI -USE_VERCEL_AI_SDK_OPENAI=true cn - -// Enable for Anthropic -USE_VERCEL_AI_SDK_ANTHROPIC=true cn -``` - -When disabled (default), the original implementation is used. When enabled, Vercel AI SDK handles the provider communication while we maintain the same external API. - -### Architecture - -``` -┌─────────────────────────────────────────────┐ -│ Consumer (CLI / Core IDE) │ -│ - Uses openai-adapters package │ -│ - No code changes required │ -└──────────────────┬──────────────────────────┘ - │ - │ Same API (BaseLlmApi) - │ -┌──────────────────▼──────────────────────────┐ -│ openai-adapters Package │ -│ │ -│ ┌────────────┐ ┌────────────┐ │ -│ │ OpenAIApi │ │AnthropicApi│ │ -│ └─────┬──────┘ └─────┬──────┘ │ -│ │ │ │ -│ Feature Flag? Feature Flag? │ -│ │ │ │ -│ ┌───┴────┐ ┌──┴────┐ │ -│ │ Yes │ │ Yes │ │ -│ ▼ │ ▼ │ │ -│ ┌────────┐ │ ┌────────┐│ │ -│ │ Vercel │ │ │ Vercel ││ │ -│ │ SDK │ │ │ SDK ││ │ -│ └────────┘ │ └────────┘│ │ -│ │ │ │ -│ ┌───┘ ┌───┘ │ -│ │ No │ No │ -│ ▼ ▼ │ -│ ┌────────────┐ ┌────────────┐ │ -│ │ Original │ │ Original │ │ -│ │ SDK │ │ SDK │ │ -│ └────────────┘ └────────────┘ │ -└─────────────────────────────────────────────┘ -``` - -### Custom Fetch Preservation - -All RequestOptions (headers, proxy, SSL certs, timeout) are fully preserved: - -```typescript -// Only use customFetch when RequestOptions are present -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, -}); -``` - -When no custom options are needed, we use native fetch for Web Streams API compatibility. - -### Format Conversion - -Vercel AI SDK uses different formats than OpenAI. We handle conversion transparently: - -**Tool Format:** - -```typescript -// OpenAI format (input) -{ - type: "function", - function: { - name: "readFile", - description: "Read a file", - parameters: { /* JSON Schema */ } - } -} - -// Vercel format (converted) -{ - readFile: { - description: "Read a file", - parameters: aiJsonSchema({ /* JSON Schema */ }) - } -} -``` - -**Stream Events:** - -```typescript -// Vercel AI SDK emits various event types -for await (const part of stream.fullStream) { - switch (part.type) { - case 'text-delta': - yield chatChunk({ content: part.textDelta }); - break; - case 'tool-call': - yield chatChunkFromDelta({ delta: { tool_calls: [...] } }); - break; - case 'finish': - yield usageChatChunk({ usage: part.usage }); - break; - // Filter out events with no OpenAI equivalent - case 'step-start': - case 'step-finish': - case 'tool-result': - continue; - } -} -``` - -All conversion logic lives in shared utilities: - -- `convertToolsToVercelFormat()` - Tool conversion -- `convertVercelStream()` - Stream event conversion -- `convertOpenAIMessagesToVercel()` - Message conversion - -### Automatic Fallbacks - -The implementation intelligently falls back to original SDK when needed: - -**1. OpenAI Responses Endpoint (o1/o3 models)** - -```typescript -if (this.shouldUseResponsesEndpoint(body.model)) { - // Use responses endpoint instead of Vercel SDK - const response = await this.responsesNonStream(body, signal); - return responseToChatCompletion(response); -} -``` - -**2. Anthropic Multi-turn Tool Conversations** - -```typescript -// Vercel SDK manages tool call lifecycle internally -// Can't handle pre-existing tool results in history -const hasToolMessages = body.messages.some((msg) => msg.role === "tool"); - -if (this.useVercelSDK && this.anthropicProvider && !hasToolMessages) { - yield * this.chatCompletionStreamVercel(body, signal); - return; -} - -// Fall back to original for tool conversations -yield * this.handleStreamResponse(response, body.model); -``` - -## Implementation Details - -### Files Modified - -**Core Implementation:** - -- `src/apis/OpenAI.ts` - Added Vercel SDK branch with feature flag -- `src/apis/Anthropic.ts` - Added Vercel SDK branch with fallback logic - -**Shared Utilities (new):** - -- `src/convertToolsToVercel.ts` - Tool format conversion -- `src/vercelStreamConverter.ts` - Stream event conversion -- `src/openaiToVercelMessages.ts` - Message format conversion - -**Tests (new):** - -- `src/test/vercel-sdk.test.ts` - 28 integration tests -- `src/test/convertToolsToVercel.test.ts` - 8 unit tests -- `src/test/vercelStreamConverter.test.ts` - 17 unit tests -- `src/test/multi-turn-tools.test.ts` - Multi-turn conversation test -- `src/test/cli-tools.test.ts` - CLI tool compatibility tests - -### OpenAI Implementation - -```typescript -export class OpenAIApi implements BaseLlmApi { - private openaiProvider?: ReturnType; - private useVercelSDK: boolean; - - constructor(protected config: OpenAIConfig) { - this.useVercelSDK = process.env.USE_VERCEL_AI_SDK_OPENAI === "true"; - - if (this.useVercelSDK) { - 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 original client for fallback - this.openai = new OpenAI({ - /* ... */ - }); - } - - async *chatCompletionStream(body, signal) { - if ( - this.useVercelSDK && - this.openaiProvider && - !this.shouldUseResponsesEndpoint(body.model) - ) { - const model = this.openaiProvider(body.model); - const vercelTools = convertToolsToVercelFormat(body.tools); - - const stream = await streamText({ - model, - messages: body.messages, - tools: vercelTools, - // ... other parameters - }); - - yield* convertVercelStream(stream.fullStream, { model: body.model }); - return; - } - - // Fall back to original implementation - const response = await this.openai.chat.completions.create(body); - for await (const result of response) { - yield result; - } - } -} -``` - -### Anthropic Implementation - -```typescript -export class AnthropicApi implements BaseLlmApi { - private anthropicProvider?: ReturnType; - private useVercelSDK: boolean; - - constructor(protected config: AnthropicConfig) { - this.useVercelSDK = process.env.USE_VERCEL_AI_SDK_ANTHROPIC === "true"; - - if (this.useVercelSDK) { - this.anthropicProvider = createAnthropic({ - apiKey: config.apiKey ?? "", - baseURL: - this.apiBase !== "https://api.anthropic.com/v1/" - ? this.apiBase - : undefined, - fetch: hasRequestOptions - ? customFetch(config.requestOptions) - : undefined, - }); - } - } - - async *chatCompletionStream(body, signal) { - // Check for tool messages in history - const hasToolMessages = body.messages.some((msg) => msg.role === "tool"); - - if (this.useVercelSDK && this.anthropicProvider && !hasToolMessages) { - const vercelMessages = convertOpenAIMessagesToVercel(body.messages); - const model = this.anthropicProvider(body.model); - const vercelTools = convertToolsToVercelFormat(body.tools); - - const stream = await streamText({ - model, - messages: vercelMessages, - tools: vercelTools, - // ... other parameters - }); - - for await (const chunk of convertVercelStream(stream.fullStream, { - model: body.model, - })) { - yield chunk; - } - return; - } - - // Fall back to original implementation - const response = await customFetch(config.requestOptions)( - new URL("messages", this.apiBase), - { method: "POST", body: JSON.stringify(this._convertBody(body)), signal }, - ); - yield* this.handleStreamResponse(response, body.model); - } -} -``` - -## What's Preserved - -### 100% Backward Compatibility - -- ✅ Same `BaseLlmApi` interface -- ✅ Same input/output formats -- ✅ All existing tests pass (191 tests) -- ✅ Zero consumer code changes -- ✅ Custom fetch (headers, proxy, SSL, timeout) -- ✅ Request options infrastructure -- ✅ Provider factory logic -- ✅ Error handling -- ✅ Usage tracking (token counts) - -### What Still Uses Original Implementation - -- FIM completion (not supported by Vercel SDK) -- Reranking (not supported by Vercel SDK) -- Embeddings (not supported by Vercel SDK) -- OpenAI responses endpoint (for o1/o3 models) -- Anthropic multi-turn tool conversations (lifecycle managed by Vercel SDK) - -## Benefits - -### Maintenance Reduction - -**Offloaded to Vercel (~60%):** - -- ✅ SSE parsing and chunk buffering -- ✅ Provider API versioning -- ✅ Tool call serialization -- ✅ Provider-specific error codes -- ✅ Type safety maintenance -- ✅ Streaming protocol handling -- ✅ Backpressure management - -**Still Maintained (~40%):** - -- Format translation (simplified by Vercel SDK's normalized interface) -- Custom features (responses endpoint, FIM, reranking) -- RequestOptions infrastructure -- Provider factory logic - -### Code Quality - -**Immediate:** - -- Shared utilities eliminate duplication -- Better test coverage (57 new tests) -- Cleaner separation of concerns - -**After Full Rollout (~300 LOC reduction):** - -- Complete elimination of SSE parsing -- No more provider-specific chunking -- Simplified error handling -- Reduced type maintenance - -### Rollback Strategy - -**Immediate (< 1 minute):** - -```bash -USE_VERCEL_AI_SDK_OPENAI=false cn -``` - -**Short-term (< 1 hour):** - -```json -"@continuedev/openai-adapters": "1.36.0" -``` - -**Long-term:** -Revert commits (feature flags preserve old code) - -## Testing - -### Run All Tests - -```bash -npm test -``` - -### Test with Vercel SDK Enabled - -```bash -USE_VERCEL_AI_SDK_OPENAI=true cn -USE_VERCEL_AI_SDK_ANTHROPIC=true cn -``` - -### Test Scenarios - -1. **Basic chat** - Simple questions, streaming responses -2. **Tool calls** - First turn tool usage -3. **Multi-turn tools** - Conversation with tool results (Anthropic falls back) -4. **Custom options** - Proxy, headers, SSL certificates -5. **Error handling** - Invalid API key, network errors -6. **Responses endpoint** - o1/o3 models (OpenAI falls back) - -All scenarios should work identically with flags enabled/disabled. - -## Known Limitations - -### Anthropic Multi-turn Tool Conversations - -**Behavior:** Automatically falls back to original implementation when `role: "tool"` messages exist in history. - -**Why:** Vercel AI SDK manages tool call lifecycle internally and doesn't support resuming from pre-existing tool conversations. - -**Impact:** Minimal - tool calls still work, just uses original implementation for subsequent turns. - -### OpenAI Responses Endpoint - -**Behavior:** o1/o3 models bypass Vercel SDK and use responses endpoint. - -**Why:** These models have unique message handling requirements. - -**Impact:** None - automatic fallback is transparent. - -### Not Yet Migrated - -- Other 48 providers (Gemini, Mistral, Azure, Bedrock, etc.) -- FIM completion -- Reranking -- Embeddings - -## Future Work - -### High Priority - -1. Migrate additional providers (Gemini, Mistral) -2. Performance monitoring and optimization -3. Enhanced logging for fallback decisions - -### Medium Priority - -4. Investigate Anthropic prompt caching with Vercel SDK -5. Verify vision/image support with Vercel SDK -6. Add metrics collection - -### Low Priority - -7. Migrate remaining providers -8. Add inline documentation -9. Create usage examples - -## Summary - -The Vercel AI SDK integration: - -- **Reduces maintenance burden by ~60%** -- **Preserves 100% backward compatibility** -- **Enables easy rollback at any point** -- **Improves code quality and test coverage** -- **Benefits both CLI and Core IDE** -- **No consumer code changes required** - -The implementation is production-ready and awaiting Phase 3 validation testing. diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index 0336bab9f..217ee963a 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -54,8 +54,6 @@ import { export class AnthropicApi implements BaseLlmApi { apiBase: string = "https://api.anthropic.com/v1/"; - private anthropicProvider?: any; - private useVercelSDK: boolean; constructor( protected config: AnthropicConfig & { @@ -66,36 +64,6 @@ export class AnthropicApi implements BaseLlmApi { if (!this.apiBase.endsWith("/")) { this.apiBase += "/"; } - - 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"); - - // 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.anthropicProvider = createAnthropic({ - 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(this.config.requestOptions) - : undefined, - }); - } } private _convertBody(oaiBody: ChatCompletionCreateParams) { @@ -335,14 +303,6 @@ export class AnthropicApi implements BaseLlmApi { body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, ): Promise { - // Check if message history contains tool results - // Vercel SDK cannot handle pre-existing tool call conversations - const hasToolMessages = body.messages.some((msg) => msg.role === "tool"); - - if (this.useVercelSDK && !hasToolMessages) { - return this.chatCompletionNonStreamVercel(body, signal); - } - const response = await customFetch(this.config.requestOptions)( new URL("messages", this.apiBase), { @@ -390,108 +350,6 @@ export class AnthropicApi implements BaseLlmApi { }; } - private async chatCompletionNonStreamVercel( - 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" - ); - const { convertToolChoiceToVercel } = await import( - "../convertToolChoiceToVercel.js" - ); - - // Convert OpenAI messages to Vercel AI SDK CoreMessage format - const vercelMessages = convertOpenAIMessagesToVercel(body.messages); - - // Extract system message - const systemMsg = vercelMessages.find((msg) => msg.role === "system"); - const systemText = - systemMsg && typeof systemMsg.content === "string" - ? systemMsg.content - : undefined; - - // Filter out system messages - Vercel AI SDK handles them separately - const nonSystemMessages = vercelMessages.filter( - (msg) => msg.role !== "system", - ); - - const model = this.anthropicProvider(body.model); - - // Convert OpenAI tools to Vercel AI SDK format - const vercelTools = await convertToolsToVercelFormat(body.tools); - - const result = await generateText({ - model, - system: systemText, - messages: nonSystemMessages as any, - temperature: body.temperature ?? undefined, - maxTokens: body.max_tokens ?? undefined, - topP: body.top_p ?? undefined, - stopSequences: body.stop - ? Array.isArray(body.stop) - ? body.stop - : [body.stop] - : undefined, - tools: vercelTools, - toolChoice: convertToolChoiceToVercel(body.tool_choice), - abortSignal: signal, - }); - - // Convert Vercel AI SDK result to OpenAI ChatCompletion format - const toolCalls = result.toolCalls?.map((tc) => ({ - id: tc.toolCallId, - type: "function" as const, - function: { - name: tc.toolName, - arguments: JSON.stringify(tc.args), - }, - })); - - return { - id: result.response?.id ?? "", - object: "chat.completion", - created: Math.floor(Date.now() / 1000), - model: body.model, - choices: [ - { - index: 0, - message: { - role: "assistant", - content: result.text, - tool_calls: toolCalls, - refusal: null, - }, - finish_reason: - result.finishReason === "tool-calls" ? "tool_calls" : "stop", - logprobs: null, - }, - ], - usage: { - prompt_tokens: result.usage.promptTokens, - completion_tokens: result.usage.completionTokens, - total_tokens: result.usage.totalTokens, - prompt_tokens_details: { - cached_tokens: - (result.usage as any).promptTokensDetails?.cachedTokens ?? 0, - cache_read_tokens: - (result.usage as any).promptTokensDetails?.cachedTokens ?? 0, - cache_write_tokens: 0, - } as any, - }, - }; - } - // This is split off so e.g. VertexAI can use it async *handleStreamResponse(response: any, model: string) { let lastToolUseId: string | undefined; @@ -584,15 +442,6 @@ export class AnthropicApi implements BaseLlmApi { body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { - // Check if message history contains tool results - // Vercel SDK cannot handle pre-existing tool call conversations - const hasToolMessages = body.messages.some((msg) => msg.role === "tool"); - - if (this.useVercelSDK && !hasToolMessages) { - yield* this.chatCompletionStreamVercel(body, signal); - return; - } - const response = await customFetch(this.config.requestOptions)( new URL("messages", this.apiBase), { @@ -605,72 +454,6 @@ export class AnthropicApi implements BaseLlmApi { yield* this.handleStreamResponse(response, body.model); } - private async *chatCompletionStreamVercel( - 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"); - const { convertToolChoiceToVercel } = await import( - "../convertToolChoiceToVercel.js" - ); - - // Convert OpenAI messages to Vercel AI SDK CoreMessage format - const vercelMessages = convertOpenAIMessagesToVercel(body.messages); - - // Extract system message - const systemMsg = vercelMessages.find((msg) => msg.role === "system"); - const systemText = - systemMsg && typeof systemMsg.content === "string" - ? systemMsg.content - : undefined; - - // Filter out system messages - Vercel AI SDK handles them separately - const nonSystemMessages = vercelMessages.filter( - (msg) => msg.role !== "system", - ); - - const model = this.anthropicProvider(body.model); - - // Convert OpenAI tools to Vercel AI SDK format - const vercelTools = await convertToolsToVercelFormat(body.tools); - - const stream = await streamText({ - model, - system: systemText, - messages: nonSystemMessages as any, - temperature: body.temperature ?? undefined, - maxTokens: body.max_tokens ?? undefined, - topP: body.top_p ?? undefined, - stopSequences: body.stop - ? Array.isArray(body.stop) - ? body.stop - : [body.stop] - : undefined, - tools: vercelTools, - toolChoice: convertToolChoiceToVercel(body.tool_choice), - abortSignal: signal, - }); - - // Convert Vercel AI SDK stream to OpenAI format - // The finish event in fullStream contains the usage data - yield* convertVercelStream(stream.fullStream as any, { - model: body.model, - }); - } - private getHeaders(): Record { const enableCaching = this.config?.cachingStrategy !== "none"; return getAnthropicHeaders(this.config.apiKey, enableCaching, this.apiBase); diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 44d39521b..6734e1c48 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -17,12 +17,13 @@ import type { } from "openai/resources/responses/responses.js"; import { z } from "zod"; import { OpenAIConfigSchema } from "../types.js"; +import { customFetch } from "../util.js"; import { - customFetch, - chatChunk, - usageChatChunk, - chatChunkFromDelta, -} from "../util.js"; + BaseLlmApi, + CreateRerankResponse, + FimCreateParamsStreaming, + RerankCreateParams, +} from "./base.js"; import { createResponsesStreamState, fromResponsesChunk, @@ -30,22 +31,13 @@ import { responseToChatCompletion, toResponsesParams, } from "./openaiResponses.js"; -import { - BaseLlmApi, - CreateRerankResponse, - FimCreateParamsStreaming, - RerankCreateParams, -} from "./base.js"; export class OpenAIApi implements BaseLlmApi { openai: OpenAI; apiBase: string = "https://api.openai.com/v1/"; - 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"; // Always create the original OpenAI client for fallback this.openai = new OpenAI({ @@ -56,33 +48,6 @@ export class OpenAIApi implements BaseLlmApi { timeout: config?.requestOptions?.timeout || undefined, }); } - - 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) { @@ -152,10 +117,6 @@ export class OpenAIApi implements BaseLlmApi { body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, ): Promise { - if (this.useVercelSDK && !this.shouldUseResponsesEndpoint(body.model)) { - return this.chatCompletionNonStreamVercel(body, signal); - } - if (this.shouldUseResponsesEndpoint(body.model)) { const response = await this.responsesNonStream(body, signal); return responseToChatCompletion(response); @@ -169,97 +130,10 @@ export class OpenAIApi implements BaseLlmApi { return response; } - private async chatCompletionNonStreamVercel( - 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 { convertToolChoiceToVercel } = await import( - "../convertToolChoiceToVercel.js" - ); - - const modifiedBody = this.modifyChatBody({ ...body }); - const model = this.openaiProvider(modifiedBody.model); - - // Convert OpenAI tools to Vercel AI SDK format - const vercelTools = await convertToolsToVercelFormat(modifiedBody.tools); - - const result = await generateText({ - model, - messages: modifiedBody.messages as any, - temperature: modifiedBody.temperature ?? undefined, - maxTokens: - modifiedBody.max_completion_tokens ?? - modifiedBody.max_tokens ?? - undefined, - topP: modifiedBody.top_p ?? undefined, - frequencyPenalty: modifiedBody.frequency_penalty ?? undefined, - presencePenalty: modifiedBody.presence_penalty ?? undefined, - stopSequences: modifiedBody.stop - ? Array.isArray(modifiedBody.stop) - ? modifiedBody.stop - : [modifiedBody.stop] - : undefined, - tools: vercelTools, - toolChoice: convertToolChoiceToVercel(modifiedBody.tool_choice), - abortSignal: signal, - }); - - // Convert Vercel AI SDK result to OpenAI ChatCompletion format - const toolCalls = result.toolCalls?.map((tc, index) => ({ - id: tc.toolCallId, - type: "function" as const, - function: { - name: tc.toolName, - arguments: JSON.stringify(tc.args), - }, - })); - - return { - id: result.response?.id ?? "", - object: "chat.completion", - created: Math.floor(Date.now() / 1000), - model: modifiedBody.model, - choices: [ - { - index: 0, - message: { - role: "assistant", - content: result.text, - tool_calls: toolCalls, - refusal: null, - }, - finish_reason: - result.finishReason === "tool-calls" ? "tool_calls" : "stop", - logprobs: null, - }, - ], - usage: { - prompt_tokens: result.usage.promptTokens, - completion_tokens: result.usage.completionTokens, - total_tokens: result.usage.totalTokens, - }, - }; - } - async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, ): AsyncGenerator { - if (this.useVercelSDK && !this.shouldUseResponsesEndpoint(body.model)) { - yield* this.chatCompletionStreamVercel(body, signal); - return; - } - if (this.shouldUseResponsesEndpoint(body.model)) { for await (const chunk of this.responsesStream(body, signal)) { yield chunk; @@ -287,59 +161,6 @@ export class OpenAIApi implements BaseLlmApi { yield lastChunkWithUsage; } } - - private async *chatCompletionStreamVercel( - 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 { convertToolChoiceToVercel } = await import( - "../convertToolChoiceToVercel.js" - ); - - const modifiedBody = this.modifyChatBody({ ...body }); - const model = this.openaiProvider(modifiedBody.model); - - // Convert OpenAI tools to Vercel AI SDK format - const vercelTools = await convertToolsToVercelFormat(modifiedBody.tools); - - const stream = await streamText({ - model, - messages: modifiedBody.messages as any, - temperature: modifiedBody.temperature ?? undefined, - maxTokens: - modifiedBody.max_completion_tokens ?? - modifiedBody.max_tokens ?? - undefined, - topP: modifiedBody.top_p ?? undefined, - frequencyPenalty: modifiedBody.frequency_penalty ?? undefined, - presencePenalty: modifiedBody.presence_penalty ?? undefined, - stopSequences: modifiedBody.stop - ? Array.isArray(modifiedBody.stop) - ? modifiedBody.stop - : [modifiedBody.stop] - : undefined, - tools: vercelTools, - toolChoice: convertToolChoiceToVercel(modifiedBody.tool_choice), - abortSignal: signal, - }); - - // Convert Vercel AI SDK stream to OpenAI format - // The finish event in fullStream contains the usage data - yield* convertVercelStream(stream.fullStream as any, { - model: modifiedBody.model, - }); - } async completionNonStream( body: CompletionCreateParamsNonStreaming, signal: AbortSignal, diff --git a/packages/openai-adapters/src/test/cli-tools.test.ts b/packages/openai-adapters/src/test/cli-tools.test.ts index 50636569e..5af0da078 100644 --- a/packages/openai-adapters/src/test/cli-tools.test.ts +++ b/packages/openai-adapters/src/test/cli-tools.test.ts @@ -9,18 +9,10 @@ dotenv.config(); if (process.env.OPENAI_API_KEY) { describe("CLI Tool Format Test", () => { - // Set feature flag - beforeAll(() => { - process.env.USE_VERCEL_AI_SDK_OPENAI = "true"; - }); - - afterAll(() => { - delete process.env.USE_VERCEL_AI_SDK_OPENAI; - }); - test("should work with actual CLI tool format (after toChatBody conversion)", async () => { const api = getLlmApi({ - provider: "openai", + provider: "ai-sdk", + model: "openai/gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY!, }); @@ -52,7 +44,7 @@ if (process.env.OPENAI_API_KEY) { let response = ""; for await (const chunk of api.chatCompletionStream( { - model: "gpt-4o-mini", + model: "openai/gpt-4o-mini", messages: [ { role: "user", @@ -75,17 +67,17 @@ if (process.env.OPENAI_API_KEY) { test("should work with empty tools array", async () => { const api = getLlmApi({ - provider: "openai", + provider: "ai-sdk", + model: "openai/gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY!, }); - // Test with empty array (common case) const tools: any[] = []; let response = ""; for await (const chunk of api.chatCompletionStream( { - model: "gpt-4o-mini", + model: "openai/gpt-4o-mini", messages: [ { role: "user", @@ -107,14 +99,15 @@ if (process.env.OPENAI_API_KEY) { test("should work with undefined tools", async () => { const api = getLlmApi({ - provider: "openai", + provider: "ai-sdk", + model: "openai/gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY!, }); let response = ""; for await (const chunk of api.chatCompletionStream( { - model: "gpt-4o-mini", + model: "openai/gpt-4o-mini", messages: [ { role: "user", diff --git a/packages/openai-adapters/src/test/multi-turn-tools.test.ts b/packages/openai-adapters/src/test/multi-turn-tools.test.ts deleted file mode 100644 index dbf248aba..000000000 --- a/packages/openai-adapters/src/test/multi-turn-tools.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import * as dotenv from "dotenv"; -import { getLlmApi } from "./util.js"; -import type { ChatCompletionMessageParam } from "openai/resources/index.js"; - -dotenv.config(); - -/** - * Test multi-turn conversation with tool calls to reproduce the zod error - */ - -if (process.env.ANTHROPIC_API_KEY) { - describe("Multi-turn Tool Call Test (Anthropic)", () => { - // Set feature flag at describe-time (before test collection) - process.env.USE_VERCEL_AI_SDK_ANTHROPIC = "true"; - - afterAll(() => { - delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC; - }); - - test("should handle multi-turn conversation with tool calls and tool results", async () => { - // Create fresh API instance with flag already set - const api = getLlmApi({ - provider: "anthropic", - apiKey: process.env.ANTHROPIC_API_KEY!, - }); - - const tools = [ - { - type: "function" as const, - function: { - name: "List", - description: "List files in a directory", - parameters: { - type: "object", - required: ["dirpath"], - properties: { - dirpath: { - type: "string", - description: "The directory path to list", - }, - }, - }, - }, - }, - { - type: "function" as const, - function: { - name: "Read", - description: "Read a file", - parameters: { - type: "object", - required: ["filepath"], - properties: { - filepath: { - type: "string", - description: "The path of the file to read", - }, - }, - }, - }, - }, - ]; - - // Turn 1: User asks to investigate codebase - const messages1: ChatCompletionMessageParam[] = [ - { - role: "user", - content: "please investigate this codebase a bit", - }, - ]; - - console.log("\n=== Turn 1: Initial request ==="); - let assistantResponse = ""; - const toolCalls: any[] = []; - - for await (const chunk of api.chatCompletionStream( - { - model: "claude-haiku-4-5", - messages: messages1, - tools, - stream: true, - }, - new AbortController().signal, - )) { - if (chunk.choices.length > 0) { - const delta = chunk.choices[0].delta; - if (delta.content) { - assistantResponse += delta.content; - } - if (delta.tool_calls) { - for (const tc of delta.tool_calls) { - if (tc.id) { - // New tool call - toolCalls.push({ - id: tc.id, - type: "function", - function: { - name: tc.function?.name || "", - arguments: tc.function?.arguments || "", - }, - }); - } else if (tc.index !== undefined && toolCalls[tc.index]) { - // Delta for existing tool call - if (tc.function?.arguments) { - toolCalls[tc.index].function.arguments += - tc.function.arguments; - } - } - } - } - } - } - - console.log("Assistant response:", assistantResponse); - console.log("Tool calls:", JSON.stringify(toolCalls, null, 2)); - - expect(toolCalls.length).toBeGreaterThan(0); - - // Turn 2: Send tool results back - const messages2: ChatCompletionMessageParam[] = [ - ...messages1, - { - role: "assistant", - content: assistantResponse || null, - tool_calls: toolCalls.length > 0 ? toolCalls : undefined, - }, - { - role: "tool", - tool_call_id: toolCalls[0].id, - content: "Files in /test:\npackage.json (file)\nREADME.md (file)", - }, - ]; - - // Add more tool results if there were multiple tool calls - for (let i = 1; i < toolCalls.length; i++) { - messages2.push({ - role: "tool", - tool_call_id: toolCalls[i].id, - content: `Result for ${toolCalls[i].function.name}`, - }); - } - - console.log("\n=== Turn 2: Sending tool results ==="); - console.log("Messages:", JSON.stringify(messages2, null, 2)); - - // This should trigger the zod error if the bug exists - let response2 = ""; - for await (const chunk of api.chatCompletionStream( - { - model: "claude-haiku-4-5", - messages: messages2, - tools, - stream: true, - }, - new AbortController().signal, - )) { - if (chunk.choices.length > 0) { - response2 += chunk.choices[0].delta.content ?? ""; - } - } - - console.log("Second response:", response2); - expect(response2.length).toBeGreaterThan(0); - }, 60000); - }); -} else { - test.skip("Multi-turn tool call test skipped - no Anthropic API key", () => {}); -} diff --git a/packages/openai-adapters/src/test/vercel-sdk.test.ts b/packages/openai-adapters/src/test/vercel-sdk.test.ts index 480baf51a..f4c65cecc 100644 --- a/packages/openai-adapters/src/test/vercel-sdk.test.ts +++ b/packages/openai-adapters/src/test/vercel-sdk.test.ts @@ -1,4 +1,3 @@ -import { ModelConfig } from "@continuedev/config-yaml"; import * as dotenv from "dotenv"; import { vi } from "vitest"; import { getLlmApi, testChat } from "./util.js"; @@ -8,46 +7,42 @@ dotenv.config(); /** * Vercel AI SDK Integration Tests * - * These tests verify that the Vercel AI SDK integration produces the same + * These tests verify that the AI SDK provider produces the same * results as the original implementation, ensuring contract compatibility. - * - * Tests run with feature flags enabled: - * - USE_VERCEL_AI_SDK_OPENAI=true - * - USE_VERCEL_AI_SDK_ANTHROPIC=true */ -interface VercelTestConfig extends Omit { +interface AiSdkTestConfig { + aiSdkProviderId: string; + model: string; + apiKey: string; + apiBase?: string; skipTools?: boolean; expectUsage?: boolean; skipSystemMessage?: boolean; } -function testVercelProvider(config: VercelTestConfig, featureFlag: string) { - const { skipTools, expectUsage, skipSystemMessage, ...modelConfig } = config; - const model = config.model; +function testAiSdkProvider(config: AiSdkTestConfig) { + const { + skipTools, + skipSystemMessage, + aiSdkProviderId, + model, + apiKey, + apiBase, + } = config; + const fullModel = `${aiSdkProviderId}/${model}`; - describe(`${config.provider}/${config.model} (Vercel SDK)`, () => { + describe(`${aiSdkProviderId}/${model} (AI SDK)`, () => { vi.setConfig({ testTimeout: 30000 }); - // Set feature flag at describe-time (before test collection) - process.env[featureFlag] = "true"; - - // Create a factory that makes fresh API instances for each test - // This ensures the API is created AFTER the feature flag is set - const apiFactory = () => { - return getLlmApi({ - provider: config.provider as any, - apiKey: config.apiKey, - apiBase: config.apiBase, - env: config.env, - }); - }; - - afterAll(() => { - delete process.env[featureFlag]; + const api = getLlmApi({ + provider: "ai-sdk", + model: fullModel, + apiKey, + apiBase, }); - testChat(apiFactory(), model, { + testChat(api, fullModel, { skipTools: skipTools ?? false, // TODO: Vercel AI SDK fullStream usage tokens are unreliable - investigate expectUsage: false, // Temporarily disable usage assertions @@ -56,59 +51,47 @@ function testVercelProvider(config: VercelTestConfig, featureFlag: string) { }); } -// OpenAI Vercel SDK Tests +// OpenAI AI SDK Tests if (process.env.OPENAI_API_KEY) { - describe("OpenAI with Vercel AI SDK", () => { - testVercelProvider( - { - provider: "openai", - model: "gpt-4o-mini", - apiKey: process.env.OPENAI_API_KEY!, - skipTools: false, - expectUsage: true, - }, - "USE_VERCEL_AI_SDK_OPENAI", - ); + describe("OpenAI with AI SDK", () => { + testAiSdkProvider({ + aiSdkProviderId: "openai", + model: "gpt-4o-mini", + apiKey: process.env.OPENAI_API_KEY!, + skipTools: false, + expectUsage: true, + }); - testVercelProvider( - { - provider: "openai", - model: "gpt-4o", - apiKey: process.env.OPENAI_API_KEY!, - skipTools: false, - expectUsage: true, - }, - "USE_VERCEL_AI_SDK_OPENAI", - ); + testAiSdkProvider({ + aiSdkProviderId: "openai", + model: "gpt-4o", + apiKey: process.env.OPENAI_API_KEY!, + skipTools: false, + expectUsage: true, + }); }); } else { test.skip("OpenAI tests skipped - no API key", () => {}); } -// Anthropic Vercel SDK Tests +// Anthropic AI SDK Tests if (process.env.ANTHROPIC_API_KEY) { - describe("Anthropic with Vercel AI SDK", () => { - testVercelProvider( - { - provider: "anthropic", - model: "claude-haiku-4-5", - apiKey: process.env.ANTHROPIC_API_KEY!, - skipTools: false, - expectUsage: true, - }, - "USE_VERCEL_AI_SDK_ANTHROPIC", - ); + describe("Anthropic with AI SDK", () => { + testAiSdkProvider({ + aiSdkProviderId: "anthropic", + model: "claude-haiku-4-5", + apiKey: process.env.ANTHROPIC_API_KEY!, + skipTools: false, + expectUsage: true, + }); - testVercelProvider( - { - provider: "anthropic", - model: "claude-sonnet-4-5", - apiKey: process.env.ANTHROPIC_API_KEY!, - skipTools: false, - expectUsage: true, - }, - "USE_VERCEL_AI_SDK_ANTHROPIC", - ); + testAiSdkProvider({ + aiSdkProviderId: "anthropic", + model: "claude-sonnet-4-5", + apiKey: process.env.ANTHROPIC_API_KEY!, + skipTools: false, + expectUsage: true, + }); }); } else { test.skip("Anthropic tests skipped - no API key", () => {}); @@ -116,7 +99,7 @@ if (process.env.ANTHROPIC_API_KEY) { // Comparison Tests: Verify outputs match between old and new implementations describe("Contract Compatibility Tests", () => { - describe("OpenAI: Original vs Vercel SDK", () => { + describe("OpenAI: Original vs AI SDK", () => { if (!process.env.OPENAI_API_KEY) { test.skip("OpenAI comparison tests skipped - no API key", () => {}); return; @@ -124,12 +107,9 @@ describe("Contract Compatibility Tests", () => { const testPrompt = "Say 'Hello World' and nothing else."; const model = "gpt-4o-mini"; + const aiSdkModel = "openai/gpt-4o-mini"; test("streaming output format matches", async () => { - // Test with original implementation - delete process.env.USE_VERCEL_AI_SDK_OPENAI; - - // Create API instance after setting/clearing environment variable const originalApi = getLlmApi({ provider: "openai", apiKey: process.env.OPENAI_API_KEY!, @@ -147,52 +127,45 @@ describe("Contract Compatibility Tests", () => { originalChunks.push(chunk); } - // Test with Vercel SDK implementation - // Important: Set flag before creating the API instance - process.env.USE_VERCEL_AI_SDK_OPENAI = "true"; - - // Create a fresh API instance with the flag enabled - const vercelApi = getLlmApi({ - provider: "openai", + const aiSdkApi = getLlmApi({ + provider: "ai-sdk", + model: aiSdkModel, apiKey: process.env.OPENAI_API_KEY!, }); - const vercelChunks: any[] = []; + const aiSdkChunks: any[] = []; try { - for await (const chunk of vercelApi.chatCompletionStream( + for await (const chunk of aiSdkApi.chatCompletionStream( { - model, + model: aiSdkModel, messages: [{ role: "user", content: testPrompt }], stream: true, }, new AbortController().signal, )) { - vercelChunks.push(chunk); + aiSdkChunks.push(chunk); } } catch (error) { - console.error("Error in OpenAI vercel streaming:", error); + console.error("Error in OpenAI AI SDK streaming:", error); throw error; } - // Verify both have chunks expect(originalChunks.length).toBeGreaterThan(0); console.log( - `OpenAI - Original chunks: ${originalChunks.length}, Vercel chunks: ${vercelChunks.length}`, + `OpenAI - Original chunks: ${originalChunks.length}, AI SDK chunks: ${aiSdkChunks.length}`, ); - expect(vercelChunks.length).toBeGreaterThan(0); + expect(aiSdkChunks.length).toBeGreaterThan(0); - // Verify chunk structure matches const originalContentChunks = originalChunks.filter( (c) => c.choices.length > 0, ); - const vercelContentChunks = vercelChunks.filter( + const aiSdkContentChunks = aiSdkChunks.filter( (c) => c.choices.length > 0, ); expect(originalContentChunks.length).toBeGreaterThan(0); - expect(vercelContentChunks.length).toBeGreaterThan(0); + expect(aiSdkContentChunks.length).toBeGreaterThan(0); - // Verify chunk format originalContentChunks.forEach((chunk) => { expect(chunk).toHaveProperty("choices"); expect(chunk).toHaveProperty("model"); @@ -200,36 +173,29 @@ describe("Contract Compatibility Tests", () => { expect(chunk.object).toBe("chat.completion.chunk"); }); - vercelContentChunks.forEach((chunk) => { + aiSdkContentChunks.forEach((chunk) => { expect(chunk).toHaveProperty("choices"); expect(chunk).toHaveProperty("model"); expect(chunk).toHaveProperty("object"); expect(chunk.object).toBe("chat.completion.chunk"); }); - // Verify usage chunk exists in both const originalUsageChunk = originalChunks.find((c) => c.usage); - const vercelUsageChunk = vercelChunks.find((c) => c.usage); + const aiSdkUsageChunk = aiSdkChunks.find((c) => c.usage); expect(originalUsageChunk).toBeDefined(); - expect(vercelUsageChunk).toBeDefined(); + expect(aiSdkUsageChunk).toBeDefined(); expect(originalUsageChunk.usage).toHaveProperty("prompt_tokens"); expect(originalUsageChunk.usage).toHaveProperty("completion_tokens"); expect(originalUsageChunk.usage).toHaveProperty("total_tokens"); - expect(vercelUsageChunk.usage).toHaveProperty("prompt_tokens"); - expect(vercelUsageChunk.usage).toHaveProperty("completion_tokens"); - expect(vercelUsageChunk.usage).toHaveProperty("total_tokens"); - - delete process.env.USE_VERCEL_AI_SDK_OPENAI; + expect(aiSdkUsageChunk.usage).toHaveProperty("prompt_tokens"); + expect(aiSdkUsageChunk.usage).toHaveProperty("completion_tokens"); + expect(aiSdkUsageChunk.usage).toHaveProperty("total_tokens"); }); test("non-streaming output format matches", async () => { - // Test with original implementation - delete process.env.USE_VERCEL_AI_SDK_OPENAI; - - // Create API instance after setting/clearing environment variable const originalApi = getLlmApi({ provider: "openai", apiKey: process.env.OPENAI_API_KEY!, @@ -244,26 +210,21 @@ describe("Contract Compatibility Tests", () => { new AbortController().signal, ); - // Test with Vercel SDK implementation - // Important: Set flag before creating the API instance - process.env.USE_VERCEL_AI_SDK_OPENAI = "true"; - - // Create a fresh API instance with the flag enabled - const vercelApi = getLlmApi({ - provider: "openai", + const aiSdkApi = getLlmApi({ + provider: "ai-sdk", + model: aiSdkModel, apiKey: process.env.OPENAI_API_KEY!, }); - const vercelResponse = await vercelApi.chatCompletionNonStream( + const aiSdkResponse = await aiSdkApi.chatCompletionNonStream( { - model, + model: aiSdkModel, messages: [{ role: "user", content: testPrompt }], stream: false, }, new AbortController().signal, ); - // Verify response structure matches expect(originalResponse).toHaveProperty("id"); expect(originalResponse).toHaveProperty("object"); expect(originalResponse).toHaveProperty("created"); @@ -271,40 +232,38 @@ describe("Contract Compatibility Tests", () => { expect(originalResponse).toHaveProperty("choices"); expect(originalResponse).toHaveProperty("usage"); - expect(vercelResponse).toHaveProperty("id"); - expect(vercelResponse).toHaveProperty("object"); - expect(vercelResponse).toHaveProperty("created"); - expect(vercelResponse).toHaveProperty("model"); - expect(vercelResponse).toHaveProperty("choices"); - expect(vercelResponse).toHaveProperty("usage"); + expect(aiSdkResponse).toHaveProperty("id"); + expect(aiSdkResponse).toHaveProperty("object"); + expect(aiSdkResponse).toHaveProperty("created"); + expect(aiSdkResponse).toHaveProperty("model"); + expect(aiSdkResponse).toHaveProperty("choices"); + expect(aiSdkResponse).toHaveProperty("usage"); expect(originalResponse.object).toBe("chat.completion"); - expect(vercelResponse.object).toBe("chat.completion"); + expect(aiSdkResponse.object).toBe("chat.completion"); expect(originalResponse.choices.length).toBe(1); - expect(vercelResponse.choices.length).toBe(1); + expect(aiSdkResponse.choices.length).toBe(1); expect(originalResponse.choices[0]).toHaveProperty("message"); expect(originalResponse.choices[0].message).toHaveProperty("role"); expect(originalResponse.choices[0].message).toHaveProperty("content"); - expect(vercelResponse.choices[0]).toHaveProperty("message"); - expect(vercelResponse.choices[0].message).toHaveProperty("role"); - expect(vercelResponse.choices[0].message).toHaveProperty("content"); + expect(aiSdkResponse.choices[0]).toHaveProperty("message"); + expect(aiSdkResponse.choices[0].message).toHaveProperty("role"); + expect(aiSdkResponse.choices[0].message).toHaveProperty("content"); expect(originalResponse.usage).toHaveProperty("prompt_tokens"); expect(originalResponse.usage).toHaveProperty("completion_tokens"); expect(originalResponse.usage).toHaveProperty("total_tokens"); - expect(vercelResponse.usage).toHaveProperty("prompt_tokens"); - expect(vercelResponse.usage).toHaveProperty("completion_tokens"); - expect(vercelResponse.usage).toHaveProperty("total_tokens"); - - delete process.env.USE_VERCEL_AI_SDK_OPENAI; + expect(aiSdkResponse.usage).toHaveProperty("prompt_tokens"); + expect(aiSdkResponse.usage).toHaveProperty("completion_tokens"); + expect(aiSdkResponse.usage).toHaveProperty("total_tokens"); }); }); - describe("Anthropic: Original vs Vercel SDK", () => { + describe("Anthropic: Original vs AI SDK", () => { if (!process.env.ANTHROPIC_API_KEY) { test.skip("Anthropic comparison tests skipped - no API key", () => {}); return; @@ -312,12 +271,9 @@ describe("Contract Compatibility Tests", () => { const testPrompt = "Say 'Hello World' and nothing else."; const model = "claude-haiku-4-5"; + const aiSdkModel = "anthropic/claude-haiku-4-5"; test("streaming output format matches", async () => { - // Test with original implementation - delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC; - - // Create API instance after setting/clearing environment variable const originalApi = getLlmApi({ provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, @@ -335,52 +291,45 @@ describe("Contract Compatibility Tests", () => { originalChunks.push(chunk); } - // Test with Vercel SDK implementation - // Important: Set flag before creating the API instance - process.env.USE_VERCEL_AI_SDK_ANTHROPIC = "true"; - - // Create a fresh API instance with the flag enabled - const vercelApi = getLlmApi({ - provider: "anthropic", + const aiSdkApi = getLlmApi({ + provider: "ai-sdk", + model: aiSdkModel, apiKey: process.env.ANTHROPIC_API_KEY!, }); - const vercelChunks: any[] = []; + const aiSdkChunks: any[] = []; try { - for await (const chunk of vercelApi.chatCompletionStream( + for await (const chunk of aiSdkApi.chatCompletionStream( { - model, + model: aiSdkModel, messages: [{ role: "user", content: testPrompt }], stream: true, }, new AbortController().signal, )) { - vercelChunks.push(chunk); + aiSdkChunks.push(chunk); } } catch (error) { - console.error("Error in Anthropic vercel streaming:", error); + console.error("Error in Anthropic AI SDK streaming:", error); throw error; } - // Verify both have chunks expect(originalChunks.length).toBeGreaterThan(0); console.log( - `Anthropic - Original chunks: ${originalChunks.length}, Vercel chunks: ${vercelChunks.length}`, + `Anthropic - Original chunks: ${originalChunks.length}, AI SDK chunks: ${aiSdkChunks.length}`, ); - expect(vercelChunks.length).toBeGreaterThan(0); + expect(aiSdkChunks.length).toBeGreaterThan(0); - // Verify chunk structure matches const originalContentChunks = originalChunks.filter( (c) => c.choices.length > 0, ); - const vercelContentChunks = vercelChunks.filter( + const aiSdkContentChunks = aiSdkChunks.filter( (c) => c.choices.length > 0, ); expect(originalContentChunks.length).toBeGreaterThan(0); - expect(vercelContentChunks.length).toBeGreaterThan(0); + expect(aiSdkContentChunks.length).toBeGreaterThan(0); - // Verify chunk format originalContentChunks.forEach((chunk) => { expect(chunk).toHaveProperty("choices"); expect(chunk).toHaveProperty("model"); @@ -388,36 +337,29 @@ describe("Contract Compatibility Tests", () => { expect(chunk.object).toBe("chat.completion.chunk"); }); - vercelContentChunks.forEach((chunk) => { + aiSdkContentChunks.forEach((chunk) => { expect(chunk).toHaveProperty("choices"); expect(chunk).toHaveProperty("model"); expect(chunk).toHaveProperty("object"); expect(chunk.object).toBe("chat.completion.chunk"); }); - // Verify usage chunk exists in both const originalUsageChunk = originalChunks.find((c) => c.usage); - const vercelUsageChunk = vercelChunks.find((c) => c.usage); + const aiSdkUsageChunk = aiSdkChunks.find((c) => c.usage); expect(originalUsageChunk).toBeDefined(); - expect(vercelUsageChunk).toBeDefined(); + expect(aiSdkUsageChunk).toBeDefined(); expect(originalUsageChunk.usage).toHaveProperty("prompt_tokens"); expect(originalUsageChunk.usage).toHaveProperty("completion_tokens"); expect(originalUsageChunk.usage).toHaveProperty("total_tokens"); - expect(vercelUsageChunk.usage).toHaveProperty("prompt_tokens"); - expect(vercelUsageChunk.usage).toHaveProperty("completion_tokens"); - expect(vercelUsageChunk.usage).toHaveProperty("total_tokens"); - - delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC; + expect(aiSdkUsageChunk.usage).toHaveProperty("prompt_tokens"); + expect(aiSdkUsageChunk.usage).toHaveProperty("completion_tokens"); + expect(aiSdkUsageChunk.usage).toHaveProperty("total_tokens"); }); test("non-streaming output format matches", async () => { - // Test with original implementation - delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC; - - // Create API instance after setting/clearing environment variable const originalApi = getLlmApi({ provider: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY!, @@ -432,26 +374,21 @@ describe("Contract Compatibility Tests", () => { new AbortController().signal, ); - // Test with Vercel SDK implementation - // Important: Set flag before creating the API instance - process.env.USE_VERCEL_AI_SDK_ANTHROPIC = "true"; - - // Create a fresh API instance with the flag enabled - const vercelApi = getLlmApi({ - provider: "anthropic", + const aiSdkApi = getLlmApi({ + provider: "ai-sdk", + model: aiSdkModel, apiKey: process.env.ANTHROPIC_API_KEY!, }); - const vercelResponse = await vercelApi.chatCompletionNonStream( + const aiSdkResponse = await aiSdkApi.chatCompletionNonStream( { - model, + model: aiSdkModel, messages: [{ role: "user", content: testPrompt }], stream: false, }, new AbortController().signal, ); - // Verify response structure matches expect(originalResponse).toHaveProperty("id"); expect(originalResponse).toHaveProperty("object"); expect(originalResponse).toHaveProperty("created"); @@ -459,36 +396,34 @@ describe("Contract Compatibility Tests", () => { expect(originalResponse).toHaveProperty("choices"); expect(originalResponse).toHaveProperty("usage"); - expect(vercelResponse).toHaveProperty("id"); - expect(vercelResponse).toHaveProperty("object"); - expect(vercelResponse).toHaveProperty("created"); - expect(vercelResponse).toHaveProperty("model"); - expect(vercelResponse).toHaveProperty("choices"); - expect(vercelResponse).toHaveProperty("usage"); + expect(aiSdkResponse).toHaveProperty("id"); + expect(aiSdkResponse).toHaveProperty("object"); + expect(aiSdkResponse).toHaveProperty("created"); + expect(aiSdkResponse).toHaveProperty("model"); + expect(aiSdkResponse).toHaveProperty("choices"); + expect(aiSdkResponse).toHaveProperty("usage"); expect(originalResponse.object).toBe("chat.completion"); - expect(vercelResponse.object).toBe("chat.completion"); + expect(aiSdkResponse.object).toBe("chat.completion"); expect(originalResponse.choices.length).toBe(1); - expect(vercelResponse.choices.length).toBe(1); + expect(aiSdkResponse.choices.length).toBe(1); expect(originalResponse.choices[0]).toHaveProperty("message"); expect(originalResponse.choices[0].message).toHaveProperty("role"); expect(originalResponse.choices[0].message).toHaveProperty("content"); - expect(vercelResponse.choices[0]).toHaveProperty("message"); - expect(vercelResponse.choices[0].message).toHaveProperty("role"); - expect(vercelResponse.choices[0].message).toHaveProperty("content"); + expect(aiSdkResponse.choices[0]).toHaveProperty("message"); + expect(aiSdkResponse.choices[0].message).toHaveProperty("role"); + expect(aiSdkResponse.choices[0].message).toHaveProperty("content"); expect(originalResponse.usage).toHaveProperty("prompt_tokens"); expect(originalResponse.usage).toHaveProperty("completion_tokens"); expect(originalResponse.usage).toHaveProperty("total_tokens"); - expect(vercelResponse.usage).toHaveProperty("prompt_tokens"); - expect(vercelResponse.usage).toHaveProperty("completion_tokens"); - expect(vercelResponse.usage).toHaveProperty("total_tokens"); - - delete process.env.USE_VERCEL_AI_SDK_ANTHROPIC; + expect(aiSdkResponse.usage).toHaveProperty("prompt_tokens"); + expect(aiSdkResponse.usage).toHaveProperty("completion_tokens"); + expect(aiSdkResponse.usage).toHaveProperty("total_tokens"); }); }); });