-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Tool Calling using Vercel's AI SDK not working as intended #2864
Comments
I'm not well versed in Rust, but I'll try to aggregate the code issues and perhaps try to fix them when I find the time. (Some) Problematic lines:
|
I think I got it mostly working with a few request and response overrides: import { getStopTokens } from "@/util";
import { createOpenAI } from "@ai-sdk/openai";
import { generateObject, generateText, streamObject, streamText, tool } from "ai";
import { z } from "zod";
function getRuntime() {
const modelName = process.env.MODEL_NAME!;
const authToken = process.env.OPENAI_API_KEY!;
const openai = createOpenAI({
baseURL: process.env.OPENAI_BASE_URL!,
apiKey: authToken,
compatibility: "strict",
fetch: async (url, options) => {
const requestBody = JSON.parse(options!.body! as string);
if (requestBody.response_format && requestBody.response_format.type === "json_schema") {
requestBody.response_format.type = "json";
requestBody.response_format.value = requestBody.response_format.json_schema.schema;
delete requestBody.response_format.json_schema;
}
const response = await fetch(url, {
...options,
body: JSON.stringify({
stop: getStopTokens(modelName),
...requestBody,
}),
});
const contentType = response.headers.get("content-type");
if (response.ok && contentType?.includes("application/json")) {
const responseBody = await response.json();
const choices = responseBody.choices.map((choice: any) => {
if (choice.message?.tool_calls) {
choice.message.tool_calls = choice.message.tool_calls.map((toolCall: any) => {
return {
...toolCall,
arguments: JSON.stringify(toolCall.function.arguments),
function: {
...toolCall.function,
arguments: JSON.stringify(toolCall.function.arguments),
},
};
});
return {
...choice,
message: {
...choice.message,
tool_calls: choice.message.tool_calls,
},
};
} else {
return choice;
}
});
return new Response(JSON.stringify({ ...responseBody, choices }), {
status: response.status,
headers: response.headers,
});
}
return response;
},
});
return openai.chat(modelName, { structuredOutputs: true });
}
async function main() {
await test("generateText", testGenerateText);
await test("streamText", testStreamText);
await test("generateObject", testGenerateObject);
await test("streamObject", testStreamObject);
await test("toolCall", testToolCall);
}
main().catch(console.error);
async function test(what: string, call: () => Promise<void>) {
console.log(`${what}...`);
try {
await call();
console.log("✅", what);
} catch (error) {
console.error("❌", what, error);
console.log();
}
}
async function testGenerateText() {
const model = getRuntime();
const response = await generateText({
model,
system: "You are a helpful assistant.",
prompt: "What is the capital of Germany?",
});
console.log(response.text);
}
async function testStreamText() {
const model = getRuntime();
const stream = await streamText({
model,
system: "You are a helpful assistant.",
prompt: "What is the capital of Germany?",
});
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
}
async function testGenerateObject() {
const model = getRuntime();
const response = await generateObject({
model,
schema: z.object({
text: z.string(),
}),
system: "You are a helpful assistant.",
prompt: "What is the capital of Germany?",
});
console.log(response.object);
}
async function testStreamObject() {
const model = getRuntime();
const stream = await streamObject({
model,
schema: z.object({ text: z.string() }),
system: "You are a helpful assistant.",
prompt: "What is the capital of Germany?",
});
for await (const chunk of stream.partialObjectStream) {
// ...
}
console.log(await stream.object);
}
async function testToolCall() {
const model = getRuntime();
const response = await generateText({
model,
system:
"You are a helpful assistant. You have a tool to get the capital of a country. Return the result of the tool call.",
prompt: "What is the capital of Germany?",
tools: {
getCapital: tool({
parameters: z.object({
country: z.string(),
}),
execute: async ({ country }) => {
return country === "Germany" ? "Berlin" : "Unknown";
},
}),
},
});
console.log(response.text || response.toolResults.find((r) => r.toolName === "getCapital")?.result);
} Note the rewriting of the requests function calls and the responses Also note, that unlike other inference framework, at the end of the tool calls there will be no text generated. But perhaps that's an issue on my end. |
System Info
/info
Output:Information
Tasks
Reproduction
npm i ai @ai-sdk/openai zod
Tool Calls
node repro_generate.js
):This will result in an error from Vercels AI SDK:
For this issue, there's a simple workaround of rewriting the response and stringifying the function arguments:
Tool Streaming
node repro_stream.js
):This will result in an error from Vercels AI SDK:
Edit: There's another one, the client sometimes sends
response_format
withoutvalue
property:which results in the following error:
Failed to deserialize the JSON body into the target type: response_format: missing field
valueat line 1 column 126
.Expected behavior
Being able to call tools/generate objects using the OpenAI compatible clients like Vercels AI SDK.
The text was updated successfully, but these errors were encountered: