47 lines
1.8 KiB
Python
47 lines
1.8 KiB
Python
# Copyright 2026 zhaoxi826
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
import docker
|
|
from typing import Dict, Any
|
|
|
|
class DockerSandboxTool:
|
|
def __init__(self):
|
|
try:
|
|
self.client = docker.from_env()
|
|
except Exception as e:
|
|
self.client = None
|
|
print(f"Failed to initialize Docker client: {e}")
|
|
|
|
def run_code(self, code: str, image: str = "python:3.9-slim") -> Dict[str, Any]:
|
|
if not self.client:
|
|
return {"error": "Docker client not initialized"}
|
|
|
|
try:
|
|
# Simple python code runner in a container
|
|
container = self.client.containers.run(
|
|
image,
|
|
command=["python", "-c", code],
|
|
remove=True,
|
|
detach=False,
|
|
stdout=True,
|
|
stderr=True
|
|
)
|
|
# Depending on python version, container returns bytes directly
|
|
output = container.decode("utf-8") if isinstance(container, bytes) else container
|
|
return {"status": "success", "output": output}
|
|
except docker.errors.ContainerError as e:
|
|
return {"status": "error", "output": e.stderr.decode("utf-8")}
|
|
except Exception as e:
|
|
return {"status": "error", "error": str(e)}
|