File size: 530 Bytes
aed39aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import io
import contextlib
from langchain_core.tools import tool


@tool
def python(code: str) -> str:
    """Execute Python code and return anything printed to stdout. Use print() to see results."""
    output = io.StringIO()
    try:
        with contextlib.redirect_stdout(output):
            exec(code, {})
        result = output.getvalue().strip()
        return result if result else "Code executed successfully (no output printed)."
    except Exception as e:
        return f"Python execution error: {e}"