openai-node

Форк
0
/
function-call.ts 
142 строки · 5.1 Кб
1
#!/usr/bin/env -S npm run tsn -T
2

3
import OpenAI from 'openai';
4
import { ChatCompletionMessage, ChatCompletionMessageParam } from 'openai/resources/chat';
5

6
// gets API Key from environment variable OPENAI_API_KEY
7
const openai = new OpenAI();
8

9
const functions: OpenAI.Chat.ChatCompletionCreateParams.Function[] = [
10
  {
11
    name: 'list',
12
    description: 'list queries books by genre, and returns a list of names of books',
13
    parameters: {
14
      type: 'object',
15
      properties: {
16
        genre: { type: 'string', enum: ['mystery', 'nonfiction', 'memoir', 'romance', 'historical'] },
17
      },
18
    },
19
  },
20
  {
21
    name: 'search',
22
    description: 'search queries books by their name and returns a list of book names and their ids',
23
    parameters: {
24
      type: 'object',
25
      properties: {
26
        name: { type: 'string' },
27
      },
28
    },
29
  },
30
  {
31
    name: 'get',
32
    description:
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.",
34
    parameters: {
35
      type: 'object',
36
      properties: {
37
        id: { type: 'string' },
38
      },
39
    },
40
  },
41
];
42

43
async function callFunction(function_call: ChatCompletionMessage.FunctionCall): Promise<any> {
44
  const args = JSON.parse(function_call.arguments!);
45
  switch (function_call.name) {
46
    case 'list':
47
      return await list(args['genre']);
48

49
    case 'search':
50
      return await search(args['name']);
51

52
    case 'get':
53
      return await get(args['id']);
54

55
    default:
56
      throw new Error('No function found');
57
  }
58
}
59

60
async function main() {
61
  const messages: ChatCompletionMessageParam[] = [
62
    {
63
      role: 'system',
64
      content:
65
        'Please use our book database, which you can access using functions to answer the following questions.',
66
    },
67
    {
68
      role: 'user',
69
      content:
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
  console.log(messages[0]);
74
  console.log(messages[1]);
75
  console.log();
76

77
  while (true) {
78
    const completion = await openai.chat.completions.create({
79
      model: 'gpt-3.5-turbo',
80
      messages,
81
      functions: functions,
82
    });
83

84
    const message = completion.choices[0]!.message;
85
    messages.push(message);
86
    console.log(message);
87

88
    // If there is no function call, we're done and can exit this loop
89
    if (!message.function_call) {
90
      return;
91
    }
92

93
    // If there is a function call, we generate a new message with the role 'function'.
94
    const result = await callFunction(message.function_call);
95
    const newMessage = {
96
      role: 'function' as const,
97
      name: message.function_call.name!,
98
      content: JSON.stringify(result),
99
    };
100
    messages.push(newMessage);
101

102
    console.log(newMessage);
103
    console.log();
104
  }
105
}
106

107
const db = [
108
  {
109
    id: 'a1',
110
    name: 'To Kill a Mockingbird',
111
    genre: 'historical',
112
    description: `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
  {
115
    id: 'a2',
116
    name: 'All the Light We Cannot See',
117
    genre: 'historical',
118
    description: `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
  {
121
    id: 'a3',
122
    name: 'Where the Crawdads Sing',
123
    genre: 'historical',
124
    description: `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

126
But 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

130
async function list(genre: string) {
131
  return db.filter((item) => item.genre === genre).map((item) => ({ name: item.name, id: item.id }));
132
}
133

134
async function search(name: string) {
135
  return db.filter((item) => item.name.includes(name)).map((item) => ({ name: item.name, id: item.id }));
136
}
137

138
async function get(id: string) {
139
  return db.find((item) => item.id === id)!;
140
}
141

142
main();
143

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.