import { readBody, HTTPError } from 'h3'; import { DustClient } from '../dust-client.js'; /** * OpenAI 兼容的聊天完成接口 */ export const chatCompletions = async (event) => { try { const body = await readBody(event); // 验证请求体 if (!body.messages || !Array.isArray(body.messages)) { throw new HTTPError(400, 'Invalid request: messages array is required'); } if (body.messages.length === 0) { throw new HTTPError(400, 'Invalid request: messages array cannot be empty'); } // 创建 Dust 客户端 const dustClient = new DustClient( process.env.WORKSPACE_ID, event.context.apiKey || process.env.DUST_API_KEY ); // 处理流式响应 if (body.stream === true) { return handleStreamingResponse(event, dustClient, body); } // 处理普通响应 const result = await dustClient.chatCompletion(body); return result; } catch (error) { console.error('Chat completion error:', error); if (error instanceof HTTPError) { throw error; } throw new HTTPError(500, `Internal server error: ${error.message}`); } }; /** * 处理流式响应 */ async function handleStreamingResponse(event, dustClient, body) { // 设置响应头 event.res.headers.set('Content-Type', 'text/event-stream'); event.res.headers.set('Cache-Control', 'no-cache'); event.res.headers.set('Connection', 'keep-alive'); // 直接让 DustClient 返回流式响应,不要在这里重复处理 return await dustClient.chatCompletion({ ...body, stream: true }); } /** * OpenAI 兼容的模型列表接口 * 返回所有可用的 Dust agents 作为模型 */ export const listModels = async (event) => { try { // 创建 Dust 客户端 const dustClient = new DustClient( process.env.WORKSPACE_ID, event.context.apiKey || process.env.DUST_API_KEY ); // 获取所有可用的模型(agents) const models = await dustClient.getModels(); return models; } catch (error) { console.error('Failed to get models:', error); // 返回默认模型作为后备 return { object: "list", data: [ { id: "dust", object: "model", created: Math.floor(Date.now() / 1000), owned_by: "dust", permission: [], root: "dust", parent: null, name: "Default Dust Assistant", description: "Default Dust assistant agent" } ] }; } }; /** * 获取特定模型信息 * 使用直接的 agent 配置 API */ export const getModel = async (event) => { try { const modelId = event.context.params?.model || 'dust'; // 创建 Dust 客户端 const dustClient = new DustClient( process.env.WORKSPACE_ID, event.context.apiKey || process.env.DUST_API_KEY ); // 首先尝试直接获取 agent 配置 let agent; try { agent = await dustClient.getAgentConfiguration(modelId); } catch (error) { // 如果直接获取失败,使用 findAgent 方法 agent = await dustClient.findAgent(modelId); } if (!agent) { throw new HTTPError(404, `Model '${modelId}' not found`); } // 转换为 OpenAI 模型格式 return { id: agent.sId, object: "model", created: agent.versionCreatedAt ? Math.floor(new Date(agent.versionCreatedAt).getTime() / 1000) : Math.floor(Date.now() / 1000), owned_by: "dust", permission: [], root: agent.sId, parent: null, name: agent.name, description: agent.description, scope: agent.scope, model: agent.model, actions: agent.actions?.length || 0, maxStepsPerRun: agent.maxStepsPerRun, visualizationEnabled: agent.visualizationEnabled }; } catch (error) { console.error('Failed to get model:', error); if (error instanceof HTTPError) { throw error; } throw new HTTPError(500, `Failed to get model: ${error.message}`); } };