error reporting fixes

This commit is contained in:
Luxferre
2026-03-23 17:10:03 +02:00
parent 5b173095f1
commit 605c8419ec
4 changed files with 102 additions and 9 deletions
+22 -2
View File
@@ -5,12 +5,21 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
var (
ErrLLMTimeout = errors.New("the request to the AI model timed out. Please try again later")
ErrLLMRateLimit = errors.New("rate limit exceeded. Please wait a moment and try again")
ErrLLMAuth = errors.New("authentication failed. Please check your API key")
ErrLLMServer = errors.New("the AI provider's server encountered an error. Please try again later")
ErrLLMInvalidResponse = errors.New("the AI model returned an invalid response structure")
)
// LLMClient represents an abstraction over the LLM provider
type LLMClient interface {
Call(ctx context.Context, model ModelConfig, messages []Message,
@@ -63,11 +72,22 @@ func (s *standardLLMClient) Call(ctx context.Context, model ModelConfig, msgs []
resp, err := client.Do(req)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) || strings.Contains(err.Error(), "timeout") {
return Message{}, ErrLLMTimeout
}
return Message{}, fmt.Errorf("HTTP request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
switch resp.StatusCode {
case http.StatusUnauthorized, http.StatusForbidden:
return Message{}, ErrLLMAuth
case http.StatusTooManyRequests:
return Message{}, ErrLLMRateLimit
case http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable:
return Message{}, ErrLLMServer
}
body, _ := io.ReadAll(resp.Body)
return Message{}, fmt.Errorf("API returned error (%d): %s", resp.StatusCode, string(body))
}
@@ -91,7 +111,7 @@ func (s *standardLLMClient) Call(ctx context.Context, model ModelConfig, msgs []
}
if err := json.Unmarshal(body, &openAIResp); err != nil {
return Message{}, fmt.Errorf("failed to unmarshal response: %w", err)
return Message{}, fmt.Errorf("%w: failed to parse API response: %v", ErrLLMInvalidResponse, err)
}
if openAIResp.Error != nil {
@@ -99,7 +119,7 @@ func (s *standardLLMClient) Call(ctx context.Context, model ModelConfig, msgs []
}
if len(openAIResp.Choices) == 0 {
return Message{}, fmt.Errorf("API returned no choices")
return Message{}, fmt.Errorf("%w: API returned no choices", ErrLLMInvalidResponse)
}
return openAIResp.Choices[0].Message, nil