adk_tool/code_execution/
python_code_tool.rs1use adk_code::{
15 CodeExecutor, ContainerCommandExecutor, ContainerConfig, ExecutionLanguage, ExecutionPayload,
16 ExecutionRequest, SandboxPolicy,
17};
18use adk_core::{Result, Tool, ToolContext};
19use async_trait::async_trait;
20use serde_json::{Value, json};
21use std::sync::Arc;
22
23pub struct PythonCodeTool {
39 executor: Arc<dyn CodeExecutor>,
40}
41
42impl PythonCodeTool {
43 pub fn new() -> Self {
45 Self {
46 executor: Arc::new(ContainerCommandExecutor::new(ContainerConfig {
47 default_image: "python:3.12-slim".to_string(),
48 ..ContainerConfig::default()
49 })),
50 }
51 }
52
53 pub fn with_executor(executor: Arc<dyn CodeExecutor>) -> Self {
55 Self { executor }
56 }
57
58 pub fn with_config(config: ContainerConfig) -> Self {
60 Self { executor: Arc::new(ContainerCommandExecutor::new(config)) }
61 }
62}
63
64impl Default for PythonCodeTool {
65 fn default() -> Self {
66 Self::new()
67 }
68}
69
70#[async_trait]
71impl Tool for PythonCodeTool {
72 fn name(&self) -> &str {
73 "python_code"
74 }
75
76 fn description(&self) -> &str {
77 "Execute Python code in an isolated container. \
78 Suitable for data processing, scripting, and general-purpose computation. \
79 Print results as JSON to stdout using json.dumps()."
80 }
81
82 fn required_scopes(&self) -> &[&str] {
83 &["code:execute", "code:execute:container"]
84 }
85
86 fn parameters_schema(&self) -> Option<Value> {
87 Some(json!({
88 "type": "object",
89 "properties": {
90 "code": {
91 "type": "string",
92 "description": "Python source code to execute."
93 },
94 "input": {
95 "description": "Optional JSON value passed via stdin."
96 }
97 },
98 "required": ["code"]
99 }))
100 }
101
102 async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
103 let code = args["code"]
104 .as_str()
105 .ok_or_else(|| adk_core::AdkError::tool("missing 'code' parameter"))?
106 .to_string();
107
108 let input = args.get("input").cloned();
109
110 let request = ExecutionRequest {
111 language: ExecutionLanguage::Python,
112 payload: ExecutionPayload::Source { code },
113 argv: vec![],
114 stdin: None,
115 input,
116 sandbox: SandboxPolicy::strict_rust(),
117 identity: None,
118 };
119
120 let result = self
121 .executor
122 .execute(request)
123 .await
124 .map_err(|e| adk_core::AdkError::tool(format!("Python execution failed: {e}")))?;
125
126 Ok(json!({
127 "status": result.status,
128 "stdout": result.stdout,
129 "stderr": result.stderr,
130 "output": result.output,
131 "exitCode": result.exit_code,
132 "durationMs": result.duration_ms,
133 }))
134 }
135}