221 行
7.2 KiB
TypeScript
221 行
7.2 KiB
TypeScript
import * as fs from 'fs';
|
|
import * as path from 'path';
|
|
import { CONTROLLER_KEY, getClassMetadata } from '@midwayjs/core';
|
|
import { BaseController, CoolCommException, CurdOption } from '@cool-midway/core';
|
|
import { AiChatService } from '../../../src/modules/ai/service/chat';
|
|
import {
|
|
OpenAiChatController,
|
|
openAiChatCurdOption,
|
|
} from '../../../src/modules/ai/controller/open/chat';
|
|
import { AiChatRequest } from '../../../src/comm/types/omni';
|
|
|
|
/**
|
|
* CoolController 元数据(脚本路径解析为异步)
|
|
*/
|
|
interface CoolControllerMeta {
|
|
prefix?: string;
|
|
curdOption?: CurdOption;
|
|
}
|
|
|
|
/**
|
|
* 等待 CoolController 将 CRUD 配置写入类元数据
|
|
*/
|
|
async function waitCoolMeta(
|
|
target: new (...args: never[]) => unknown
|
|
): Promise<CoolControllerMeta> {
|
|
const started = Date.now();
|
|
while (Date.now() - started < 2000) {
|
|
const meta = getClassMetadata(CONTROLLER_KEY, target) as
|
|
| CoolControllerMeta
|
|
| undefined;
|
|
if (meta?.curdOption) {
|
|
return meta;
|
|
}
|
|
await new Promise<void>(resolve => setImmediate(resolve));
|
|
}
|
|
throw new Error(`${target.name} 的 CoolController 元数据未就绪`);
|
|
}
|
|
|
|
function serviceApiMethods(apis: CurdOption['serviceApis'] = []): string[] {
|
|
return apis.map(api => (typeof api === 'string' ? api : api.method));
|
|
}
|
|
|
|
function userAsk(
|
|
content: string,
|
|
extra?: Partial<AiChatRequest>
|
|
): AiChatRequest {
|
|
return {
|
|
cardId: extra?.cardId ?? 101,
|
|
locale: extra?.locale,
|
|
messages: extra?.messages ?? [{ role: 'user', content }],
|
|
};
|
|
}
|
|
|
|
describe('T36: 名片 AI 顾问对话 (modules/ai chat)', () => {
|
|
describe('1. AiChatService.ask 入参校验', () => {
|
|
let service: AiChatService;
|
|
|
|
beforeEach(() => {
|
|
service = new AiChatService();
|
|
});
|
|
|
|
it('缺 cardId 应抛 CoolCommException', async () => {
|
|
await expect(
|
|
service.ask({
|
|
cardId: '' as unknown as number,
|
|
messages: [{ role: 'user', content: 'hello' }],
|
|
})
|
|
).rejects.toThrow(CoolCommException);
|
|
|
|
await expect(
|
|
service.ask({
|
|
messages: [{ role: 'user', content: 'hello' }],
|
|
} as AiChatRequest)
|
|
).rejects.toThrow(CoolCommException);
|
|
});
|
|
|
|
it('空 messages 应抛 CoolCommException', async () => {
|
|
await expect(
|
|
service.ask({ cardId: 101, messages: [] })
|
|
).rejects.toThrow(CoolCommException);
|
|
|
|
await expect(
|
|
service.ask({ cardId: 101, messages: undefined as unknown as [] })
|
|
).rejects.toThrow(CoolCommException);
|
|
});
|
|
|
|
it('最后一条非 user 或内容为空应抛 CoolCommException', async () => {
|
|
await expect(
|
|
service.ask({
|
|
cardId: 101,
|
|
messages: [{ role: 'assistant', content: 'hi' }],
|
|
})
|
|
).rejects.toThrow(CoolCommException);
|
|
|
|
await expect(
|
|
service.ask({
|
|
cardId: 101,
|
|
messages: [{ role: 'user', content: ' ' }],
|
|
})
|
|
).rejects.toThrow(CoolCommException);
|
|
});
|
|
});
|
|
|
|
describe('2. RuleBased 回复与留资意图', () => {
|
|
let service: AiChatService;
|
|
|
|
beforeEach(() => {
|
|
service = new AiChatService();
|
|
});
|
|
|
|
it('价格问题 shouldCollectLead=true,并引导留资', async () => {
|
|
const result = await service.ask(userAsk('What is the price for a partnership?'));
|
|
expect(result.shouldCollectLead).toBe(true);
|
|
expect(result.reply).toBeTruthy();
|
|
expect(result.locale).toBe('en-US');
|
|
});
|
|
|
|
it('合作 / 联系问题 shouldCollectLead=true', async () => {
|
|
const coop = await service.ask(userAsk('想谈合作'));
|
|
expect(coop.shouldCollectLead).toBe(true);
|
|
|
|
const contact = await service.ask(
|
|
userAsk('How can I contact you?', { locale: 'en-GB' })
|
|
);
|
|
expect(contact.shouldCollectLead).toBe(true);
|
|
expect(contact.locale).toBe('en-GB');
|
|
});
|
|
|
|
it('普通问候 shouldCollectLead=false 且 reply 非空', async () => {
|
|
const result = await service.ask(userAsk('hello'));
|
|
expect(result.shouldCollectLead).toBe(false);
|
|
expect(result.reply).toBeTruthy();
|
|
expect(result.reply.trim().length).toBeGreaterThan(0);
|
|
expect(result.locale).toBe('en-US');
|
|
});
|
|
|
|
it('locale 缺省为 en-US,英文回复不含中文', async () => {
|
|
const result = await service.ask(userAsk('hi there'));
|
|
expect(result.locale).toBe('en-US');
|
|
expect(/[\u4e00-\u9fff]/.test(result.reply)).toBe(false);
|
|
});
|
|
|
|
it('zh-CN 回复含中文', async () => {
|
|
const result = await service.ask(userAsk('你好', { locale: 'zh-CN' }));
|
|
expect(result.locale).toBe('zh-CN');
|
|
expect(result.shouldCollectLead).toBe(false);
|
|
expect(/[\u4e00-\u9fff]/.test(result.reply)).toBe(true);
|
|
});
|
|
|
|
it('兼容 serviceApis 单对象入参', async () => {
|
|
const body: AiChatRequest = {
|
|
cardId: 88,
|
|
locale: 'zh-CN',
|
|
messages: [
|
|
{ role: 'system', content: 'concierge' },
|
|
{ role: 'user', content: '价格多少' },
|
|
],
|
|
};
|
|
const result = await service.ask(body);
|
|
expect(result.shouldCollectLead).toBe(true);
|
|
expect(/[\u4e00-\u9fff]/.test(result.reply)).toBe(true);
|
|
});
|
|
|
|
it('当 DeepSeekService 已配置时优先调用大模型,失败时平滑降级', async () => {
|
|
const mockDeepSeek = {
|
|
isConfigured: jest.fn().mockReturnValue(true),
|
|
chatCompletion: jest.fn().mockResolvedValue('这是 DeepSeek 大模型生成的拟人顾问回复'),
|
|
};
|
|
service.deepSeekService = mockDeepSeek as any;
|
|
|
|
const res = await service.ask(userAsk('你们都有什么服务?'));
|
|
expect(res.reply).toBe('这是 DeepSeek 大模型生成的拟人顾问回复');
|
|
expect(mockDeepSeek.chatCompletion).toHaveBeenCalled();
|
|
|
|
// 测试异常平滑降级
|
|
mockDeepSeek.chatCompletion.mockRejectedValue(new Error('Network error'));
|
|
const fallbackRes = await service.ask(userAsk('你好', { locale: 'zh-CN' }));
|
|
expect(fallbackRes.reply).toBeTruthy();
|
|
expect(fallbackRes.reply).toContain('智能顾问');
|
|
});
|
|
});
|
|
|
|
describe('3. OpenAiChatController /open/ai/chat', () => {
|
|
const controllerFile = path.join(
|
|
__dirname,
|
|
'../../../src/modules/ai/controller/open/chat.ts'
|
|
);
|
|
|
|
let meta: CoolControllerMeta;
|
|
let option: CurdOption;
|
|
|
|
beforeAll(async () => {
|
|
meta = await waitCoolMeta(OpenAiChatController);
|
|
option = meta.curdOption as CurdOption;
|
|
});
|
|
|
|
it('文件路径应符合 /open/ai/chat 自动路由约定', () => {
|
|
expect(fs.existsSync(controllerFile)).toBe(true);
|
|
expect(controllerFile.replace(/\\/g, '/')).toMatch(
|
|
/modules\/ai\/controller\/open\/chat\.ts$/
|
|
);
|
|
});
|
|
|
|
it('路由前缀应为 /open/ai/chat', () => {
|
|
expect(meta.prefix).toBe('/open/ai/chat');
|
|
});
|
|
|
|
it('控制器应继承 BaseController,绑定 AiChatService,不开 CRUD', () => {
|
|
expect(OpenAiChatController.prototype).toBeInstanceOf(BaseController);
|
|
expect(option.service).toBe(AiChatService);
|
|
expect(openAiChatCurdOption.service).toBe(AiChatService);
|
|
expect(option.api || []).toEqual([]);
|
|
});
|
|
|
|
it('serviceApis 应包含 ask', () => {
|
|
const methods = serviceApiMethods(option.serviceApis);
|
|
expect(methods).toContain('ask');
|
|
});
|
|
});
|
|
});
|