github.com/hupe1980/go-huggingface@v0.0.15/question_answering.go (about) 1 package huggingface 2 3 import ( 4 "context" 5 "encoding/json" 6 "errors" 7 ) 8 9 type QuestionAnsweringInputs struct { 10 // (Required) The question as a string that has an answer within Context. 11 Question string `json:"question"` 12 13 // (Required) A string that contains the answer to the question 14 Context string `json:"context"` 15 } 16 17 // Request structure for question answering model 18 type QuestionAnsweringRequest struct { 19 // (Required) 20 Inputs QuestionAnsweringInputs `json:"inputs,omitempty"` 21 Options Options `json:"options,omitempty"` 22 Model string `json:"-"` 23 } 24 25 // Response structure for question answering model 26 type QuestionAnsweringResponse struct { 27 // A string that’s the answer within the Context text. 28 Answer string `json:"answer,omitempty"` 29 30 // A float that represents how likely that the answer is correct. 31 Score float64 `json:"score,omitempty"` 32 33 // The string index of the start of the answer within Context. 34 Start int `json:"start,omitempty"` 35 36 // The string index of the stop of the answer within Context. 37 End int `json:"end,omitempty"` 38 } 39 40 // QuestionAnswering performs question answering using the specified model. 41 // It sends a POST request to the Hugging Face inference endpoint with the provided question and context inputs. 42 // The response contains the answer or an error if the request fails. 43 func (ic *InferenceClient) QuestionAnswering(ctx context.Context, req *QuestionAnsweringRequest) (*QuestionAnsweringResponse, error) { 44 if req.Inputs.Question == "" { 45 return nil, errors.New("question is required") 46 } 47 48 if req.Inputs.Context == "" { 49 return nil, errors.New("context is required") 50 } 51 52 body, err := ic.post(ctx, req.Model, "question-answering", req) 53 if err != nil { 54 return nil, err 55 } 56 57 questionAnsweringResponse := QuestionAnsweringResponse{} 58 if err := json.Unmarshal(body, &questionAnsweringResponse); err != nil { 59 return nil, err 60 } 61 62 return &questionAnsweringResponse, nil 63 }