openai-node
142 строки · 5.1 Кб
1#!/usr/bin/env -S npm run tsn -T
2
3import OpenAI from 'openai';4import { ChatCompletionMessage, ChatCompletionMessageParam } from 'openai/resources/chat';5
6// gets API Key from environment variable OPENAI_API_KEY
7const openai = new OpenAI();8
9const functions: OpenAI.Chat.ChatCompletionCreateParams.Function[] = [10{11name: 'list',12description: 'list queries books by genre, and returns a list of names of books',13parameters: {14type: 'object',15properties: {16genre: { type: 'string', enum: ['mystery', 'nonfiction', 'memoir', 'romance', 'historical'] },17},18},19},20{21name: 'search',22description: 'search queries books by their name and returns a list of book names and their ids',23parameters: {24type: 'object',25properties: {26name: { type: 'string' },27},28},29},30{31name: 'get',32description:33"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.",34parameters: {35type: 'object',36properties: {37id: { type: 'string' },38},39},40},41];42
43async function callFunction(function_call: ChatCompletionMessage.FunctionCall): Promise<any> {44const args = JSON.parse(function_call.arguments!);45switch (function_call.name) {46case 'list':47return await list(args['genre']);48
49case 'search':50return await search(args['name']);51
52case 'get':53return await get(args['id']);54
55default:56throw new Error('No function found');57}58}
59
60async function main() {61const messages: ChatCompletionMessageParam[] = [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];73console.log(messages[0]);74console.log(messages[1]);75console.log();76
77while (true) {78const completion = await openai.chat.completions.create({79model: 'gpt-3.5-turbo',80messages,81functions: functions,82});83
84const message = completion.choices[0]!.message;85messages.push(message);86console.log(message);87
88// If there is no function call, we're done and can exit this loop89if (!message.function_call) {90return;91}92
93// If there is a function call, we generate a new message with the role 'function'.94const result = await callFunction(message.function_call);95const newMessage = {96role: 'function' as const,97name: message.function_call.name!,98content: JSON.stringify(result),99};100messages.push(newMessage);101
102console.log(newMessage);103console.log();104}105}
106
107const db = [108{109id: 'a1',110name: 'To Kill a Mockingbird',111genre: 'historical',112description: `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.`,113},114{115id: 'a2',116name: 'All the Light We Cannot See',117genre: 'historical',118description: `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.`,119},120{121id: 'a3',122name: 'Where the Crawdads Sing',123genre: 'historical',124description: `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.125
126But 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.`,127},128];129
130async function list(genre: string) {131return db.filter((item) => item.genre === genre).map((item) => ({ name: item.name, id: item.id }));132}
133
134async function search(name: string) {135return db.filter((item) => item.name.includes(name)).map((item) => ({ name: item.name, id: item.id }));136}
137
138async function get(id: string) {139return db.find((item) => item.id === id)!;140}
141
142main();143