I've created a npm package that aims to make it easier to work with the openai tools api for assistants/chat in typescript: https://github.com/alvesvaren/zod-to-openai-tool
It's inspired by libraries such as tRPC, and allows the types to be fully inferred the whole way. It allows you to define zod schemas, that can then automatically be used to create a json schema to send as tools:
import OpenAI from "openai";
import { createInterface } from "readline";
import { createTools, t } from "../src";
import { z } from 'zod';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const { tools, processChatActions } = createTools({
getWeather: t.input(z.object({
city: z.string(),
date: z.coerce.date().default(() => new Date()).describe("The date for which to fetch the weather information, defaults to today")
.run(async ({ city, date }) => {
/* do stuff */ return { weather: weatherData }
}),
});
const messages: OpenAI.ChatCompletionMessageParam[] = [];
for await (const content of createInterface({ input: process.stdin })) {
messages.push({
role: "user",
content,
});
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo-1106",
messages,
tools,
});
const message = completion.choices[0].message;
messages.push(message);
if (message.tool_calls) {
const tool_outputs = await processChatActions(message.tool_calls);
messages.push(...tool_outputs);
const completion2 = await openai.chat.completions.create({
model: "gpt-3.5-turbo-1106",
messages,
tools,
});
messages.push(completion2.choices[0].message);
}
console.log(messages[messages.length - 1].content);
}
If anyone wants to try it out, it's published to NPM as zod-to-openai-tool