openai-node
66 строк · 1.8 Кб
1import 'openai/shims/node.mjs';
2import OpenAI from 'openai';
3import { distance } from 'fastest-levenshtein';
4import { ChatCompletion } from 'openai/resources/chat/completions';
5import * as shims from 'openai/_shims/index';
6
7// The tests in this file don't typecheck with "moduleResolution": "node"
8
9function typeTests(x: shims.Request) {
10const url: string = x.url;
11}
12
13const client = new OpenAI();
14
15declare global {
16namespace jest {
17interface Matchers<R> {
18toBeSimilarTo(comparedTo: string, expectedDistance: number): R;
19}
20}
21}
22expect.extend({
23toBeSimilarTo(received, comparedTo: string, expectedDistance: number) {
24const message = () =>
25[
26`Received: ${JSON.stringify(received)}`,
27`Expected: ${JSON.stringify(comparedTo)}`,
28`Expected distance: ${expectedDistance}`,
29`Received distance: ${actualDistance}`,
30].join('\n');
31
32const actualDistance = distance(received, comparedTo);
33if (actualDistance < expectedDistance) {
34return {
35message,
36pass: true,
37};
38}
39
40return {
41message,
42pass: false,
43};
44},
45});
46
47it(`raw response`, async function () {
48const response = await client.chat.completions
49.create({
50model: 'gpt-4',
51messages: [{ role: 'user', content: 'Say this is a test' }],
52})
53.asResponse();
54
55// test that we can use node-fetch Response API
56const chunks: string[] = [];
57const { body } = response;
58if (!body) throw new Error(`expected response.body to be defined`);
59body.on('data', (chunk) => chunks.push(chunk));
60await new Promise<void>((resolve, reject) => {
61body.once('end', resolve);
62body.once('error', reject);
63});
64const json: ChatCompletion = JSON.parse(chunks.join(''));
65expect(json.choices[0]?.message.content || '').toBeSimilarTo('This is a test', 10);
66});
67