feat: 补全文档中文翻译(LLM,OpenAI 兼容接口)

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

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
// 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)
}
+108
View File
@@ -0,0 +1,108 @@
package ai
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// TestChatOK 用 httptest 模拟 OpenAI 兼容服务,验证请求装配与响应解析。
func TestChatOK(t *testing.T) {
var gotPath, gotAuth, gotBody string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
gotAuth = r.Header.Get("Authorization")
b := make([]byte, r.ContentLength)
_, _ = r.Body.Read(b)
gotBody = string(b)
_ = json.NewEncoder(w).Encode(map[string]any{
"choices": []map[string]any{
{"message": map[string]string{"role": "assistant", "content": "操作数"}},
},
})
}))
defer srv.Close()
cfg := Config{BaseURL: srv.URL + "/v1", APIKey: "sk-test", Model: "test-chat"}
out, err := Chat(context.Background(), cfg, "sys", "hello")
if err != nil {
t.Fatalf("Chat: %v", err)
}
if out != "操作数" {
t.Fatalf("回复 = %q, want 操作数", out)
}
if gotPath != "/v1/chat/completions" {
t.Fatalf("路径 = %q", gotPath)
}
if gotAuth != "Bearer sk-test" {
t.Fatalf("鉴权头 = %q", gotAuth)
}
var req chatRequest
if err := json.Unmarshal([]byte(gotBody), &req); err != nil {
t.Fatalf("请求体解析: %v", err)
}
if req.Model != "test-chat" || req.Stream || len(req.Messages) != 2 {
t.Fatalf("请求体不对: %+v", req)
}
if req.Messages[0].Role != "system" || req.Messages[1].Content != "hello" {
t.Fatalf("消息不对: %+v", req.Messages)
}
}
// TestChatAPIError 服务端返回 error 结构时应当透出它的消息。
func TestChatAPIError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_ = json.NewEncoder(w).Encode(map[string]any{
"error": map[string]string{"message": "Invalid API key"},
})
}))
defer srv.Close()
cfg := Config{BaseURL: srv.URL, APIKey: "bad", Model: "m"}
_, err := Chat(context.Background(), cfg, "s", "u")
if err == nil || !strings.Contains(err.Error(), "Invalid API key") {
t.Fatalf("应透出服务端错误消息,实际: %v", err)
}
}
// TestTranslateDocPrompt 确认翻译走的是 Chat 且带上了原文。
func TestTranslateDocPrompt(t *testing.T) {
var userContent string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req chatRequest
_ = json.NewDecoder(r.Body).Decode(&req)
if len(req.Messages) == 2 {
userContent = req.Messages[1].Content
}
_ = json.NewEncoder(w).Encode(map[string]any{
"choices": []map[string]any{
{"message": map[string]string{"content": "译文"}},
},
})
}))
defer srv.Close()
cfg := Config{BaseURL: srv.URL, APIKey: "k", Model: "m"}
out, err := TranslateDoc(context.Background(), cfg, "Append formats using...")
if err != nil {
t.Fatalf("TranslateDoc: %v", err)
}
if out != "译文" || userContent != "Append formats using..." {
t.Fatalf("out=%q user=%q", out, userContent)
}
}
// TestReady 配置不齐时应判为不可用。
func TestReady(t *testing.T) {
full := Config{BaseURL: "x", APIKey: "y", Model: "z"}
if !full.Ready() {
t.Fatal("完整配置应可用")
}
if (Config{BaseURL: "x", APIKey: "y"}).Ready() {
t.Fatal("缺模型不应可用")
}
}
+9
View File
@@ -176,6 +176,11 @@ type App struct {
setDlg settings
applied settings
setOpen bool
// trans 是补全文档的译文缓存(原文→译文,空串哨兵表示同会话内翻译
// 失败过、不再重试),transInflight 去重进行中的请求。见 translate.go。
trans map[string]string
transInflight map[string]bool
// wantFocus 表示下一帧要把焦点交回编辑器(弹窗/面板关闭后)。
wantFocus bool
@@ -270,6 +275,8 @@ func New() *App {
// 设置是跨工作区的,构造时就装好,新文档直接按它排版。
a.set = loadSettings()
a.applied = a.set
// 译文缓存也是跨工作区的:标准库文档固定,重启后秒出译文。
a.loadTranslations()
if a.set.Light {
a.light = true
a.th = theme(true)
@@ -527,6 +534,8 @@ func (a *App) newDoc(abs, text string) *Doc {
d.st.OnCompletion = func(r editor.CompletionRequest) { a.complete(d, r) }
d.st.OnHover = func(r editor.HoverRequest) { a.hover(d, r) }
d.st.OnDefinition = func(off int) { a.definition(d, off) }
// 补全面板自定义渲染:底部文档接 LLM 中文翻译(见 completion.go)。
d.st.RenderCompletions = a.renderCompletions
// 编辑器级的快捷键在这里拦。OnInput 在编辑器处理之前收到按键,
// 返回 true 表示已消费。
//
+52
View File
@@ -0,0 +1,52 @@
package app
import (
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/editor"
)
// completionRows 是候选列表最多显示的行数(与编辑器默认一致)。
const completionRows = 200
// renderCompletions 复刻编辑器默认的补全面板,把底部文档换成中文译文:
// 选中文档时异步发起 LLM 翻译(带缓存),译好后的下一帧自动显示。
// 没配 AI 或还没译回来就显示英文原文,不阻塞选择。
//
// 为什么整面板接管:编辑器只给了整面板的渲染钩子(RenderCompletions),
// 没有「只换文档区」的粒度;列表部分照抄 DefaultCompletions,
// 选择/点击/滚动的交互都还在 m(CompletionMenu)里,不丢功能。
func (a *App) renderCompletions(c *ui.Context, panel ui.Element, m *editor.CompletionMenu) {
t := c.Theme()
ct := m.Theme()
font := m.Font()
lh := m.LineHeight()
panel.Background(t.Surface).Border(1, t.Border).Radius(t.Radius).Shadow(0, 4, 16, 0, ui.RGBA(0, 0, 0, 0.2)).
Padding(t.Space(1)).MaxHeight(lh*9 + t.Space(2)).MinWidth(t.Space(60)).MaxWidth(t.Space(150))
items := m.Items()
panel.Children(func() {
ui.Scroll(c).Key("rows").MaxHeight(lh * 9).Children(func() {
for i, it := range items {
if i >= completionRows {
break
}
row := m.Item(i).Row().Justify(ui.Start).Gap(t.Space(2)).AlignItems(ui.Center).Padding(t.Space(0.5), t.Space(1.5)).
Radius(t.Radius - 2).Height(lh + 2)
if i == m.Selected() {
row.Background(t.Accent.Alpha(0.18))
}
row.Children(func() {
ui.Text(c, it.Kind.Icon()).Font("monospace").FontSize(font.Size - 1).TextColor(ct.TokenColor(it.Kind.Token())).Width(t.Space(3))
ui.Text(c, it.Label).Font(font.Family).FontSize(font.Size).TextColor(ct.Text).SingleLine().Shrink(1)
if it.Detail != "" {
ui.Text(c, it.Detail).FontSize(font.Size - 1).TextColor(t.TextMuted).SingleLine().Shrink(1).Grow(1).TextAlign(ui.End)
}
})
}
})
if s := m.Selected(); s < len(items) && items[s].Documentation != "" {
ui.Box(c).Height(1).Background(t.Border).Margin(t.Space(1), 0)
text := a.docTranslation(items[s].Documentation)
ui.Text(c, text).FontSize(t.FontSize - 1).TextColor(t.TextMuted).MaxWidth(t.Space(140)).Padding(t.Space(0.5), t.Space(1.5))
}
})
}
+26
View File
@@ -27,6 +27,13 @@ type settings struct {
// InlayHints 控制参数名/类型这类内联提示。
// 老配置文件里没有这一项,读的时候要按「默认开」处理(见 loadSettings)。
InlayHints bool `json:"inlayHints"`
// TranslateDocs 开关补全文档的中文翻译(需配好下面的 AI 接口)。
TranslateDocs bool `json:"translateDocs"`
// AI 接口三件套:OpenAI 兼容的地址、Key 与模型名,
// 如 https://api.deepseek.com/v1 + sk-xxx + deepseek-chat。
AIBaseURL string `json:"aiBaseUrl"`
AIAPIKey string `json:"aiApiKey"`
AIModel string `json:"aiModel"`
}
// defaultSettings 是没配置过时的取值,和改动前的硬编码保持一致。
@@ -43,6 +50,7 @@ func defaultSettings() settings {
History: true,
AutoSnapshot: true,
InlayHints: true,
TranslateDocs: true,
}
}
@@ -181,6 +189,24 @@ func (a *App) settingsDialog(c *ui.Context) {
}
})
// AI 文档翻译:补全列表底部的英文 godoc 译成中文。
row("文档翻译", func() {
ui.Checkbox(c, &a.setDlg.TranslateDocs, "补全文档翻译成中文(OpenAI 兼容接口)")
})
if a.setDlg.TranslateDocs {
row("接口地址", func() {
ui.TextInput(c, &a.setDlg.AIBaseURL).FillWidth().FontSize(12)
})
row("API Key", func() {
ui.TextInput(c, &a.setDlg.AIAPIKey).FillWidth().FontSize(12)
})
row("模型", func() {
ui.TextInput(c, &a.setDlg.AIModel).FillWidth().FontSize(12)
})
ui.Text(c, "示例:https://api.deepseek.com/v1 + deepseek-chat,或本地 Ollama http://localhost:11434/v1。").
FontSize(10).TextColor(t.TextMuted).SingleLine()
}
ui.Row(c).Gap(8).Justify(ui.End).Children(func() {
if ui.Button(c, "恢复默认").Clicked() {
a.setDlg = defaultSettings()
+118
View File
@@ -0,0 +1,118 @@
package app
import (
"context"
"encoding/json"
"os"
"path/filepath"
"time"
"mygoland/internal/ai"
)
// docTranslation 返回一段补全文档的中文译文。
//
// 没有现成译文时后台发起 LLM 翻译(同一文本只发一次),先返回英文原文——
// 补全面板是即时模式,翻译回来 win.Update 重绘,下一帧自然换上译文。
// 必须在主线程调用(读写缓存 map)。
func (a *App) docTranslation(text string) string {
if !a.translateOn() || text == "" {
return text
}
if tr, ok := a.trans[text]; ok {
if tr == "" {
// 空串哨兵:这个会话里翻译失败过,别再烧 API,直接原文。
return text
}
return tr
}
if a.transInflight[text] {
return text
}
if a.trans == nil {
a.trans = map[string]string{}
a.transInflight = map[string]bool{}
}
a.transInflight[text] = true
cfg := a.aiConfig()
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
defer cancel()
tr, err := ai.TranslateDoc(ctx, cfg, text)
a.win.Update(func() {
delete(a.transInflight, text)
if err != nil || tr == "" {
// 失败:缓存哨兵,同会话不再重试(重启后会再试)。
logf("翻译失败: %v", err)
a.trans[text] = ""
return
}
a.trans[text] = tr
a.saveTranslations()
})
}()
return text
}
// translateOn 判断文档翻译是否可用:开了开关且三件套配齐。
func (a *App) translateOn() bool {
s := a.set
return s.TranslateDocs && ai.Config{
BaseURL: s.AIBaseURL, APIKey: s.AIAPIKey, Model: s.AIModel,
}.Ready()
}
// aiConfig 从设置里取 AI 接口配置。
func (a *App) aiConfig() ai.Config {
return ai.Config{BaseURL: a.set.AIBaseURL, APIKey: a.set.AIAPIKey, Model: a.set.AIModel}
}
// translationsPath 是译文缓存文件。
func translationsPath() string {
dir := sessionDir()
if dir == "" {
return ""
}
return filepath.Join(dir, "translations.json")
}
// loadTranslations 启动时装载译文缓存:标准库文档是固定的,重启后秒出译文。
func (a *App) loadTranslations() {
p := translationsPath()
if p == "" {
return
}
b, err := os.ReadFile(p)
if err != nil {
return
}
var m map[string]string
if err := json.Unmarshal(b, &m); err != nil {
return
}
a.trans = map[string]string{}
for k, v := range m {
if k != "" && v != "" {
a.trans[k] = v
}
}
}
// saveTranslations 把译文缓存落盘(空串哨兵不存,重启后失败的可重试)。
func (a *App) saveTranslations() {
p := translationsPath()
if p == "" || len(a.trans) == 0 {
return
}
m := map[string]string{}
for k, v := range a.trans {
if v != "" {
m[k] = v
}
}
b, err := json.MarshalIndent(m, "", " ")
if err != nil {
return
}
_ = os.WriteFile(p, b, 0o644)
}