import { Injectable, Logger } from '@nestjs/common'; import { PrismaService } from '../../../database/prisma.service'; import { VectorService } from './vector.service'; export interface KnowledgeSearchResult { id: string; question: string; answer: string; score: number; category?: string; } export interface CreateKnowledgeDto { title: string; content: string; categoryId?: string; tags?: string[]; } /** * 知识库服务 - RAG向量检索 */ @Injectable() export class KnowledgeService { private readonly logger = new Logger(KnowledgeService.name); constructor( private readonly prisma: PrismaService, private readonly vectorService: VectorService, ) {} /** * 搜索知识库 */ async search(query: string, topK = 5): Promise { const startTime = Date.now(); try { // 生成查询向量 const queryVector = await this.vectorService.embed(query); // 向量相似度搜索(PostgreSQL pgvector) const results = await this.prisma.$queryRaw` SELECT id, title as question, content as answer, 1 - (vector <=> ${queryVector}::vector) as score, category_id as "categoryId" FROM knowledge_docs WHERE status = 'PUBLISHED' ORDER BY vector <=> ${queryVector}::vector LIMIT ${topK} `; if (results.length === 0) { return null; } const topResult = results[0]; this.logger.debug(`知识库搜索完成: 分数=${topResult.score.toFixed(3)}, 耗时=${Date.now() - startTime}ms`); return topResult; } catch (error) { this.logger.error('知识库搜索失败:', error); return null; } } /** * 批量搜索 */ async searchBatch(queries: string[]): Promise<(KnowledgeSearchResult | null)[]> { return Promise.all(queries.map((q) => this.search(q))); } /** * 创建知识文档 */ async create(dto: CreateKnowledgeDto, userId: string): Promise { // 生成向量 const vector = await this.vectorService.embed(dto.content); // 创建文档 const doc = await this.prisma.knowledgeDoc.create({ data: { title: dto.title, content: dto.content, contentHash: this.hashContent(dto.content), vector: vector as unknown as undefined, categoryId: dto.categoryId, tags: dto.tags || [], status: 'PUBLISHED', createdById: userId, }, }); this.logger.log(`知识文档已创建: ${doc.id}`); return doc.id; } /** * 批量导入 */ async batchImport(docs: CreateKnowledgeDto[], userId: string): Promise { let imported = 0; for (const doc of docs) { try { await this.create(doc, userId); imported++; } catch (error) { this.logger.error(`导入文档失败: ${doc.title}`, error); } } this.logger.log(`批量导入完成: ${imported}/${docs.length}`); return imported; } /** * 更新知识文档 */ async update(id: string, dto: Partial): Promise { const updateData: Record = { ...dto }; if (dto.content) { updateData.contentHash = this.hashContent(dto.content); updateData.vector = await this.vectorService.embed(dto.content); } await this.prisma.knowledgeDoc.update({ where: { id }, data: updateData, }); this.logger.debug(`知识文档已更新: ${id}`); } /** * 删除知识文档 */ async delete(id: string): Promise { await this.prisma.knowledgeDoc.update({ where: { id }, data: { status: 'ARCHIVED' }, }); this.logger.debug(`知识文档已归档: ${id}`); } /** * 获取分类列表 */ async getCategories(): Promise> { const categories = await this.prisma.category.findMany({ include: { _count: { select: { docs: { where: { status: 'PUBLISHED' } } }, }, }, }); return categories.map((cat) => ({ id: cat.id, name: cat.name, count: cat._count.docs, })); } /** * 内容哈希 */ private hashContent(content: string): string { const crypto = require('crypto'); return crypto.createHash('md5').update(content).digest('hex'); } }