MCPcopy Create free account
hub / github.com/53AI/53AIHub / GetQueryEmbedding

Method GetQueryEmbedding

api/service/rag/embedding.go:960–1019  ·  view source on GitHub ↗

GetQueryEmbedding 获取查询文本的向量(使用 singleflight 防止并发重复请求)

(eid int64, query string, channelID int64, config *ChunkConfig)

Source from the content-addressed store, hash-verified

958
959// GetQueryEmbedding 获取查询文本的向量(使用 singleflight 防止并发重复请求)
960func (s *EmbeddingService) GetQueryEmbedding(eid int64, query string, channelID int64, config *ChunkConfig) ([]float64, error) {
961 // 验证输入
962 if config == nil {
963 return nil, fmt.Errorf("配置不能为空")
964 }
965
966 query = strings.TrimSpace(query)
967 if query == "" {
968 return nil, fmt.Errorf("查询内容不能为空")
969 }
970
971 modelName := ""
972 if config.EmbeddingModelName != nil {
973 modelName = *config.EmbeddingModelName
974 }
975 cacheKey := buildQueryEmbeddingCacheKey(eid, query, channelID, modelName)
976 if cacheKey != "" {
977 if cachedVector, hit := s.getCachedQueryEmbedding(cacheKey); hit {
978 return cachedVector, nil
979 }
980 }
981
982 // 使用 singleflight 防止并发时对相同查询重复调用 embedding API
983 sfKey := fmt.Sprintf("eid:%d:ch:%d:m:%s:q:%s", eid, channelID, modelName, query)
984 result, err := embeddingSingleflight.Do(sfKey, func() (interface{}, error) {
985 // 再次检查缓存(可能在等待其他请求完成时已写入)
986 if cacheKey != "" {
987 if cachedVector, hit := s.getCachedQueryEmbedding(cacheKey); hit {
988 return cachedVector, nil
989 }
990 }
991
992 // 获取渠道配置
993 channel, err := model.GetChannelByID(channelID)
994 if err != nil {
995 return nil, fmt.Errorf("获取渠道配置失败: %v", err)
996 }
997
998 if channel.Eid != eid {
999 return nil, fmt.Errorf("渠道不属于当前企业")
1000 }
1001
1002 // 调用embedding API
1003 vector, err := s.callEmbeddingAPI(query, channel, config, nil)
1004 if err != nil {
1005 return nil, err
1006 }
1007
1008 if cacheKey != "" {
1009 s.setCachedQueryEmbedding(cacheKey, vector)
1010 }
1011 return vector, nil
1012 })
1013
1014 if err != nil {
1015 return nil, err
1016 }
1017

Callers 6

SearchEntitiesMethod · 0.80
SearchEntityFilesMethod · 0.80
singleVectorSearchMethod · 0.80
meanPairSimilarityMethod · 0.80

Calls 6

callEmbeddingAPIMethod · 0.95
ErrorfMethod · 0.80
DoMethod · 0.65

Tested by

no test coverage detected