50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
import { useContextKey } from '@kevisual/use-config/context';
|
|
import { ProviderManager } from '@kevisual/ai';
|
|
import { App } from '@kevisual/router';
|
|
import { assistantConfig } from '@/app.ts';
|
|
import { Query } from '@kevisual/query';
|
|
const app = useContextKey<App>('app');
|
|
const query = useContextKey<Query>('assistantQuery');
|
|
|
|
app
|
|
.route({
|
|
path: 'ai',
|
|
key: 'chat',
|
|
description: '与 AI 进行对话, 调用 GPT 的AI 服务,生成结果,并返回。',
|
|
middleware: ['auth-admin'],
|
|
metadata: {
|
|
admin: true,
|
|
}
|
|
})
|
|
.define(async (ctx) => {
|
|
const { messages = [], username, group, question, chatOpts = {} } = ctx.query;
|
|
if (messages.length === 0 && question) {
|
|
messages.push({
|
|
role: 'user',
|
|
content: question,
|
|
});
|
|
} else {
|
|
ctx.throw(4001, 'messages or question is required');
|
|
}
|
|
|
|
const as = assistantConfig.getCacheAssistantConfig();
|
|
const { provider, apiKey, model } = as.ai || {};
|
|
if (!provider) {
|
|
const response = await query.post(ctx.query);
|
|
if (response.code === 200) {
|
|
ctx.body = response.data;
|
|
return;
|
|
} else {
|
|
return ctx.throw(response.code, response.message);
|
|
}
|
|
}
|
|
const pm = new ProviderManager({
|
|
provider: provider,
|
|
apiKey: apiKey,
|
|
model: model,
|
|
});
|
|
const result = await pm.provider.chat(messages, chatOpts);
|
|
ctx.body = result;
|
|
})
|
|
.addTo(app);
|