remove feature flagged USE_VERCEL_AI_SDK

This commit is contained in:
uinstinct 2026-02-18 18:36:08 +05:30
parent 8eee3e0300
commit 811bb12d09
3 changed files with 6 additions and 570 deletions

View file

@ -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<ChatCompletion> {
// 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<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"
);
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<ChatCompletionChunk> {
// 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<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");
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<string, string> {
const enableCaching = this.config?.cachingStrategy !== "none";
return getAnthropicHeaders(this.config.apiKey, enableCaching, this.apiBase);

View file

@ -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<typeof OpenAIConfigSchema>) {
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<T extends ChatCompletionCreateParams>(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<ChatCompletion> {
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<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 { 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<ChatCompletionChunk, any, unknown> {
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<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 { 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,

View file

@ -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", () => {});
}