import { expect, test } from "vitest" import { streamConsumeInMacroTask } from "#Source/basic/index.ts" import { Openai } from "#Source/openai/index.ts" import { eitherToTuple } from "#Source/result/index.ts" import { tubeToReadableStream } from "#Source/tube/index.ts" const testApiKey = "sk-DLj8aHvKjvHfZ7IHA2F07c968c3d4aE491C1525e40E24932" const testBaseUrl = "https://cn.api.openai-next.com/v1/" const openai = new Openai({ apiKey: testApiKey, baseUrl: testBaseUrl, }) test("customEmbedding ", { timeout: 60_000 }, async () => { const embedding = await openai.customEmbedding({ input: "床前明月光,疑是地上霜。举头望明月,低头思故乡。", }) const [left, right] = eitherToTuple(embedding) if (left !== undefined) { throw new Error(`请求失败: ${JSON.stringify(left)}`) } const resultLength = right.embedding.length expect(resultLength).toBe(1_536) }) test("customChatCompletion ", { timeout: 60_000 }, async () => { const nonStreamingResult = await openai.customChatCompletionNonStreaming({ model: "gpt-4o-mini", messages: [ { role: "system", content: "你是讲故事大王。" }, { role: "user", content: "讲一个小红帽吃掉大灰狼的故事。" }, ], }) const [left, right] = eitherToTuple(nonStreamingResult) if (left !== undefined) { throw new Error(`请求失败: ${JSON.stringify(left)}`) } const contentLength = right.content.length expect(contentLength).toBeGreaterThan(0) }) test("customChatCompletionStreaming ", { timeout: 60_000 }, async () => { const [left, right] = eitherToTuple( await openai.customChatCompletionStreaming({ model: "gpt-4o-mini", messages: [ { role: "system", content: "你是讲故事大王。" }, { role: "user", content: "讲一个小红帽吃掉大灰狼的故事。" }, ], }), ) if (left !== undefined) { throw new Error(`请求失败: ${JSON.stringify(left)}`) } else { const stream = tubeToReadableStream(right.completionTube) streamConsumeInMacroTask({ readableStream: stream, onValue: (chunk) => { console.log(JSON.stringify(chunk.content.total, null, 2)) // process.stdout.write() }, }) } })