|
| 1 | +"""Tools that provide code execution features""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import shlex |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +from jupyter_ai.tools.models import Tool, Toolkit |
| 8 | + |
| 9 | + |
| 10 | +async def bash(command: str, timeout: Optional[int] = None) -> str: |
| 11 | + """Executes a bash command and returns the result |
| 12 | +
|
| 13 | + Args: |
| 14 | + command: The bash command to execute |
| 15 | + timeout: Optional timeout in seconds |
| 16 | +
|
| 17 | + Returns: |
| 18 | + The command output (stdout and stderr combined) |
| 19 | + """ |
| 20 | + |
| 21 | + proc = await asyncio.create_subprocess_exec( |
| 22 | + *shlex.split(command), |
| 23 | + stdout=asyncio.subprocess.PIPE, |
| 24 | + stderr=asyncio.subprocess.PIPE, |
| 25 | + ) |
| 26 | + |
| 27 | + try: |
| 28 | + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout) |
| 29 | + output = stdout.decode("utf-8") |
| 30 | + error = stderr.decode("utf-8") |
| 31 | + |
| 32 | + if proc.returncode != 0: |
| 33 | + if error: |
| 34 | + return f"Error: {error}" |
| 35 | + return f"Command failed with exit code {proc.returncode}" |
| 36 | + |
| 37 | + return output if output else "Command executed successfully with no output." |
| 38 | + except asyncio.TimeoutError: |
| 39 | + proc.kill() |
| 40 | + return f"Command timed out after {timeout} seconds" |
| 41 | + |
| 42 | + |
| 43 | +toolkit = Toolkit( |
| 44 | + name="code_execution_toolkit", |
| 45 | + description="Tools to execute code in different environments.", |
| 46 | +) |
| 47 | +toolkit.add_tool(Tool(callable=bash, execute=True)) |
0 commit comments