// Package ai 是一个 OpenAI 兼容接口的最小客户端,给文档翻译用。 // // 兼容 DeepSeek、GLM、Moonshot、通义、OpenAI 以及本地 Ollama // (http://localhost:11434/v1)——它们都实现 /chat/completions。 package ai import ( "bytes" "context" "encoding/json" "fmt" "net/http" "strings" "time" ) // Config 是访问一个 OpenAI 兼容服务所需的三件套。 type Config struct { // BaseURL 形如 https://api.deepseek.com/v1,客户端在后面拼 /chat/completions。 BaseURL string APIKey string // Model 如 deepseek-chat、glm-4-flash、qwen-plus。 Model string } // Ready 判断配置是否齐全可用。 func (c Config) Ready() bool { return c.BaseURL != "" && c.APIKey != "" && c.Model != "" } // chatRequest/chatResponse 只覆盖非流式对话用到的字段。 type chatRequest struct { Model string `json:"model"` Messages []chatMessage `json:"messages"` Temperature float64 `json:"temperature"` Stream bool `json:"stream"` } type chatMessage struct { Role string `json:"role"` Content string `json:"content"` } type chatResponse struct { Choices []struct { Message chatMessage `json:"message"` } `json:"choices"` Error *struct { Message string `json:"message"` } `json:"error"` } // Chat 发一次非流式对话,返回 assistant 的回复文本。 func Chat(ctx context.Context, cfg Config, system, user string) (string, error) { if !cfg.Ready() { return "", fmt.Errorf("AI 接口未配置完整(地址 / Key / 模型)") } reqBody, err := json.Marshal(chatRequest{ Model: cfg.Model, Messages: []chatMessage{ {Role: "system", Content: system}, {Role: "user", Content: user}, }, Temperature: 0.2, Stream: false, }) if err != nil { return "", err } url := strings.TrimRight(cfg.BaseURL, "/") + "/chat/completions" req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(reqBody)) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+cfg.APIKey) resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() var out chatResponse dec := json.NewDecoder(resp.Body) if err := dec.Decode(&out); err != nil { return "", fmt.Errorf("响应解析失败(HTTP %d): %w", resp.StatusCode, err) } if resp.StatusCode != http.StatusOK { if out.Error != nil && out.Error.Message != "" { return "", fmt.Errorf("HTTP %d: %s", resp.StatusCode, out.Error.Message) } return "", fmt.Errorf("HTTP %d", resp.StatusCode) } if len(out.Choices) == 0 { return "", fmt.Errorf("响应里没有 choices") } return out.Choices[0].Message.Content, nil } // translateSystem 是文档翻译的系统提示。 const translateSystem = `你是 Go 文档翻译助手。把用户给的 godoc 英文文档翻译成简体中文: - 代码标识符(函数名、类型名、包名、字段名、参数名)原样保留,不翻译 - 术语符合 Go 中文社区惯例(如 operand 译作操作数、slice 译作切片) - 译文简洁通顺,只输出译文本身,不要任何解释或前后缀` // TranslateDoc 把一段 godoc 文档翻译成简体中文。 func TranslateDoc(ctx context.Context, cfg Config, text string) (string, error) { ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() return Chat(ctx, cfg, translateSystem, text) }