DeterministicJSON 提供确定性的 JSON 序列化 主要用于 KV-Cache 优化:确保相同的数据结构总是生成相同的 JSON 输出 Go 的 map 迭代顺序是随机的,这会导致: - 相同内容的 JSON 输出不同 - LLM Provider 的 KV-Cache 失效 - 成本增加 10x(根据 Manus 团队数据) 此包通过递归排序 map 的 key 来解决这个问题 MarshalDeterministic 确定性地序列化为 JSON 对于 map 类型,会按 key 字典序排序
(v any)
| 20 | // MarshalDeterministic 确定性地序列化为 JSON |
| 21 | // 对于 map 类型,会按 key 字典序排序 |
| 22 | func MarshalDeterministic(v any) ([]byte, error) { |
| 23 | normalized := normalizeValue(reflect.ValueOf(v)) |
| 24 | return json.Marshal(normalized) |
| 25 | } |
| 26 | |
| 27 | // MarshalDeterministicIndent 确定性地序列化为格式化的 JSON |
| 28 | func MarshalDeterministicIndent(v any, prefix, indent string) ([]byte, error) { |