openai-node

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

3
import OpenAI from 'openai';
4
import { ZodSchema, z } from 'zod';
5
import { zodToJsonSchema } from 'zod-to-json-schema';
6

7
const openai = new OpenAI();
8

9
const ListParams = z.object({
10
  genre: z.enum(['mystery', 'nonfiction', 'memoir', 'romance', 'historical']),
11
});
12

13
const SearchParams = z.object({
14
  name: z.string(),
15
});
16

17
const GetParams = z.object({
18
  id: z.string(),
19
});
20

21
const functions = [
22
  {
23
    name: 'list',
24
    description: 'list queries books by genre, and returns a list of names of books',
25
    parameters: zodToJsonSchema(ListParams),
26
    parse: zodParseJSON(ListParams),
27
    function: list,
28
  },
29
  {
30
    name: 'search',
31
    description: 'search queries books by their name and returns a list of book names and their ids',
32
    parameters: zodToJsonSchema(SearchParams),
33
    parse: zodParseJSON(SearchParams),
34
    function: search,
35
  },
36
  {
37
    name: 'get',
38
    description:
39
      "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.",
40
    parameters: zodToJsonSchema(GetParams),
41
    parse: zodParseJSON(GetParams),
42
    function: get,
43
  },
44
] as const;
45

46
async function main() {
47
  const runner = await openai.beta.chat.completions
48
    .runFunctions({
49
      model: 'gpt-3.5-turbo',
50
      messages: [
51
        {
52
          role: 'system',
53
          content:
54
            'Please use our book database, which you can access using functions to answer the following questions.',
55
        },
56
        {
57
          role: 'user',
58
          content:
59
            'I really enjoyed reading To Kill a Mockingbird, could you recommend me a book that is similar and tell me why?',
60
        },
61
      ],
62
      functions,
63
    })
64
    .on('message', (msg) => console.log(msg))
65
    .on('content', (diff) => process.stdout.write(diff));
66

67
  const result = await runner.finalChatCompletion();
68
  console.log(result);
69

70
  console.log();
71
  console.log(runner.messages);
72
}
73

74
const db = [
75
  {
76
    id: 'a1',
77
    name: 'To Kill a Mockingbird',
78
    genre: 'historical',
79
    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.`,
80
  },
81
  {
82
    id: 'a2',
83
    name: 'All the Light We Cannot See',
84
    genre: 'historical',
85
    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.`,
86
  },
87
  {
88
    id: 'a3',
89
    name: 'Where the Crawdads Sing',
90
    genre: 'historical',
91
    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.
92
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.`,
93
  },
94
];
95

96
async function list({ genre }: z.infer<typeof ListParams>) {
97
  return db.filter((item) => item.genre === genre).map((item) => ({ name: item.name, id: item.id }));
98
}
99

100
async function search({ name }: z.infer<typeof SearchParams>) {
101
  return db.filter((item) => item.name.includes(name)).map((item) => ({ name: item.name, id: item.id }));
102
}
103

104
async function get({ id }: z.infer<typeof GetParams>) {
105
  return db.find((item) => item.id === id)!;
106
}
107

108
function zodParseJSON<T>(schema: ZodSchema<T>) {
109
  return (input: string): T => schema.parse(JSON.parse(input));
110
}
111

112
main();
113

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

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

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

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