package openrouter import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" ) const defaultBaseURL = "https://openrouter.ai/api/v1" type Client struct { apiKey string baseURL string httpClient *http.Client } type Option func(*Client) func WithBaseURL(u string) Option { return func(c *Client) { c.baseURL = u } } func WithHTTPClient(hc *http.Client) Option { return func(c *Client) { c.httpClient = hc } } func NewClient(apiKey string, opts ...Option) *Client { c := &Client{ apiKey: apiKey, baseURL: defaultBaseURL, httpClient: http.DefaultClient, } for _, o := range opts { o(c) } return c } func (c *Client) do(ctx context.Context, path string, reqBody, respBody any) error { data, err := json.Marshal(reqBody) if err != nil { return fmt.Errorf("openrouter: marshal request: %w", err) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(data)) if err != nil { return fmt.Errorf("openrouter: build request: %w", err) } req.Header.Set("Authorization", "Bearer "+c.apiKey) req.Header.Set("Content-Type", "application/json") resp, err := c.httpClient.Do(req) if err != nil { return fmt.Errorf("openrouter: send request: %w", err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("openrouter: read response: %w", err) } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("openrouter: HTTP %d: %s", resp.StatusCode, body) } if err := json.Unmarshal(body, respBody); err != nil { return fmt.Errorf("openrouter: unmarshal response: %w\nbody: %s", err, body) } return nil }