Files
MyGolandRelease/internal/ai/llm.go
T
zerorigin f401c3de85 feat: 补全文档中文翻译(LLM,OpenAI 兼容接口)
补全列表底部的英文 godoc 翻译成中文:
- internal/ai: OpenAI 兼容最小客户端 + TranslateDoc(保留代码标识符)
- app 层 docTranslation: 内存+磁盘缓存、inflight 去重、失败哨兵防重复请求
- 自定义补全面板渲染(RenderCompletions 钩子),文档区异步换译文,
  不重送候选列表、不打断选择状态
- 设置新增「文档翻译」:开关 + 接口地址/API Key/模型 三件套,
  兼容 DeepSeek/GLM/Ollama/OpenAI 等,没配齐时静默关闭
2026-11-04 17:10:05 +08:00

112 lines
3.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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)
}