Skip to content

Instantly share code, notes, and snippets.

@mkanenobu
Last active July 21, 2023 01:37
Show Gist options
  • Save mkanenobu/424ccd3223f751d3f0353346528edc60 to your computer and use it in GitHub Desktop.
Save mkanenobu/424ccd3223f751d3f0353346528edc60 to your computer and use it in GitHub Desktop.
import type { ZodObject, ZodRawShape } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
/**
* zod と zod-to-json-schema を使って型安全に completion 結果を得るコード
*/
export const createChatCompletionWithFunction = async <T extends ZodRawShape>(
messages: ChatCompletionRequestMessage[],
functionName: string,
schema: ZodObject<T>
) => {
const configuration = new Configuration({
apiKey: process.env.API_KEY,
});
const openaiClient = new OpenAIApi(configuration);
const fn: ChatCompletionFunctions = {
name: functionName,
parameters: zodToJsonSchema(schema),
};
const result = await openaiClient.createChatCompletion({
model: "gpt-4-0613",
messages,
functions: [fn],
});
const functionCallArguments =
result?.data.choices.at(0)?.message?.function_call?.arguments;
if (!functionCallArguments) {
throw new Error(
"Failed to chat completion, function call arguments is not found"
);
}
return await schema.parseAsync(JSON.parse(functionCallArguments));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment