smolagents_rs/tools/
python_interpreter.rs

1//! This module contains the Python interpreter tool. The model uses this tool to evaluate python code.
2
3use std::collections::HashMap;
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use super::base::BaseTool;
9use super::tool_traits::Tool;
10use crate::local_python_interpreter::evaluate_python_code;
11use anyhow::Result;
12
13#[derive(Deserialize, JsonSchema)]
14#[schemars(title = "PythonInterpreterToolParams")]
15pub struct PythonInterpreterToolParams {
16    #[schemars(
17        description = "The code snippet to evaluate. All variables used in this snippet must be defined in this same snippet, 
18        else you will get an error. 
19        This code can only import the following python libraries: 
20        collections, datetime, itertools, math, queue, random, re, stat, statistics, time, unicodedata"
21    )]
22    code: String,
23}
24#[derive(Debug, Serialize, Default, Clone)]
25pub struct PythonInterpreterTool {
26    pub tool: BaseTool,
27}
28
29impl PythonInterpreterTool {
30    pub fn new() -> Self {
31        PythonInterpreterTool {
32            tool: BaseTool {
33                name: "python_interpreter",
34                description:  "This is a tool that evaluates python code. It can be used to perform calculations."
35            }}
36    }
37}
38
39impl Tool for PythonInterpreterTool {
40    type Params = PythonInterpreterToolParams;
41    fn name(&self) -> &'static str {
42        self.tool.name
43    }
44    fn description(&self) -> &'static str {
45        self.tool.description
46    }
47    fn forward(&self, arguments: PythonInterpreterToolParams) -> Result<String> {
48        let result = evaluate_python_code(&arguments.code, vec![], &mut HashMap::new());
49        match result {
50            Ok(result) => Ok(format!("Evaluation Result: {}", result)),
51            Err(e) => Err(anyhow::anyhow!("Error evaluating code: {}", e)),
52        }
53    }
54}