openai-node

Форк
0
66 строк · 1.8 Кб
1
import 'openai/shims/node.mjs';
2
import OpenAI from 'openai';
3
import { distance } from 'fastest-levenshtein';
4
import { ChatCompletion } from 'openai/resources/chat/completions';
5
import * as shims from 'openai/_shims/index';
6

7
// The tests in this file don't typecheck with "moduleResolution": "node"
8

9
function typeTests(x: shims.Request) {
10
  const url: string = x.url;
11
}
12

13
const client = new OpenAI();
14

15
declare global {
16
  namespace jest {
17
    interface Matchers<R> {
18
      toBeSimilarTo(comparedTo: string, expectedDistance: number): R;
19
    }
20
  }
21
}
22
expect.extend({
23
  toBeSimilarTo(received, comparedTo: string, expectedDistance: number) {
24
    const message = () =>
25
      [
26
        `Received: ${JSON.stringify(received)}`,
27
        `Expected: ${JSON.stringify(comparedTo)}`,
28
        `Expected distance: ${expectedDistance}`,
29
        `Received distance: ${actualDistance}`,
30
      ].join('\n');
31

32
    const actualDistance = distance(received, comparedTo);
33
    if (actualDistance < expectedDistance) {
34
      return {
35
        message,
36
        pass: true,
37
      };
38
    }
39

40
    return {
41
      message,
42
      pass: false,
43
    };
44
  },
45
});
46

47
it(`raw response`, async function () {
48
  const response = await client.chat.completions
49
    .create({
50
      model: 'gpt-4',
51
      messages: [{ role: 'user', content: 'Say this is a test' }],
52
    })
53
    .asResponse();
54

55
  // test that we can use node-fetch Response API
56
  const chunks: string[] = [];
57
  const { body } = response;
58
  if (!body) throw new Error(`expected response.body to be defined`);
59
  body.on('data', (chunk) => chunks.push(chunk));
60
  await new Promise<void>((resolve, reject) => {
61
    body.once('end', resolve);
62
    body.once('error', reject);
63
  });
64
  const json: ChatCompletion = JSON.parse(chunks.join(''));
65
  expect(json.choices[0]?.message.content || '').toBeSimilarTo('This is a test', 10);
66
});
67

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

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

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

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