package ai import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "sort" "strings" "time" ) // openAIClient talks to a server with the OpenAI chat-completions API, such // as Ollama or LM Studio. type openAIClient struct { base string // ends in /v1 apiKey string cfg Config http *http.Client } func newOpenAI(baseURL, apiKey string, cfg Config) *openAIClient { return &openAIClient{ base: NormalizeBaseURL(baseURL), apiKey: apiKey, cfg: cfg, // Local models can take minutes on long prompts. http: &http.Client{Timeout: 10 * time.Minute}, } } // NormalizeBaseURL turns "llm.lan:11434", "http://llm.lan:11434" or // "http://llm.lan:11434/v1/" into "http://llm.lan:11434/v1". func NormalizeBaseURL(u string) string { u = strings.TrimRight(strings.TrimSpace(u), "/") if u == "" { return "" } if !strings.Contains(u, "://") { u = "http://" + u } if !strings.HasSuffix(u, "/v1") { u += "/v1" } return u } func (o *openAIClient) Generate(ctx context.Context, req Request) (string, error) { type message struct { Role string `json:"role"` Content string `json:"content"` } body := map[string]any{ "model": o.cfg.ModelFor(req.Task), } var msgs []message if req.System != "" { msgs = append(msgs, message{"system", req.System}) } msgs = append(msgs, message{"user", req.Prompt}) body["messages"] = msgs if req.MaxTokens > 0 { body["max_tokens"] = req.MaxTokens } if req.Schema != nil { body["response_format"] = map[string]any{ "type": "json_schema", "json_schema": map[string]any{ "name": "reply", "schema": req.Schema, }, } } var out struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` FinishReason string `json:"finish_reason"` } `json:"choices"` } if err := o.do(ctx, http.MethodPost, "/chat/completions", body, &out); err != nil { return "", err } if len(out.Choices) == 0 { return "", fmt.Errorf("%s returned no reply", o.base) } text := strings.TrimSpace(out.Choices[0].Message.Content) if text == "" { return "", fmt.Errorf("%s returned an empty reply (finish reason %s)", o.base, out.Choices[0].FinishReason) } return text, nil } // ListModels asks an OpenAI-compatible server which models it has. func ListModels(ctx context.Context, baseURL, apiKey string) ([]string, error) { o := newOpenAI(baseURL, apiKey, Config{}) o.http.Timeout = 10 * time.Second var out struct { Data []struct { ID string `json:"id"` } `json:"data"` } if err := o.do(ctx, http.MethodGet, "/models", nil, &out); err != nil { return nil, err } ids := make([]string, 0, len(out.Data)) for _, m := range out.Data { ids = append(ids, m.ID) } sort.Strings(ids) return ids, nil } func (o *openAIClient) do(ctx context.Context, method, path string, body, out any) error { var rd io.Reader if body != nil { raw, err := json.Marshal(body) if err != nil { return err } rd = bytes.NewReader(raw) } req, err := http.NewRequestWithContext(ctx, method, o.base+path, rd) if err != nil { return err } if body != nil { req.Header.Set("Content-Type", "application/json") } if o.apiKey != "" { req.Header.Set("Authorization", "Bearer "+o.apiKey) } res, err := o.http.Do(req) if err != nil { return fmt.Errorf("can't reach %s: %w", o.base, err) } defer res.Body.Close() raw, _ := io.ReadAll(io.LimitReader(res.Body, 32<<20)) if res.StatusCode != http.StatusOK { return fmt.Errorf("%s%s: HTTP %d: %.300s", o.base, path, res.StatusCode, raw) } if err := json.Unmarshal(raw, out); err != nil { return fmt.Errorf("%s%s: unexpected reply: %w", o.base, path, err) } return nil }