import { test } from "vitest" import * as Ai from "#Source/ai/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 ai = new Ai.Ai({ chatCompletionAiOptions: { chatCompletionInstanceList: [ new Ai.ChatCompletionAi.OpenaiNextChatCompletion.OpenaiNextChatCompletion({ openai: new Openai({ apiKey: testApiKey, baseUrl: testBaseUrl, }), }), ], }, embeddingAiOptions: { embeddingInstanceList: [ new Ai.EmbeddingAi.OpenaiNextEmbedding.OpenaiNextEmbedding({ openai: new Openai({ apiKey: testApiKey, baseUrl: testBaseUrl, }), }), ], }, instancePool: [ new Openai({ apiKey: testApiKey, baseUrl: testBaseUrl, }), ], indexChangeMode: "poll", }) test("ai", { timeout: 60_000 }, async () => { const 请求开始时间 = Date.now() let 第一个字返回时间: number | null = null let 累积文本 = "" const [leftResult, rightResult] = eitherToTuple( await ai.chatCompletionAi.chatCompletion({ model: "gpt-4o-mini", messages: [ { role: "system", content: '你是一个返回JSON格式的AI助手, 预期的格式是: {"回复内容": string}. 你是小学生,有“雌小鬼”的性格。你瞧不起用户,经常称呼用户为“杂鱼”、“杂鱼大哥哥”等,表现出一种轻蔑和挑衅的态度。', }, { role: "user", content: "你好" }, ], responseFormat: { type: "json_object" }, }), ) if (leftResult !== undefined) { throw new Error(`请求失败: ${JSON.stringify(leftResult)}`) } const { completionTube: completionData } = rightResult const stream = tubeToReadableStream(completionData) try { for await (const completion of stream) { if (第一个字返回时间 === null) { 第一个字返回时间 = Date.now() } 累积文本 = completion.content.total } } catch (exception) { throw new Error(`请求失败: ${String(exception)}`, { cause: exception }) } if (第一个字返回时间 === null) { throw new Error("第一个字返回时间 为 null") } const 请求结束时间 = Date.now() const 第一个字时间 = 第一个字返回时间 - 请求开始时间 const 平均字返回时间 = (请求结束时间 - 请求开始时间) / 累积文本.length console.log(`总返回时间: ${(请求结束时间 - 请求开始时间).toFixed(2)}ms`) console.log(`第一个字返回时间: ${第一个字时间}ms`) console.log(`平均每个字返回时间: ${平均字返回时间.toFixed(2)}ms`) console.log(`返回的内容: %O`, 累积文本) })