1package anthropic
2
3import (
4 "cmp"
5 "errors"
6 "net/http"
7 "strings"
8
9 "charm.land/fantasy"
10 "github.com/charmbracelet/anthropic-sdk-go"
11)
12
13func toProviderErr(err error) error {
14 var apiErr *anthropic.Error
15 if errors.As(err, &apiErr) {
16 return &fantasy.ProviderError{
17 Title: cmp.Or(fantasy.ErrorTitleForStatusCode(apiErr.StatusCode), "provider request failed"),
18 Message: apiErr.Error(),
19 Cause: apiErr,
20 URL: apiErr.Request.URL.String(),
21 StatusCode: apiErr.StatusCode,
22 RequestBody: apiErr.DumpRequest(true),
23 ResponseHeaders: toHeaderMap(apiErr.Response.Header),
24 ResponseBody: apiErr.DumpResponse(true),
25 }
26 }
27 return err
28}
29
30func toHeaderMap(in http.Header) (out map[string]string) {
31 out = make(map[string]string, len(in))
32 for k, v := range in {
33 if l := len(v); l > 0 {
34 out[k] = v[l-1]
35 in[strings.ToLower(k)] = v
36 }
37 }
38 return out
39}