PTC 基础示例 演示如何使用 Programmatic Tool Calling 让 LLM 生成 Python 代码并调用工具
()
| 16 | // PTC 基础示例 |
| 17 | // 演示如何使用 Programmatic Tool Calling 让 LLM 生成 Python 代码并调用工具 |
| 18 | func main() { |
| 19 | // 检查 API Key |
| 20 | apiKey := os.Getenv("ANTHROPIC_API_KEY") |
| 21 | if apiKey == "" { |
| 22 | log.Fatal("请设置环境变量 ANTHROPIC_API_KEY") |
| 23 | } |
| 24 | |
| 25 | // 1. 创建工具注册表并注册内置工具 |
| 26 | registry := tools.NewRegistry() |
| 27 | builtin.RegisterAll(registry) |
| 28 | |
| 29 | // 2. 创建 ToolBridge 用于程序化工具调用 |
| 30 | toolBridge := bridge.NewToolBridge(registry) |
| 31 | |
| 32 | // 3. 创建 CodeExecute 工具并启用 PTC 支持 |
| 33 | codeExecTool := builtin.NewCodeExecuteToolWithBridge(toolBridge) |
| 34 | |
| 35 | // 可选: 自定义桥接服务器地址 |
| 36 | // codeExecTool.SetBridgeURL("http://localhost:9000") |
| 37 | |
| 38 | // 4. 创建工具实例 |
| 39 | readTool, _ := registry.Create("Read", nil) |
| 40 | writeTool, _ := registry.Create("Write", nil) |
| 41 | globTool, _ := registry.Create("Glob", nil) |
| 42 | bashTool, _ := registry.Create("Bash", nil) |
| 43 | |
| 44 | // 5. 转换为 Provider ToolSchema (添加 AllowedCallers 支持) |
| 45 | toolSchemas := []provider.ToolSchema{ |
| 46 | { |
| 47 | Name: "CodeExecute", |
| 48 | Description: codeExecTool.Description(), |
| 49 | InputSchema: codeExecTool.InputSchema(), |
| 50 | // CodeExecute 只能被 LLM 直接调用 |
| 51 | AllowedCallers: []string{"direct"}, |
| 52 | }, |
| 53 | { |
| 54 | Name: "Read", |
| 55 | Description: readTool.Description(), |
| 56 | InputSchema: readTool.InputSchema(), |
| 57 | // Read 可以被 LLM 直接调用,也可以在 Python 代码中调用 |
| 58 | AllowedCallers: []string{"direct", "code_execution_20250825"}, |
| 59 | }, |
| 60 | { |
| 61 | Name: "Write", |
| 62 | Description: writeTool.Description(), |
| 63 | InputSchema: writeTool.InputSchema(), |
| 64 | AllowedCallers: []string{"direct", "code_execution_20250825"}, |
| 65 | }, |
| 66 | { |
| 67 | Name: "Glob", |
| 68 | Description: globTool.Description(), |
| 69 | InputSchema: globTool.InputSchema(), |
| 70 | AllowedCallers: []string{"direct", "code_execution_20250825"}, |
| 71 | }, |
| 72 | { |
| 73 | Name: "Bash", |
| 74 | Description: bashTool.Description(), |
| 75 | InputSchema: bashTool.InputSchema(), |
nothing calls this directly
no test coverage detected