adk_code/vertex_sandbox/
tool.rs1use super::errors;
4use super::executor::SandboxCodeExecutor;
5use super::types::InputFile;
6use adk_core::{Result, Tool, ToolContext};
7use async_trait::async_trait;
8use base64::Engine as _;
9use base64::engine::general_purpose::STANDARD as BASE64;
10use serde_json::{Value, json};
11use std::sync::Arc;
12use tracing::debug;
13
14const DEFAULT_FILE_MIME_TYPE: &str = "application/octet-stream";
16
17pub struct VertexSandboxTool {
44 executor: Arc<SandboxCodeExecutor>,
45}
46
47impl VertexSandboxTool {
48 pub fn new(executor: Arc<SandboxCodeExecutor>) -> Self {
50 Self { executor }
51 }
52}
53
54#[async_trait]
55impl Tool for VertexSandboxTool {
56 fn name(&self) -> &str {
57 "vertex_sandbox_code_execution"
58 }
59
60 fn description(&self) -> &str {
61 "Executes code in a managed Vertex AI Agent Engine sandbox. Pass the source in 'code' \
62 and optional input files in 'files' (name, mimeType, dataBase64). Returns stdout, \
63 stderr, and any files the code wrote. State persists across calls in the same session."
64 }
65
66 fn is_long_running(&self) -> bool {
67 true
68 }
69
70 fn parameters_schema(&self) -> Option<Value> {
71 Some(json!({
72 "type": "object",
73 "properties": {
74 "code": {
75 "type": "string",
76 "description": "Source code to execute in the sandbox.",
77 },
78 "files": {
79 "type": "array",
80 "description": "Input files made available to the code.",
81 "items": {
82 "type": "object",
83 "properties": {
84 "name": { "type": "string", "description": "Filename the code sees." },
85 "mimeType": { "type": "string", "description": "MIME type of the file." },
86 "dataBase64": { "type": "string", "description": "Base64-encoded file bytes." },
87 },
88 "required": ["name", "dataBase64"],
89 },
90 },
91 },
92 "required": ["code"],
93 }))
94 }
95
96 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
97 let errors = errors();
98 let code = args.get("code").and_then(Value::as_str).ok_or_else(|| {
99 errors.invalid_input(
100 "vertex sandbox tool requires a string 'code' argument with the source to execute",
101 )
102 })?;
103
104 let mut files = Vec::new();
105 if let Some(entries) = args.get("files").filter(|value| !value.is_null()) {
106 let entries = entries.as_array().ok_or_else(|| {
107 errors.invalid_input(
108 "vertex sandbox tool 'files' must be an array of {name, mimeType, dataBase64} objects",
109 )
110 })?;
111 for entry in entries {
112 let name = entry
113 .get("name")
114 .and_then(Value::as_str)
115 .filter(|name| !name.trim().is_empty())
116 .ok_or_else(|| {
117 errors.invalid_input(
118 "every vertex sandbox input file needs a non-empty 'name'",
119 )
120 })?;
121 let mime_type =
122 entry.get("mimeType").and_then(Value::as_str).unwrap_or(DEFAULT_FILE_MIME_TYPE);
123 let data = entry.get("dataBase64").and_then(Value::as_str).ok_or_else(|| {
124 errors.invalid_input(format!(
125 "vertex sandbox input file '{name}' needs a base64 string 'dataBase64'",
126 ))
127 })?;
128 let bytes = BASE64.decode(data).map_err(|error| {
129 errors.invalid_input(format!(
130 "vertex sandbox input file '{name}' dataBase64 is not valid base64: {error}",
131 ))
132 })?;
133 files.push(InputFile::new(name, mime_type, bytes));
134 }
135 }
136
137 let session_key = format!("{}/{}/{}", ctx.app_name(), ctx.user_id(), ctx.session_id());
138 debug!(session.key = session_key.as_str(), "executing code in vertex sandbox");
139 let result = self.executor.execute_for_session(&session_key, code, &files).await?;
140
141 let output_files: Vec<Value> = result
142 .output_files
143 .iter()
144 .map(|file| {
145 json!({
146 "name": file.name,
147 "mimeType": file.mime_type,
148 "dataBase64": BASE64.encode(&file.data),
149 })
150 })
151 .collect();
152 Ok(json!({
153 "stdout": result.stdout,
154 "stderr": result.stderr,
155 "outputFiles": output_files,
156 }))
157 }
158}