vector_store.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package rag
  2. import (
  3. "context"
  4. "fmt"
  5. "strconv"
  6. "github.com/2930134478/AI-CS/backend/infra"
  7. )
  8. // VectorStoreService 向量存储服务(业务层)
  9. type VectorStoreService struct {
  10. vectorStore *infra.VectorStore
  11. }
  12. // NewVectorStoreService 创建向量存储服务实例
  13. func NewVectorStoreService(vectorStore *infra.VectorStore) *VectorStoreService {
  14. return &VectorStoreService{
  15. vectorStore: vectorStore,
  16. }
  17. }
  18. // UpsertVector 插入或更新单个向量
  19. func (s *VectorStoreService) UpsertVector(ctx context.Context, documentID string, knowledgeBaseID string, content string, vector []float32) error {
  20. return s.vectorStore.UpsertVector(ctx, documentID, knowledgeBaseID, content, vector)
  21. }
  22. // UpsertVectors 批量插入或更新向量
  23. func (s *VectorStoreService) UpsertVectors(ctx context.Context, documentIDs []string, knowledgeBaseIDs []string, contents []string, vectors [][]float32) error {
  24. return s.vectorStore.UpsertVectors(ctx, documentIDs, knowledgeBaseIDs, contents, vectors)
  25. }
  26. // SearchVectors 搜索相似向量
  27. func (s *VectorStoreService) SearchVectors(ctx context.Context, queryVector []float32, topK int, knowledgeBaseID *string) ([]SearchResult, error) {
  28. results, err := s.vectorStore.SearchVectors(ctx, queryVector, topK, knowledgeBaseID)
  29. if err != nil {
  30. return nil, fmt.Errorf("向量检索失败: %w", err)
  31. }
  32. // 转换结果
  33. searchResults := make([]SearchResult, len(results))
  34. for i, r := range results {
  35. searchResults[i] = SearchResult{
  36. DocumentID: r.DocumentID,
  37. KnowledgeBaseID: r.KnowledgeBaseID,
  38. Content: r.Content,
  39. Score: r.Score,
  40. }
  41. }
  42. return searchResults, nil
  43. }
  44. // DeleteVector 删除向量
  45. func (s *VectorStoreService) DeleteVector(ctx context.Context, documentID string) error {
  46. return s.vectorStore.DeleteVector(ctx, documentID)
  47. }
  48. // DeleteVectors 批量删除向量
  49. func (s *VectorStoreService) DeleteVectors(ctx context.Context, documentIDs []string) error {
  50. return s.vectorStore.DeleteVectors(ctx, documentIDs)
  51. }
  52. // ConvertDocumentID 将 uint 转换为 string
  53. func ConvertDocumentID(id uint) string {
  54. return strconv.FormatUint(uint64(id), 10)
  55. }
  56. // ConvertKnowledgeBaseID 将 uint 转换为 string
  57. func ConvertKnowledgeBaseID(id uint) string {
  58. return strconv.FormatUint(uint64(id), 10)
  59. }