feat: 补全文档中文翻译(LLM,OpenAI 兼容接口)
补全列表底部的英文 godoc 翻译成中文: - internal/ai: OpenAI 兼容最小客户端 + TranslateDoc(保留代码标识符) - app 层 docTranslation: 内存+磁盘缓存、inflight 去重、失败哨兵防重复请求 - 自定义补全面板渲染(RenderCompletions 钩子),文档区异步换译文, 不重送候选列表、不打断选择状态 - 设置新增「文档翻译」:开关 + 接口地址/API Key/模型 三件套, 兼容 DeepSeek/GLM/Ollama/OpenAI 等,没配齐时静默关闭
This commit is contained in:
1 parent
83abecd607
commit
f401c3de85
7 files changed
+467
No files matched your search
@@ -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)
|
||||
}
|
||||
@@ -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("缺模型不应可用")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user