|
| 1 | +import OpenAI, { toFile } from 'openai'; |
| 2 | +import { distance } from 'fastest-levenshtein'; |
| 3 | +import { test, expect } from 'bun:test'; |
| 4 | + |
| 5 | +const client = new OpenAI(); |
| 6 | + |
| 7 | +function expectSimilar(received: any, comparedTo: string, expectedDistance: number) { |
| 8 | + const message = () => |
| 9 | + [ |
| 10 | + `Received: ${JSON.stringify(received)}`, |
| 11 | + `Expected: ${JSON.stringify(comparedTo)}`, |
| 12 | + `Expected distance: ${expectedDistance}`, |
| 13 | + `Received distance: ${actualDistance}`, |
| 14 | + ].join('\n'); |
| 15 | + |
| 16 | + const actualDistance = distance(received, comparedTo); |
| 17 | + expect(actualDistance).toBeLessThan(expectedDistance); |
| 18 | +} |
| 19 | + |
| 20 | +test(`basic request works`, async function () { |
| 21 | + const completion = await client.chat.completions.create({ |
| 22 | + model: 'gpt-4', |
| 23 | + messages: [{ role: 'user', content: 'Say this is a test' }], |
| 24 | + }); |
| 25 | + expectSimilar(completion.choices[0]?.message?.content, 'This is a test', 10); |
| 26 | +}); |
| 27 | + |
| 28 | +test(`streaming works`, async function () { |
| 29 | + const stream = await client.chat.completions.create({ |
| 30 | + model: 'gpt-4', |
| 31 | + messages: [{ role: 'user', content: 'Say this is a test' }], |
| 32 | + stream: true, |
| 33 | + }); |
| 34 | + const chunks = []; |
| 35 | + for await (const part of stream) { |
| 36 | + chunks.push(part); |
| 37 | + } |
| 38 | + expectSimilar(chunks.map((c) => c.choices[0]?.delta.content || '').join(''), 'This is a test', 10); |
| 39 | +}); |
| 40 | + |
| 41 | +test(`toFile rejects`, async function () { |
| 42 | + try { |
| 43 | + await toFile(new TextEncoder().encode('foo'), 'foo.txt'); |
| 44 | + throw new Error(`expected toFile to reject`); |
| 45 | + } catch (error) { |
| 46 | + expect((error as any).message).toEqual(`file uploads aren't supported in this environment yet`); |
| 47 | + } |
| 48 | +}); |
0 commit comments