| 43 | func (h *HTTPJSONKB) Name() string { return h.name } |
| 44 | |
| 45 | func (h *HTTPJSONKB) Retrieve(ctx context.Context, query string, opts map[string]any) (types.RetrievalResult, error) { |
| 46 | topK := effectiveTopK(h.cfg, opts, 8) |
| 47 | body := map[string]any{ |
| 48 | "query": query, |
| 49 | "top_k": topK, |
| 50 | "kb": h.name, |
| 51 | } |
| 52 | raw, _ := json.Marshal(body) |
| 53 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(h.cfg.Endpoint, "/"), bytes.NewReader(raw)) |
| 54 | if err != nil { |
| 55 | return types.RetrievalResult{}, err |
| 56 | } |
| 57 | req.Header.Set("Content-Type", "application/json") |
| 58 | for k, v := range h.cfg.Headers { |
| 59 | if strings.TrimSpace(k) != "" && strings.TrimSpace(v) != "" { |
| 60 | req.Header.Set(k, v) |
| 61 | } |
| 62 | } |
| 63 | if req.Header.Get("Authorization") == "" && strings.TrimSpace(h.cfg.APIKey) != "" { |
| 64 | req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(h.cfg.APIKey)) |
| 65 | } |
| 66 | resp, err := h.client.Do(req) |
| 67 | if err != nil { |
| 68 | return types.RetrievalResult{}, err |
| 69 | } |
| 70 | defer resp.Body.Close() |
| 71 | b, err := io.ReadAll(resp.Body) |
| 72 | if err != nil { |
| 73 | return types.RetrievalResult{}, err |
| 74 | } |
| 75 | if resp.StatusCode < 200 || resp.StatusCode >= 300 { |
| 76 | return types.RetrievalResult{}, fmt.Errorf("http retrieval %s: status %d: %s", h.name, resp.StatusCode, truncateForErr(b, 512)) |
| 77 | } |
| 78 | return parseHTTPChunksJSON(b) |
| 79 | } |
| 80 | |
| 81 | func truncateForErr(b []byte, max int) string { |
| 82 | s := string(b) |