github.com/weaviate/weaviate@v1.24.6/usecases/modulecomponents/additional/rank/rank_result.go (about) 1 // _ _ 2 // __ _____ __ ___ ___ __ _| |_ ___ 3 // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ 4 // \ V V / __/ (_| |\ V /| | (_| | || __/ 5 // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| 6 // 7 // Copyright © 2016 - 2024 Weaviate B.V. All rights reserved. 8 // 9 // CONTACT: hello@weaviate.io 10 // 11 12 package rank 13 14 import ( 15 "context" 16 "errors" 17 "fmt" 18 "sort" 19 20 "github.com/weaviate/weaviate/entities/models" 21 "github.com/weaviate/weaviate/entities/moduletools" 22 "github.com/weaviate/weaviate/entities/search" 23 rerankmodels "github.com/weaviate/weaviate/usecases/modulecomponents/additional/models" 24 ) 25 26 func (p *ReRankerProvider) getScore(ctx context.Context, cfg moduletools.ClassConfig, 27 in []search.Result, params *Params, 28 ) ([]search.Result, error) { 29 if len(in) == 0 { 30 return nil, nil 31 } 32 if params == nil { 33 return nil, fmt.Errorf("no params provided") 34 } 35 36 rankProperty := params.GetProperty() 37 query := params.GetQuery() 38 39 // check if user parameter values are valid 40 if len(rankProperty) == 0 { 41 return in, errors.New("no properties provided") 42 } 43 44 documents := make([]string, len(in)) 45 for i := range in { // for each result of the general GraphQL Query 46 // get text property 47 rankPropertyValue := "" 48 schema := in[i].Object().Properties.(map[string]interface{}) 49 for property, value := range schema { 50 if property == rankProperty { 51 if valueString, ok := value.(string); ok { 52 rankPropertyValue = valueString 53 } 54 } 55 } 56 documents[i] = rankPropertyValue 57 } 58 59 // rank results 60 result, err := p.client.Rank(ctx, query, documents, cfg) 61 if err != nil { 62 return nil, fmt.Errorf("error ranking with cohere: %w", err) 63 } 64 65 // add scores to results 66 for i := range in { 67 if in[i].AdditionalProperties == nil { 68 in[i].AdditionalProperties = models.AdditionalProperties{} 69 } 70 in[i].AdditionalProperties["rerank"] = []*rerankmodels.RankResult{ 71 { 72 Score: &result.DocumentScores[i].Score, 73 }, 74 } 75 } 76 77 // sort the list 78 sort.Slice(in, func(i, j int) bool { 79 apI := in[i].AdditionalProperties["rerank"].([]*rerankmodels.RankResult) 80 apJ := in[j].AdditionalProperties["rerank"].([]*rerankmodels.RankResult) 81 82 // Sort in descending order, based on Score values 83 return *apI[0].Score > *apJ[0].Score 84 }) 85 return in, nil 86 }