|
| 1 | +package aibridged |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "os" |
| 7 | + |
| 8 | + "github.com/anthropics/anthropic-sdk-go" |
| 9 | + "github.com/anthropics/anthropic-sdk-go/option" |
| 10 | + ant_constant "github.com/anthropics/anthropic-sdk-go/shared/constant" |
| 11 | +) |
| 12 | + |
| 13 | +// newAnthropicClient creates an Anthropic client with the given base URL and API key. |
| 14 | +func newAnthropicClient(baseURL, key string, opts ...option.RequestOption) anthropic.Client { |
| 15 | + if key == "" { |
| 16 | + key = os.Getenv("ANTHROPIC_API_KEY") |
| 17 | + } |
| 18 | + opts = append(opts, option.WithAPIKey(key)) |
| 19 | + if baseURL != "" { |
| 20 | + opts = append(opts, option.WithBaseURL(baseURL)) |
| 21 | + } |
| 22 | + |
| 23 | + return anthropic.NewClient(opts...) |
| 24 | +} |
| 25 | + |
| 26 | +func getAnthropicErrorResponse(err error) *AnthropicErrorResponse { |
| 27 | + var apierr *anthropic.Error |
| 28 | + if !errors.As(err, &apierr) { |
| 29 | + return nil |
| 30 | + } |
| 31 | + |
| 32 | + msg := apierr.Error() |
| 33 | + |
| 34 | + var detail *anthropic.BetaAPIError |
| 35 | + if field, ok := apierr.JSON.ExtraFields["error"]; ok { |
| 36 | + _ = json.Unmarshal([]byte(field.Raw()), &detail) |
| 37 | + } |
| 38 | + if detail != nil { |
| 39 | + msg = detail.Message |
| 40 | + } |
| 41 | + |
| 42 | + return &AnthropicErrorResponse{ |
| 43 | + BetaErrorResponse: &anthropic.BetaErrorResponse{ |
| 44 | + Error: anthropic.BetaErrorUnion{ |
| 45 | + Message: msg, |
| 46 | + Type: string(detail.Type), |
| 47 | + }, |
| 48 | + Type: ant_constant.ValueOf[ant_constant.Error](), |
| 49 | + }, |
| 50 | + StatusCode: apierr.StatusCode, |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +type AnthropicErrorResponse struct { |
| 55 | + *anthropic.BetaErrorResponse |
| 56 | + |
| 57 | + StatusCode int `json:"-"` |
| 58 | +} |
0 commit comments