i dont like commits

This commit is contained in:
Tomas Dvorak
2026-02-24 12:10:13 +01:00
parent 898a3c303f
commit 1d72a1cc01
109 changed files with 43586 additions and 8484 deletions
+43
View File
@@ -2,9 +2,11 @@
package ai
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
@@ -77,6 +79,8 @@ func (e *APIError) Error() string {
return e.Message
}
const maxHTTPErrorBodyBytes = 2048
// Embed generates embeddings for texts.
func (c *OpenAIClient) Embed(ctx context.Context, texts []string) ([][]float32, error) {
if c.config.APIKey == "" {
@@ -145,6 +149,10 @@ func (c *OpenAIClient) embedBatch(ctx context.Context, model string, texts []str
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return nil, formatHTTPStatusError("embeddings", resp)
}
var embeddingResp EmbeddingResponse
if err := json.NewDecoder(resp.Body).Decode(&embeddingResp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
@@ -252,6 +260,10 @@ func (c *OpenAIClient) QueryWithContext(ctx context.Context, query string, conte
}
defer resp.Body.Close()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return "", formatHTTPStatusError("chat/completions", resp)
}
var chatResp ChatResponse
if err := json.NewDecoder(resp.Body).Decode(&chatResp); err != nil {
return "", fmt.Errorf("failed to decode response: %w", err)
@@ -296,3 +308,34 @@ func (c *MockClient) Embed(ctx context.Context, texts []string) ([][]float32, er
func (c *MockClient) QueryWithContext(ctx context.Context, query string, context []string) (string, error) {
return "This is a mock response.", nil
}
func formatHTTPStatusError(endpoint string, resp *http.Response) error {
body, err := io.ReadAll(io.LimitReader(resp.Body, maxHTTPErrorBodyBytes))
if err != nil {
return fmt.Errorf("openai %s returned status %d (%s) and body read failed: %w", endpoint, resp.StatusCode, http.StatusText(resp.StatusCode), err)
}
return fmt.Errorf(
"openai %s returned status %d (%s): %s",
endpoint,
resp.StatusCode,
http.StatusText(resp.StatusCode),
extractHTTPErrorMessage(body),
)
}
func extractHTTPErrorMessage(body []byte) string {
trimmed := bytes.TrimSpace(body)
if len(trimmed) == 0 {
return "<empty body>"
}
var payload struct {
Error *APIError `json:"error"`
}
if err := json.Unmarshal(trimmed, &payload); err == nil && payload.Error != nil && strings.TrimSpace(payload.Error.Message) != "" {
return strings.TrimSpace(payload.Error.Message)
}
return string(trimmed)
}