Files
smartmate/backend/services/memory/internal/utils/extract_json.go
Losita 2a96f4c6f9 Version: 0.9.76.dev.260505
后端:
1.阶段 6 agent / memory 服务化收口
- 新增 cmd/agent 独立进程入口,承载 agent zrpc server、agent outbox relay / consumer 和运行时依赖初始化
- 补齐 services/agent/rpc 的 Chat stream 与 conversation meta/list/timeline、schedule-preview、context-stats、schedule-state unary RPC
- 新增 gateway/client/agent 与 shared/contracts/agent,将 /api/v1/agent chat 和非 chat 门面切到 agent zrpc
- 收缩 gateway 本地 AgentService 装配,双 RPC 开关开启时不再初始化本地 agent 编排、LLM、RAG 和 memory reader fallback
- 将 backend/memory 物理迁入 services/memory,私有实现收入 internal,保留 module/model/observe 作为 memory 服务门面
- 调整 memory outbox、memory reader 和 agent 记忆渲染链路的 import 与服务边界,cmd/memory 独占 memory worker / consumer
- 关闭 gateway 侧 agent outbox worker 所有权,agent relay / consumer 由 cmd/agent 独占,gateway 仅保留 HTTP/SSE 门面与迁移期开关回退
- 更新阶段 6 文档,记录 agent / memory 当前切流点、smoke 结果,以及 backend/client 与 gateway/shared 的目录收口口径
2026-05-05 19:31:39 +08:00

105 lines
2.0 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 utils
import (
"encoding/json"
"errors"
"regexp"
"strings"
)
var fencedJSONPattern = regexp.MustCompile("(?s)```(?:json)?\\s*([\\[{].*[\\]}])\\s*```")
// ExtractJSON 从模型输出中提取 JSON 文本(兼容代码块包裹)。
//
// 步骤:
// 1. 先判断整段文本是否本身就是合法 JSON
// 2. 再尝试匹配 ```json ... ``` 代码块;
// 3. 最后做一次“首个 JSON 对象/数组”扫描提取。
func ExtractJSON(raw string) (string, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return "", errors.New("empty model output")
}
// 1. 直接 JSON 命中时,避免做额外启发式扫描。
if json.Valid([]byte(trimmed)) {
return trimmed, nil
}
// 2. 兼容 markdown 代码块包裹 JSON。
matches := fencedJSONPattern.FindStringSubmatch(trimmed)
if len(matches) > 1 {
candidate := strings.TrimSpace(matches[1])
if json.Valid([]byte(candidate)) {
return candidate, nil
}
}
// 3. 兜底扫描首个完整 JSON 片段,尽量提升容错能力。
if candidate, ok := findFirstJSONSegment(trimmed); ok {
return candidate, nil
}
return "", errors.New("json not found in model output")
}
func findFirstJSONSegment(raw string) (string, bool) {
start := -1
var open, close rune
for i, ch := range raw {
if ch == '{' {
start = i
open = '{'
close = '}'
break
}
if ch == '[' {
start = i
open = '['
close = ']'
break
}
}
if start < 0 {
return "", false
}
depth := 0
inString := false
escaped := false
for i, ch := range raw[start:] {
if inString {
if escaped {
escaped = false
continue
}
if ch == '\\' {
escaped = true
continue
}
if ch == '"' {
inString = false
}
continue
}
if ch == '"' {
inString = true
continue
}
if ch == open {
depth++
continue
}
if ch == close {
depth--
if depth == 0 {
candidate := strings.TrimSpace(raw[start : start+i+1])
if json.Valid([]byte(candidate)) {
return candidate, true
}
return "", false
}
}
}
return "", false
}