bge.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package embedding
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "log"
  9. "net/http"
  10. "strings"
  11. "time"
  12. )
  13. // BGEEmbeddingService BGE 嵌入服务实现
  14. type BGEEmbeddingService struct {
  15. apiURL string
  16. apiKey string
  17. model string
  18. dimension int
  19. }
  20. // NewBGEEmbeddingService 创建 BGE 嵌入服务实例
  21. func NewBGEEmbeddingService(apiURL, apiKey, model string) *BGEEmbeddingService {
  22. if apiURL == "" {
  23. apiURL = "http://localhost:8080"
  24. }
  25. if model == "" {
  26. model = "bge-small-zh-v1.5"
  27. }
  28. return &BGEEmbeddingService{
  29. apiURL: apiURL,
  30. apiKey: apiKey,
  31. model: model,
  32. dimension: 512, // BGE 模型的默认维度
  33. }
  34. }
  35. // EmbedText 向量化单个文本
  36. func (s *BGEEmbeddingService) EmbedText(ctx context.Context, text string) ([]float32, error) {
  37. vectors, err := s.EmbedTexts(ctx, []string{text})
  38. if err != nil {
  39. return nil, err
  40. }
  41. if len(vectors) == 0 {
  42. return nil, fmt.Errorf("未返回向量")
  43. }
  44. return vectors[0], nil
  45. }
  46. // EmbedTexts 批量向量化文本
  47. func (s *BGEEmbeddingService) EmbedTexts(ctx context.Context, texts []string) ([][]float32, error) {
  48. if len(texts) == 0 {
  49. return nil, nil
  50. }
  51. // 支持填完整路径或仅填 base:若已以 /embeddings 结尾则不再追加,否则追加 /embeddings
  52. url := strings.TrimSuffix(s.apiURL, "/")
  53. if url != "" && !strings.HasSuffix(strings.ToLower(url), "/embeddings") {
  54. url = url + "/embeddings"
  55. } else if url == "" {
  56. url = s.apiURL + "/embeddings"
  57. }
  58. // 构建请求体(兼容 HuggingFace Inference API 格式)
  59. requestBody := map[string]interface{}{
  60. "inputs": texts,
  61. }
  62. jsonData, err := json.Marshal(requestBody)
  63. if err != nil {
  64. return nil, fmt.Errorf("序列化请求失败: %w", err)
  65. }
  66. // 创建 HTTP 请求
  67. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
  68. if err != nil {
  69. return nil, fmt.Errorf("创建请求失败: %w", err)
  70. }
  71. req.Header.Set("Content-Type", "application/json")
  72. if s.apiKey != "" {
  73. req.Header.Set("Authorization", "Bearer "+s.apiKey)
  74. }
  75. // 发送请求
  76. client := &http.Client{Timeout: 30 * time.Second}
  77. resp, err := client.Do(req)
  78. if err != nil {
  79. return nil, fmt.Errorf("BGE 嵌入服务调用失败: %w", err)
  80. }
  81. defer resp.Body.Close()
  82. // 读取响应
  83. body, err := io.ReadAll(resp.Body)
  84. if err != nil {
  85. return nil, fmt.Errorf("读取响应失败: %w", err)
  86. }
  87. if resp.StatusCode != http.StatusOK {
  88. return nil, fmt.Errorf("BGE 嵌入服务调用失败: HuggingFace API 返回错误状态码 %d: %s", resp.StatusCode, string(body))
  89. }
  90. // 解析响应(HuggingFace Inference API 格式);若返回 HTML 则提示检查 API 地址/密钥
  91. var response [][]float64
  92. if err := json.Unmarshal(body, &response); err != nil {
  93. if len(body) > 0 && body[0] == '<' {
  94. snippet := string(body)
  95. if len(snippet) > 200 {
  96. snippet = snippet[:200] + "..."
  97. }
  98. log.Printf("[嵌入] BGE 返回了 HTML 而非 JSON,请检查 API 地址与密钥。响应片段: %s", snippet)
  99. return nil, fmt.Errorf("嵌入 API 返回了 HTML 而非 JSON,请检查「设置 - 知识库向量模型」中的 API 地址与密钥: %w", err)
  100. }
  101. return nil, fmt.Errorf("解析响应失败: %w", err)
  102. }
  103. // 转换为 float32
  104. result := make([][]float32, len(response))
  105. for i, item := range response {
  106. result[i] = make([]float32, len(item))
  107. for j, v := range item {
  108. result[i][j] = float32(v)
  109. }
  110. }
  111. return result, nil
  112. }
  113. // GetDimension 获取向量维度
  114. func (s *BGEEmbeddingService) GetDimension() int {
  115. return s.dimension
  116. }
  117. // GetModelName 获取模型名称
  118. func (s *BGEEmbeddingService) GetModelName() string {
  119. return s.model
  120. }