-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathe2b_router.py
161 lines (139 loc) · 6.36 KB
/
e2b_router.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# coding=utf-8
# Copyright 2025 The HuggingFace Team. All rights reserved.
#
# 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 argparse
import asyncio
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict
from typing import Optional
from fastapi import FastAPI, Request
import argparse
import asyncio
from fastapi import FastAPI
import uvicorn
from e2b_code_interpreter.models import Execution
from dotenv import load_dotenv
from e2b_code_interpreter import AsyncSandbox
load_dotenv()
class BatchRequest(BaseModel):
"""
BatchRequest is a data model representing a batch processing request.
Attributes:
scripts (list[str]): A list of script names or paths to be executed.
language (str): The programming language in which the scripts are written.
timeout (int): The maximum allowed execution time for each script in seconds.
request_timeout (int): The maximum allowed time for the entire batch request in seconds.
"""
scripts: list[str]
language: str
timeout: int
request_timeout: int
class ScriptResult(BaseModel):
"""
ScriptResult is a Pydantic model that represents the result of a script execution.
Attributes:
execution (Optional[Execution]): An optional instance of the `Execution` class
that contains details about the script's execution, such as status, output,
or any other relevant metadata.
exception_str (Optional[str]): An optional string that captures the exception
message or details if an error occurred during the script's execution.
model_config (ConfigDict): A configuration dictionary that allows arbitrary
types to be used within the Pydantic model. This is necessary to support
custom types like `Execution` within the model.
"""
execution: Optional[Execution]
exception_str: Optional[str]
# required to allow arbitrary types in pydantic models such as Execution
model_config = ConfigDict(arbitrary_types_allowed=True)
def create_app(args):
"""
Creates and configures a FastAPI application instance.
Args:
args: An object containing configuration parameters for the application.
- num_sandboxes (int): The maximum number of concurrent sandboxes allowed.
Returns:
FastAPI: A configured FastAPI application instance.
The application includes the following endpoints:
1. GET /health:
- Returns the health status of the application.
- Response: {"status": "ok"}
2. POST /execute_batch:
- Executes a batch of scripts in an isolated sandbox environment.
- Request Body: BatchRequest object containing:
- language (str): The programming language of the scripts (python or javascript).
- timeout (int): The maximum execution time for each script.
- request_timeout (int): The timeout for the request itself.
- scripts (List[str]): A list of scripts to execute.
- Response: A list of ScriptResult objects for each script, containing:
- execution: The result of the script execution.
- exception_str: Any exception encountered during execution.
Notes:
- A semaphore is used to limit the number of concurrent sandboxes.
- Each script execution is wrapped in a timeout to prevent hanging.
- Sandboxes are cleaned up after execution, even in case of errors.
"""
app = FastAPI()
# Instantiate semaphore and attach it to app state
app.state.sandbox_semaphore = asyncio.Semaphore(args.max_num_sandboxes)
@app.get("/health")
async def health():
return {"status": "ok"}
@app.post("/execute_batch")
async def execute_batch(batch: BatchRequest, request: Request):
semaphore = request.app.state.sandbox_semaphore
language = batch.language
timeout = batch.timeout
request_timeout = batch.request_timeout
asyncio_timeout = batch.timeout + 1
async def run_script(script: str) -> ScriptResult:
async with semaphore:
try:
sandbox = await AsyncSandbox.create(
timeout=timeout,
request_timeout=request_timeout,
)
execution = await asyncio.wait_for(
sandbox.run_code(script, language=language),
timeout=asyncio_timeout,
)
return ScriptResult(execution=execution, exception_str=None)
except Exception as e:
return ScriptResult(execution=None, exception_str=str(e))
finally:
try:
await sandbox.kill()
except Exception:
pass
tasks = [run_script(script) for script in batch.scripts]
return await asyncio.gather(*tasks)
return app
def parse_args():
"""
Parse command-line arguments for the e2b_router script.
Arguments:
--host (str): The hostname or IP address to bind the server to. Defaults to "0.0.0.0" (binds to all interfaces).
--port (int): The port number on which the server will listen. Defaults to 8000.
--max_num_sandboxes (int): The maximum number of sandboxes that can be created or managed simultaneously. Defaults to 20.
Returns:
argparse.Namespace: Parsed command-line arguments as an object.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--host", default="0.0.0.0")
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--max_num_sandboxes", type=int, default=20)
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
app = create_app(args)
uvicorn.run(app, host=args.host, port=args.port)