Download apps/api/src/modules/knowledge/services/vector.service.ts from qf46578/omnics: direct link, hf CLI and curl.
- Browser
- Download file 2.93 kB
-
https://huggingface.co/spaces/qf46578/omnics/resolve/main/apps/api/src/modules/knowledge/services/vector.service.ts
- Command line
-
hf download hf://spaces/qf46578/omnics/apps/api/src/modules/knowledge/services/vector.service.ts
-
curl -L -o vector.service.ts https://huggingface.co/spaces/qf46578/omnics/resolve/main/apps/api/src/modules/knowledge/services/vector.service.ts
2.93 kB
| import { Injectable, Logger } from '@nestjs/common'; | |
| import { ConfigService } from '@nestjs/config'; | |
| import axios from 'axios'; | |
| /** | |
| * 向量服务 - 文本嵌入 | |
| */ | |
| () | |
| export class VectorService { | |
| private readonly logger = new Logger(VectorService.name); | |
| private readonly embeddingModel: string; | |
| private readonly embeddingApiKey: string; | |
| private readonly embeddingBaseUrl: string; | |
| constructor(private readonly config: ConfigService) { | |
| this.embeddingModel = config.get('EMBEDDING_MODEL') || 'text-embedding-ada-002'; | |
| this.embeddingApiKey = config.get('EMBEDDING_API_KEY') || ''; | |
| this.embeddingBaseUrl = config.get('EMBEDDING_BASE_URL') || 'https://api.openai.com/v1'; | |
| } | |
| /** | |
| * 生成文本嵌入向量 | |
| */ | |
| async embed(text: string): Promise<number[]> { | |
| // 如果没有配置API,返回模拟向量 | |
| if (!this.embeddingApiKey) { | |
| return this.generateMockVector(text); | |
| } | |
| try { | |
| const response = await axios.post( | |
| `${this.embeddingBaseUrl}/embeddings`, | |
| { | |
| model: this.embeddingModel, | |
| input: text, | |
| }, | |
| { | |
| headers: { | |
| 'Authorization': `Bearer ${this.embeddingApiKey}`, | |
| 'Content-Type': 'application/json', | |
| }, | |
| }, | |
| ); | |
| return response.data.data[0].embedding; | |
| } catch (error) { | |
| this.logger.error('向量生成失败:', error); | |
| // 降级到模拟向量 | |
| return this.generateMockVector(text); | |
| } | |
| } | |
| /** | |
| * 批量生成嵌入 | |
| */ | |
| async embedBatch(texts: string[]): Promise<number[][]> { | |
| return Promise.all(texts.map((text) => this.embed(text))); | |
| } | |
| /** | |
| * 计算余弦相似度 | |
| */ | |
| cosineSimilarity(a: number[], b: number[]): number { | |
| if (a.length !== b.length) { | |
| throw new Error('向量长度不匹配'); | |
| } | |
| let dotProduct = 0; | |
| let normA = 0; | |
| let normB = 0; | |
| for (let i = 0; i < a.length; i++) { | |
| dotProduct += a[i] * b[i]; | |
| normA += a[i] * a[i]; | |
| normB += b[i] * b[i]; | |
| } | |
| return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB)); | |
| } | |
| /** | |
| * 生成模拟向量(用于开发/测试) | |
| */ | |
| private generateMockVector(text: string): number[] { | |
| // 基于文本生成确定性的模拟向量 | |
| const hash = this.simpleHash(text); | |
| const vector: number[] = []; | |
| for (let i = 0; i < 1536; i++) { | |
| // 生成[-1, 1]范围的值 | |
| vector.push(Math.sin(hash + i * 0.1)); | |
| } | |
| // 归一化 | |
| const norm = Math.sqrt(vector.reduce((sum, v) => sum + v * v, 0)); | |
| return vector.map((v) => v / norm); | |
| } | |
| /** | |
| * 简单哈希函数 | |
| */ | |
| private simpleHash(text: string): number { | |
| let hash = 0; | |
| for (let i = 0; i < text.length; i++) { | |
| const char = text.charCodeAt(i); | |
| hash = ((hash << 5) - hash) + char; | |
| hash = hash & hash; // Convert to 32bit integer | |
| } | |
| return Math.abs(hash); | |
| } | |
| } | |