File size: 2,930 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
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';

/**
 * 向量服务 - 文本嵌入
 */
@Injectable()
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);
  }
}