openai-node
144 строки · 5.6 Кб
1#!/usr/bin/env -S npm run tsn -T
2
3import OpenAI from 'openai';4import { RunnableToolFunctionWithParse } from 'openai/lib/RunnableFunction';5import { JSONSchema } from 'openai/lib/jsonschema';6import { ZodSchema, z } from 'zod';7import { zodToJsonSchema } from 'zod-to-json-schema';8
9// gets API Key from environment variable OPENAI_API_KEY
10const openai = new OpenAI();11
12// Define your functions, alongside zod schemas.
13
14const ListParams = z.object({15genre: z.enum(['mystery', 'nonfiction', 'memoir', 'romance', 'historical']),16});17type ListParams = z.infer<typeof ListParams>;18async function listBooks({ genre }: ListParams) {19return db.filter((item) => item.genre === genre).map((item) => ({ name: item.name, id: item.id }));20}
21
22const SearchParams = z.object({23name: z.string(),24});25type SearchParams = z.infer<typeof SearchParams>;26async function searchBooks({ name }: SearchParams) {27return db.filter((item) => item.name.includes(name)).map((item) => ({ name: item.name, id: item.id }));28}
29
30const GetParams = z.object({31id: z.string(),32});33type GetParams = z.infer<typeof GetParams>;34async function getBook({ id }: GetParams) {35return db.find((item) => item.id === id)!;36}
37
38async function main() {39const runner = await openai.beta.chat.completions40.runTools({41model: 'gpt-4-1106-preview',42stream: true,43tools: [44zodFunction({45function: listBooks,46schema: ListParams,47description: 'List queries books by genre, and returns a list of names of books',48}),49zodFunction({50function: searchBooks,51schema: SearchParams,52description: 'Search queries books by their name and returns a list of book names and their ids',53}),54zodFunction({55function: getBook,56schema: GetParams,57description:58"Get returns a book's detailed information based on the id of the book. Note that this does not accept names, and only IDs, which you can get by using search.",59}),60],61messages: [62{63role: 'system',64content:65'Please use our book database, which you can access using functions to answer the following questions.',66},67{68role: 'user',69content:70'I really enjoyed reading To Kill a Mockingbird, could you recommend me a book that is similar and tell me why?',71},72],73})74.on('message', (msg) => console.log('msg', msg))75.on('functionCall', (functionCall) => console.log('functionCall', functionCall))76.on('functionCallResult', (functionCallResult) => console.log('functionCallResult', functionCallResult))77.on('content', (diff) => process.stdout.write(diff));78
79const result = await runner.finalChatCompletion();80console.log();81console.log('messages');82console.log(runner.messages);83
84console.log();85console.log('final chat completion');86console.dir(result, { depth: null });87}
88
89const db = [90{91id: 'a1',92name: 'To Kill a Mockingbird',93genre: 'historical',94description: `Compassionate, dramatic, and deeply moving, "To Kill A Mockingbird" takes readers to the roots of human behavior - to innocence and experience, kindness and cruelty, love and hatred, humor and pathos. Now with over 18 million copies in print and translated into forty languages, this regional story by a young Alabama woman claims universal appeal. Harper Lee always considered her book to be a simple love story. Today it is regarded as a masterpiece of American literature.`,95},96{97id: 'a2',98name: 'All the Light We Cannot See',99genre: 'historical',100description: `In a mining town in Germany, Werner Pfennig, an orphan, grows up with his younger sister, enchanted by a crude radio they find that brings them news and stories from places they have never seen or imagined. Werner becomes an expert at building and fixing these crucial new instruments and is enlisted to use his talent to track down the resistance. Deftly interweaving the lives of Marie-Laure and Werner, Doerr illuminates the ways, against all odds, people try to be good to one another.`,101},102{103id: 'a3',104name: 'Where the Crawdads Sing',105genre: 'historical',106description: `For years, rumors of the “Marsh Girl” haunted Barkley Cove, a quiet fishing village. Kya Clark is barefoot and wild; unfit for polite society. So in late 1969, when the popular Chase Andrews is found dead, locals immediately suspect her.107But Kya is not what they say. A born naturalist with just one day of school, she takes life's lessons from the land, learning the real ways of the world from the dishonest signals of fireflies. But while she has the skills to live in solitude forever, the time comes when she yearns to be touched and loved. Drawn to two young men from town, who are each intrigued by her wild beauty, Kya opens herself to a new and startling world—until the unthinkable happens.`,108},109];110
111/**
112* A generic utility function that returns a RunnableFunction
113* you can pass to `.runTools()`,
114* with a fully validated, typesafe parameters schema.
115*
116* You are encouraged to copy/paste this into your codebase!
117*/
118function zodFunction<T extends object>({119function: fn,120schema,121description = '',122name,123}: {124function: (args: T) => Promise<object>;125schema: ZodSchema<T>;126description?: string;127name?: string;128}): RunnableToolFunctionWithParse<T> {129return {130type: 'function',131function: {132function: fn,133name: name ?? fn.name,134description: description,135parameters: zodToJsonSchema(schema) as JSONSchema,136parse(input: string): T {137const obj = JSON.parse(input);138return schema.parse(obj);139},140},141};142}
143
144main();145