File size: 4,016 Bytes
6e73b5d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
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}`);
}
};
|