All checks were successful
build-and-push / build (push) Successful in 32s
- GET /my/tasks: 전 프로젝트에서 나에게 배정된 작업 + projectName (대시보드 JIRA 보드용) · fix: ORDER BY "end"(예약어) 따옴표 처리 - CalendarEvent 모델 + /calendar/events CRUD(본인 소유), nav에 캘린더 추가 - internal/ai(OpenAI, stdlib): 메일 동기화 시 신규 메일에 한 줄 AI 요약 생성(OPENAI_API_KEY) · ProjectMailMsg.Summary, 회당 40건 상한 - nav inbox 라벨 쪽지함으로 통일 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
76 lines
2.0 KiB
Go
76 lines
2.0 KiB
Go
// 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
|
|
}
|