diff --git a/src/codeinterpreterapi/main.py b/src/codeinterpreterapi/main.py new file mode 100644 index 0000000..a54282d --- /dev/null +++ b/src/codeinterpreterapi/main.py @@ -0,0 +1,40 @@ +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse +import traceback +import io +import contextlib + +app = FastAPI(title="Code Interpreter API") + +@app.get("/") +async def root(): + return {"message": "🚀 Code Interpreter API is running"} + +@app.post("/run") +async def run_code(request: Request): + """ + 简易 Python 代码执行接口 + Body 例子: + { + "code": "print(1+1)" + } + """ + try: + data = await request.json() + code = data.get("code", "") + if not code: + return JSONResponse({"error": "No code provided"}, status_code=400) + + # 捕获代码输出 + output_buffer = io.StringIO() + with contextlib.redirect_stdout(output_buffer): + exec(code, {}) + + result = output_buffer.getvalue() + return {"result": result.strip()} + + except Exception as e: + return JSONResponse({ + "error": str(e), + "traceback": traceback.format_exc() + }, status_code=500)