github.com/weaviate/weaviate@v1.24.6/modules/sum-transformers/client/client.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 client 13 14 import ( 15 "bytes" 16 "context" 17 "encoding/json" 18 "fmt" 19 "io" 20 "net/http" 21 "time" 22 23 "github.com/pkg/errors" 24 "github.com/sirupsen/logrus" 25 "github.com/weaviate/weaviate/modules/sum-transformers/ent" 26 ) 27 28 type client struct { 29 origin string 30 httpClient *http.Client 31 logger logrus.FieldLogger 32 } 33 34 type sumInput struct { 35 Text string `json:"text"` 36 } 37 38 type summaryResponse struct { 39 // Property string `json:"property"` 40 Result string `json:"result"` 41 } 42 43 type sumResponse struct { 44 Error string 45 sumInput 46 Summary []summaryResponse `json:"summary"` 47 } 48 49 func New(origin string, timeout time.Duration, logger logrus.FieldLogger) *client { 50 return &client{ 51 origin: origin, 52 httpClient: &http.Client{ 53 Timeout: timeout, 54 }, 55 logger: logger, 56 } 57 } 58 59 func (c *client) GetSummary(ctx context.Context, property, text string, 60 ) ([]ent.SummaryResult, error) { 61 body, err := json.Marshal(sumInput{ 62 Text: text, 63 }) 64 if err != nil { 65 return nil, errors.Wrapf(err, "marshal body") 66 } 67 68 req, err := http.NewRequestWithContext(ctx, "POST", c.url("/sum/"), 69 bytes.NewReader(body)) 70 if err != nil { 71 return nil, errors.Wrap(err, "create POST request") 72 } 73 74 res, err := c.httpClient.Do(req) 75 if err != nil { 76 return nil, errors.Wrap(err, "send POST request") 77 } 78 defer res.Body.Close() 79 80 bodyBytes, err := io.ReadAll(res.Body) 81 if err != nil { 82 return nil, errors.Wrap(err, "read response body") 83 } 84 85 var resBody sumResponse 86 if err := json.Unmarshal(bodyBytes, &resBody); err != nil { 87 return nil, errors.Wrap(err, "unmarshal response body") 88 } 89 90 if res.StatusCode > 399 { 91 return nil, errors.Errorf("fail with status %d: %s", res.StatusCode, resBody.Error) 92 } 93 94 out := make([]ent.SummaryResult, len(resBody.Summary)) 95 96 for i, elem := range resBody.Summary { 97 out[i].Result = elem.Result 98 out[i].Property = property 99 } 100 101 // format resBody to nerResult 102 return out, nil 103 } 104 105 func (c *client) url(path string) string { 106 return fmt.Sprintf("%s%s", c.origin, path) 107 }