gitFlow/internal/ai/openai.go
dimitar aee63bf321 feat: phase 5 — AI agent integration (OpenAI, Ollama, Anthropic)
Add the AI layer that turns scan results into suggested next actions.

Provider model (internal/ai):
- Provider interface with Name() and Suggest(ctx, ScanResult) returning
  []Suggestion (repo_path, action, message, command, priority 0-2)
- NewProvider factory resolves the configured provider and enforces that
  cloud providers have their API key in the configured env var; Ollama
  needs no key
- OpenAIProvider: Chat Completions with response_format json_object
- OllamaProvider: local /api/chat with format:json for structured output
- AnthropicProvider: Messages API with system prompt and key/version
  headers; all three fall back to provider-appropriate defaults for
  base_url and model
- Shared client: 60s timeout, 4 MiB response cap, JSON encode/decode,
  HTTP error surfaces the upstream status and body

Prompt design (BuildPrompt):
- Renders the full repository status table (name/status/branch/ahead/
  behind/changes) plus strict output rules: exact suggestion schema,
  allowed actions, smallest-safe-step guidance, no invented repositories,
  return [] when healthy

Parsing (parseSuggestions):
- Tolerates ```json fences and surrounding prose, clamps priorities to
  0-2, caps the result, and rejects replies without a JSON array

Suggestion display (presenter.Suggestions):
- "AI SUGGESTIONS" table (repository/action/priority/message/command)
  rendered below the scan table with priority color-coded (red/yellow/
  green); empty results say all repositories are healthy

Guarded execution (--ai-execute, experimental):
- RunConfirmed executes a suggestion's command inside its repository only
  after explicit per-command y/N confirmation, and only for actions on an
  allowlist (commit/push/pull/stash/checkout) so LLM output can never run
  arbitrary shell commands; cancellation aborts remaining suggestions

CLI wiring:
- scan: AI block after the table when --ai is set and format is not json
  (JSON streams stay machine-readable); failures degrade to warnings
- watch: AI is queried only on the first frame and when something changed
  since the previous frame, to avoid hammering the provider every interval
- New --ai-execute flag and provider validation in config (openai/ollama/
  anthropic), included in the config dump

Testing:
- httptest-based provider tests verifying request shape (model, auth
  headers, path), response parsing, API error bodies, HTTP failures, and
  cancellation
- Parse tests: plain/fenced/prose replies, empty arrays, garbage,
  truncated JSON, priority clamping
- Execution tests: unsafe actions and empty commands never run, declined
  confirmations are skipped, confirmed commands execute in the repo dir,
  failing commands surface errors
- Presenter suggestion table and empty-state tests

Verified: go build, go vet, go test -race, gofmt clean; end-to-end smoke
test against a local fake Ollama server (request shape confirmed, table +
suggestions rendered) and the missing-API-key warning path.
2026-08-02 08:48:27 +02:00

88 lines
2.3 KiB
Go

package ai
import (
"context"
"fmt"
"gitea.oblak.solutions/dimitar/gitFlow/internal/config"
"gitea.oblak.solutions/dimitar/gitFlow/pkg/status"
)
const defaultOpenAIBaseURL = "https://api.openai.com/v1"
// OpenAIProvider talks to the OpenAI Chat Completions API.
type OpenAIProvider struct {
model string
baseURL string
apiKey string
client *client
}
// NewOpenAI builds an OpenAI provider. base_url and model fall back to
// sensible defaults when unset in the configuration.
func NewOpenAI(cfg config.AIConfig, apiKey string) *OpenAIProvider {
baseURL := cfg.BaseURL
if baseURL == "" {
baseURL = defaultOpenAIBaseURL
}
model := cfg.Model
if model == "" {
model = "gpt-4o"
}
return &OpenAIProvider{model: model, baseURL: baseURL, apiKey: apiKey, client: newClient()}
}
// Name implements Provider.
func (p *OpenAIProvider) Name() string { return "openai" }
// chatMessage is a single chat turn, shared with the other providers.
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type chatRequest struct {
Model string `json:"model"`
Messages []chatMessage `json:"messages"`
ResponseFormat *responseFormat `json:"response_format,omitempty"`
}
type responseFormat struct {
Type string `json:"type"` // "json_object"
}
type chatResponse struct {
Choices []struct {
Message chatMessage `json:"message"`
} `json:"choices"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
// Suggest implements Provider.
func (p *OpenAIProvider) Suggest(ctx context.Context, result status.ScanResult) ([]Suggestion, error) {
req := chatRequest{
Model: p.model,
Messages: []chatMessage{
{Role: "system", Content: "You are gitflow, a concise Git repository health assistant. You reply with JSON only."},
{Role: "user", Content: BuildPrompt(result)},
},
ResponseFormat: &responseFormat{Type: "json_object"},
}
var resp chatResponse
err := p.client.postJSON(ctx, p.baseURL+"/chat/completions",
map[string]string{"Authorization": "Bearer " + p.apiKey}, req, &resp)
if err != nil {
return nil, err
}
if resp.Error != nil {
return nil, fmt.Errorf("ai: openai: %s", resp.Error.Message)
}
if len(resp.Choices) == 0 {
return nil, fmt.Errorf("ai: openai: empty response")
}
return parseSuggestions(resp.Choices[0].Message.Content)
}