Execute 实现 Tool 接口(带缓存)
(ctx context.Context, input map[string]any, tc *ToolContext)
| 497 | |
| 498 | // Execute 实现 Tool 接口(带缓存) |
| 499 | func (ct *CachedTool) Execute(ctx context.Context, input map[string]any, tc *ToolContext) (any, error) { |
| 500 | // 生成缓存键 |
| 501 | key := ct.cache.GenerateKey(ct.tool.Name(), input) |
| 502 | |
| 503 | // 尝试从缓存获取 |
| 504 | if cached, ok := ct.cache.Get(ctx, key); ok { |
| 505 | return cached, nil |
| 506 | } |
| 507 | |
| 508 | // 执行工具 |
| 509 | result, err := ct.tool.Execute(ctx, input, tc) |
| 510 | if err != nil { |
| 511 | return nil, err |
| 512 | } |
| 513 | |
| 514 | // 缓存结果 |
| 515 | if err := ct.cache.Set(ctx, key, result, ct.cache.config.TTL); err != nil { |
| 516 | // 缓存失败不影响结果返回,只记录错误 |
| 517 | _ = err // 忽略缓存错误 |
| 518 | } |
| 519 | |
| 520 | return result, nil |
| 521 | } |