ai_xiaopei
6 days ago 1196f409d86bc61e7596eb274840244a62ce84ba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package llm
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "path/filepath"
    "regexp"
    "strings"
    "time"
 
    "gopkg.in/yaml.v3"
)
 
// LLMConfig 单个 LLM 配置
type LLMConfig struct {
    APIBase         string  `yaml:"api_base"`
    APIKey          string  `yaml:"api_key"`
    Model           string  `yaml:"model"`
    Temperature     float64 `yaml:"temperature"`
    MaxTokens       int     `yaml:"max_tokens"`
    DisableThinking bool    `yaml:"disable_thinking"`
}
 
// Config 配置文件结构
type Config struct {
    LLM struct {
        Primary LLMConfig `yaml:"primary"`
        Fallback *LLMConfig `yaml:"fallback"`
    } `yaml:"llm"`
    KnowledgeBase struct {
        VaultPath string `yaml:"vault_path"`
        DBPath    string `yaml:"db_path"`
    } `yaml:"knowledge_base"`
    Draft struct {
        ReviewDir   string `yaml:"review_dir"`
        DefaultType string `yaml:"default_type"`
    } `yaml:"draft"`
}
 
// Client LLM 客户端
type Client struct {
    config     Config
    usePrimary bool
}
 
// ExtractResult 提取结果
type ExtractResult struct {
    Tags        []string `json:"tags"`
    RelatedDocs []string `json:"related_docs"`
}
 
// MergeHint 合并指示
type MergeHint struct {
    Recommendation struct {
        Action     string `json:"action"`
        Target     string `json:"target"`
        Reason     string `json:"reason"`
        Confidence string `json:"confidence"`
    } `json:"recommendation"`
    Analysis []struct {
        Path      string `json:"path"`
        Relevance string `json:"relevance"`
        Reason    string `json:"reason"`
    } `json:"analysis"`
}
 
// SearchCandidate 搜索候选
type SearchCandidate struct {
    Title   string  `json:"title"`
    Path    string  `json:"path"`
    Score   float64 `json:"score"`
    Content string  `json:"content,omitempty"` // 文件内容(截取前5000字)
}
 
// NewClient 创建 LLM 客户端
func NewClient() *Client {
    config := LoadConfig()
    return &Client{config: config, usePrimary: true}
}
 
// LoadConfig 加载配置文件(导出供其他包使用)
func LoadConfig() Config {
    var config Config
 
    // 配置文件路径
    homeDir, _ := os.UserHomeDir()
    configPath := filepath.Join(homeDir, ".kb-cli", "config.yaml")
 
    // 读取配置文件
    data, err := os.ReadFile(configPath)
    if err != nil {
        // 如果配置文件不存在,使用默认值
        fmt.Fprintf(os.Stderr, "警告: 无法读取配置文件 %s,使用默认值\n", configPath)
        return getDefaultConfig()
    }
 
    // 解析 YAML
    if err := yaml.Unmarshal(data, &config); err != nil {
        fmt.Fprintf(os.Stderr, "警告: 解析配置文件失败: %v,使用默认值\n", err)
        return getDefaultConfig()
    }
 
    // 展开 ~ 路径
    config.LLM.Primary.APIBase = expandPath(config.LLM.Primary.APIBase)
    config.KnowledgeBase.VaultPath = expandPath(config.KnowledgeBase.VaultPath)
    config.KnowledgeBase.DBPath = expandPath(config.KnowledgeBase.DBPath)
    if config.LLM.Fallback != nil {
        config.LLM.Fallback.APIBase = expandPath(config.LLM.Fallback.APIBase)
    }
 
    return config
}
 
// getDefaultConfig 获取默认配置
func getDefaultConfig() Config {
    var config Config
    config.LLM.Primary.APIBase = "http://192.168.3.246:1127/v1"
    config.LLM.Primary.APIKey = "sk-local"
    config.LLM.Primary.Model = "qwen3.6-35b-a3b"
    config.LLM.Primary.Temperature = 0.3
    config.LLM.Primary.MaxTokens = 2000
    config.LLM.Primary.DisableThinking = true
    config.KnowledgeBase.VaultPath = "~/aisim/note/001/笔记001"
    config.KnowledgeBase.DBPath = "~/.cache/kb-cli/kb.db"
    config.Draft.ReviewDir = "待审阅"
    config.Draft.DefaultType = "售后"
    return config
}
 
// expandPath 展开路径中的 ~
func expandPath(path string) string {
    if strings.HasPrefix(path, "~/") {
        homeDir, _ := os.UserHomeDir()
        return filepath.Join(homeDir, path[2:])
    }
    return path
}
 
// getCurrentConfig 获取当前使用的 LLM 配置
func (c *Client) getCurrentConfig() LLMConfig {
    if c.usePrimary {
        return c.config.LLM.Primary
    }
    if c.config.LLM.Fallback != nil {
        return *c.config.LLM.Fallback
    }
    return c.config.LLM.Primary
}
 
// switchToNext 切换到下一个可用的 LLM
func (c *Client) switchToNext() bool {
    if c.usePrimary && c.config.LLM.Fallback != nil {
        fmt.Fprintf(os.Stderr, "主 LLM 不可用,切换到备用 LLM\n")
        c.usePrimary = false
        return true
    }
    return false
}
 
// ExtractTags 提取 tags 和相关文档
func (c *Client) ExtractTags(content string) (*ExtractResult, error) {
    prompt := fmt.Sprintf(`分析以下知识库草稿,提取:
1. tags(5-10个):
   - 核心问题标签(如"充不进气"、"档案下载失败")
   - 扩展词(不同人可能的描述,如"充气慢"、"进气不足")
   - 平台/设备标签(如"电子秤平台"、"智能枪")
2. related_docs(0-5个):相关文档标题(用于创建链接)
 
输出 JSON:
{
  "tags": ["充不进气", "充气慢", "进气不足", "智能枪", "电子秤平台"],
  "related_docs": ["智能枪通气杆卡住漏气", "角阀充装功率不足"]
}
 
草稿内容:
%s`, content)
 
    response, err := c.callLLMWithRetry(prompt)
    if err != nil {
        return nil, err
    }
 
    // 解析 JSON
    var result ExtractResult
    if err := parseJSON(response, &result); err != nil {
        return nil, fmt.Errorf("解析 LLM 响应失败: %w", err)
    }
 
    return &result, nil
}
 
// GenerateMergeHint 生成合并指示
func (c *Client) GenerateMergeHint(draftContent string, candidates []SearchCandidate, dirStructure string) (*MergeHint, error) {
    prompt := fmt.Sprintf(`你是一个知识库管理助手。请判断以下草稿与哪些知识库文档相关。
 
## 知识库目录结构
%s
 
## 草稿内容
%s
 
## 候选文档(Top 3)
`, dirStructure, draftContent)
 
    for i, cand := range candidates {
        prompt += fmt.Sprintf("### %d. %s\n", i+1, cand.Title)
        prompt += fmt.Sprintf("- 路径: %s\n", cand.Path)
        prompt += fmt.Sprintf("- 相关度: %.2f\n\n", cand.Score)
        if cand.Content != "" {
            prompt += fmt.Sprintf("**文档内容**:\n```\n%s\n```\n\n", cand.Content)
        }
    }
 
    prompt += `
## 任务
请分析草稿与每个候选文档的相关性,输出 JSON 格式:
 
{
  "recommendation": {
    "action": "merge|new|split",
    "target": "目标路径(如果 action=merge,必须是上述目录结构中存在的目录)",
    "reason": "判断理由",
    "confidence": "high|medium|low"
  },
  "analysis": [
    {
      "path": "文档路径",
      "relevance": "high|medium|low",
      "reason": "相关性说明"
    }
  ]
}
 
判断标准:
- action=merge: 草稿内容与某个候选文档高度相关,应该合并
- action=new: 草稿内容是全新的,应该新建文档(target 填写建议的目录路径)
- action=split: 草稿内容包含多个独立主题,应该拆分
- confidence=high: 判断很确定
- confidence=medium: 判断比较确定
- confidence=low: 判断不太确定
 
分类原则:
- 平台专属内容放对应平台目录下(如电子秤平台/智能枪/)
- 多平台共用的硬件知识放 共有硬件/ 下
- 跨平台通用知识放 通用/通用/
 
只输出 JSON,不要其他内容。`
 
    response, err := c.callLLMWithRetry(prompt)
    if err != nil {
        return nil, err
    }
 
    var result MergeHint
    if err := parseJSON(response, &result); err != nil {
        return nil, fmt.Errorf("解析 LLM 响应失败: %w", err)
    }
 
    return &result, nil
}
 
// GenerateReviewPreview 生成审阅预览概要(3句话概括目标FAQ)
func (c *Client) GenerateReviewPreview(targetTitle, targetContent string) (string, error) {
    // 截取前2000字符作为上下文
    contentPreview := targetContent
    if len(contentPreview) > 2000 {
        contentPreview = contentPreview[:2000] + "..."
    }
 
    prompt := fmt.Sprintf(`请用3句话概括以下知识库文档的核心内容,帮助用户快速了解这个文档讲的是什么:
 
## 文档标题
%s
 
## 文档内容(部分)
%s
 
要求:
1. 第一句:这个文档解决什么问题/讲什么主题
2. 第二句:核心内容/关键要点
3. 第三句:适用场景/使用条件
 
直接输出3句话,不要编号,不要其他内容。`, targetTitle, contentPreview)
 
    response, err := c.callLLMWithRetry(prompt)
    if err != nil {
        return "", err
    }
 
    return strings.TrimSpace(response), nil
}
 
// ClassifyDocuments 分类文档
func (c *Client) ClassifyDocuments(prompt string) (string, error) {
    response, err := c.callLLMWithRetry(prompt)
    if err != nil {
        return "", err
    }
 
    // 解析 JSON
    var result []struct {
        Path        string  `json:"path"`
        Platform    string  `json:"platform"`
        Device      string  `json:"device"`
        ContentType string  `json:"content_type"`
        Confidence  float64 `json:"confidence"`
    }
 
    if err := parseJSON(response, &result); err != nil {
        return "", fmt.Errorf("解析 LLM 响应失败: %w", err)
    }
 
    // 转换回 JSON 字符串
    jsonBytes, err := json.Marshal(result)
    if err != nil {
        return "", err
    }
 
    return string(jsonBytes), nil
}
 
// ClassifyDocuments 分类文档
 
// callLLMWithRetry 带重试的 LLM 调用
func (c *Client) callLLMWithRetry(prompt string) (string, error) {
    // 第一次尝试
    response, err := c.callLLM(prompt)
    if err == nil {
        return response, nil
    }
 
    // 判断是否是需要切换的错误
    if shouldSwitchLLM(err) {
        // 尝试切换到备用 LLM
        if c.switchToNext() {
            fmt.Fprintf(os.Stderr, "重试备用 LLM...\n")
            response, err = c.callLLM(prompt)
            if err == nil {
                return response, nil
            }
        }
    }
 
    return "", err
}
 
// shouldSwitchLLM 判断是否应该切换到备用 LLM
func shouldSwitchLLM(err error) bool {
    errMsg := err.Error()
    // 网络错误、超时、认证失败等应该切换
    return strings.Contains(errMsg, "connection") ||
        strings.Contains(errMsg, "timeout") ||
        strings.Contains(errMsg, "401") ||
        strings.Contains(errMsg, "403") ||
        strings.Contains(errMsg, "500") ||
        strings.Contains(errMsg, "502") ||
        strings.Contains(errMsg, "503") ||
        strings.Contains(errMsg, "504")
}
 
// callLLM 调用 LLM API
func (c *Client) callLLM(prompt string) (string, error) {
    llmConfig := c.getCurrentConfig()
    url := llmConfig.APIBase + "/chat/completions"
 
    payload := map[string]interface{}{
        "model": llmConfig.Model,
        "messages": []map[string]string{
            {"role": "user", "content": prompt},
        },
        "temperature": llmConfig.Temperature,
        "max_tokens":  llmConfig.MaxTokens,
    }
 
    // 如果需要禁用思考模式
    if llmConfig.DisableThinking {
        payload["chat_template_kwargs"] = map[string]bool{
            "enable_thinking": false,
        }
    }
 
    jsonData, err := json.Marshal(payload)
    if err != nil {
        return "", fmt.Errorf("序列化请求失败: %w", err)
    }
 
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        return "", fmt.Errorf("创建请求失败: %w", err)
    }
 
    req.Header.Set("Content-Type", "application/json")
    if llmConfig.APIKey != "" {
        req.Header.Set("Authorization", "Bearer "+llmConfig.APIKey)
    }
 
    client := &http.Client{Timeout: 60 * time.Second}
    resp, err := client.Do(req)
    if err != nil {
        return "", fmt.Errorf("请求失败: %w", err)
    }
    defer resp.Body.Close()
 
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return "", fmt.Errorf("读取响应失败: %w", err)
    }
 
    if resp.StatusCode != http.StatusOK {
        return "", fmt.Errorf("API 返回错误状态: %d, body: %s", resp.StatusCode, string(body))
    }
 
    // 解析响应
    var result struct {
        Choices []struct {
            Message struct {
                Content string `json:"content"`
            } `json:"message"`
        } `json:"choices"`
    }
 
    if err := json.Unmarshal(body, &result); err != nil {
        return "", fmt.Errorf("解析响应失败: %w", err)
    }
 
    if len(result.Choices) == 0 {
        return "", fmt.Errorf("API 返回空结果")
    }
 
    return result.Choices[0].Message.Content, nil
}
 
// parseJSON 解析 JSON(支持 markdown 代码块)
func parseJSON(content string, v interface{}) error {
    // 尝试提取 ```json 代码块
    re := regexp.MustCompile("(?s)```json\\s*(.*?)\\s*```")
    matches := re.FindStringSubmatch(content)
    if len(matches) > 1 {
        content = matches[1]
    }
 
    if err := json.Unmarshal([]byte(content), v); err != nil {
        return err
    }
 
    return nil
}