// Package ai provides a tiny OpenAI chat client (stdlib only) for short mail // summaries. Disabled (no-op) when no API key is configured. package ai import ( "bytes" "context" "encoding/json" "fmt" "net/http" "strings" "time" ) type Client struct { key string model string http *http.Client } func New(apiKey string) *Client { return &Client{key: strings.TrimSpace(apiKey), model: "gpt-4o-mini", http: &http.Client{Timeout: 20 * time.Second}} } func (c *Client) Enabled() bool { return c != nil && c.key != "" } // Summarize returns a one-line Korean summary of the text. Best-effort; returns // an error the caller can ignore (summary stays empty). func (c *Client) Summarize(ctx context.Context, text string) (string, error) { if !c.Enabled() { return "", nil } text = strings.TrimSpace(text) if text == "" { return "", nil } if len(text) > 4000 { text = text[:4000] } body := map[string]any{ "model": c.model, "messages": []map[string]string{ {"role": "system", "content": "너는 이메일을 아주 짧게 요약하는 비서다. 한국어로 핵심만 한 문장(최대 40자)으로 답하라. 군더더기·인사말 제외."}, {"role": "user", "content": text}, }, "max_tokens": 80, "temperature": 0.2, } b, _ := json.Marshal(body) req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.openai.com/v1/chat/completions", bytes.NewReader(b)) req.Header.Set("Authorization", "Bearer "+c.key) req.Header.Set("Content-Type", "application/json") resp, err := c.http.Do(req) if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode >= 300 { return "", fmt.Errorf("openai %d", resp.StatusCode) } var out struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` } `json:"choices"` } if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { return "", err } if len(out.Choices) == 0 { return "", nil } return strings.TrimSpace(out.Choices[0].Message.Content), nil }