File size: 4,430 Bytes
d162abc | 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | 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<KnowledgeSearchResult | null> {
const startTime = Date.now();
try {
// 生成查询向量
const queryVector = await this.vectorService.embed(query);
// 向量相似度搜索(PostgreSQL pgvector)
const results = await this.prisma.$queryRaw<KnowledgeSearchResult[]>`
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<string> {
// 生成向量
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<number> {
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<CreateKnowledgeDto>): Promise<void> {
const updateData: Record<string, unknown> = { ...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<void> {
await this.prisma.knowledgeDoc.update({
where: { id },
data: { status: 'ARCHIVED' },
});
this.logger.debug(`知识文档已归档: ${id}`);
}
/**
* 获取分类列表
*/
async getCategories(): Promise<Array<{ id: string; name: string; count: number }>> {
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');
}
}
|