abox-code-interpreter 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,419 @@
1
+ import logging
2
+ import httpx
3
+
4
+ from typing import cast, Optional, Dict, overload, Union, List
5
+ from httpx import AsyncClient
6
+
7
+ from agentbox import (
8
+ AsyncSandbox as BaseAsyncSandbox,
9
+ InvalidArgumentException,
10
+ )
11
+ from agentbox.api.client_async import get_transport
12
+
13
+ from agentbox_code_interpreter.constants import (
14
+ DEFAULT_TEMPLATE,
15
+ JUPYTER_PORT,
16
+ DEFAULT_TIMEOUT,
17
+ )
18
+ from agentbox_code_interpreter.models import (
19
+ Execution,
20
+ ExecutionError,
21
+ Context,
22
+ RunCodeLanguage,
23
+ Result,
24
+ aextract_exception,
25
+ OutputHandlerWithAsync,
26
+ async_parse_output,
27
+ OutputMessage,
28
+ )
29
+ from agentbox_code_interpreter.exceptions import (
30
+ format_execution_timeout_error,
31
+ format_request_timeout_error,
32
+ format_sandbox_killed_error,
33
+ )
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ class AsyncSandbox(BaseAsyncSandbox):
39
+ """
40
+ AgentBox cloud sandbox is a secure and isolated cloud environment.
41
+
42
+ The sandbox allows you to:
43
+ - Access Linux OS
44
+ - Create, list, and delete files and directories
45
+ - Run commands
46
+ - Run isolated code
47
+ - Access the internet
48
+
49
+ See the [Code Interpreter guide](https://docs.agentbox.ru/en/sdk/code-interpreter/).
50
+
51
+ Use the `AsyncSandbox.create()` to create a new sandbox.
52
+
53
+ Example:
54
+ ```python
55
+ from agentbox_code_interpreter import AsyncSandbox
56
+ sandbox = await AsyncSandbox.create()
57
+ ```
58
+ """
59
+
60
+ default_template = DEFAULT_TEMPLATE
61
+
62
+ @property
63
+ def _jupyter_url(self) -> str:
64
+ # Honors the `sandbox_url` option and the `AGENTBOX_SANDBOX_URL` environment
65
+ # variable, same as the base SDK does for envd requests.
66
+ sandbox_url = cast(Optional[str], self.connection_config._sandbox_url)
67
+ if sandbox_url:
68
+ return sandbox_url
69
+ return f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(JUPYTER_PORT)}"
70
+
71
+ @property
72
+ def _client(self) -> AsyncClient:
73
+ # TODO: Remove later
74
+ # Use a dedicated HTTP/1.1 transport for Jupyter requests.
75
+ #
76
+ # The base SDK's shared transport now defaults to http2=True. With
77
+ # HTTP/2, multiple requests are multiplexed over a single TCP
78
+ # connection, so when a client cancels a request (e.g. the caller
79
+ # disconnects from the streaming `/execute` endpoint) the server
80
+ # may not detect the disconnect: only the HTTP/2 stream is
81
+ # cancelled, the underlying TCP connection stays open.
82
+ #
83
+ # Forcing HTTP/1.1 here keeps the 1:1 mapping between TCP
84
+ # connection and request, so client disconnects propagate to the
85
+ # server as a TCP close and long-running executions can be
86
+ # cancelled reliably. The helper also caches the transport
87
+ # per-event-loop for async.
88
+ return AsyncClient(
89
+ transport=get_transport(self.connection_config, http2=False),
90
+ )
91
+
92
+ async def _handle_connection_error(self, err: Exception) -> None:
93
+ """
94
+ Raises a descriptive exception if the connection error was caused by
95
+ the sandbox being killed mid-request. If the sandbox is still running
96
+ (or its state can't be determined), returns so the caller can re-raise
97
+ the original error.
98
+ """
99
+ try:
100
+ running = await self.is_running()
101
+ except Exception:
102
+ # The state check itself failed, so we can't tell whether the
103
+ # sandbox was killed — let the caller re-raise the original error
104
+ # instead of wrongly claiming the sandbox is gone.
105
+ return
106
+ if not running:
107
+ raise format_sandbox_killed_error() from err
108
+
109
+ @overload
110
+ async def run_code(
111
+ self,
112
+ code: str,
113
+ language: Optional[RunCodeLanguage] = None,
114
+ on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None,
115
+ on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None,
116
+ on_result: Optional[OutputHandlerWithAsync[Result]] = None,
117
+ on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None,
118
+ envs: Optional[Dict[str, str]] = None,
119
+ timeout: Optional[float] = None,
120
+ request_timeout: Optional[float] = None,
121
+ ) -> Execution:
122
+ """
123
+ Runs the code for the specified language.
124
+
125
+ Specify the `language` or `context` option to run the code as a different language or in a different `Context`.
126
+ If no language is specified, Python is used.
127
+
128
+ You can reference previously defined variables, imports, and functions in the code.
129
+
130
+ :param code: Code to execute
131
+ :param language: Language to use for code execution. If not defined, the default Python context is used.
132
+ :param on_stdout: Callback for stdout messages
133
+ :param on_stderr: Callback for stderr messages
134
+ :param on_result: Callback for the `Result` object
135
+ :param on_error: Callback for the `ExecutionError` object
136
+ :param envs: Custom environment variables
137
+ :param timeout: Timeout for the code execution in **seconds**
138
+ :param request_timeout: Timeout for the request in **seconds**
139
+
140
+ :return: `Execution` result object
141
+ """
142
+ ...
143
+
144
+ @overload
145
+ async def run_code(
146
+ self,
147
+ code: str,
148
+ context: Optional[Context] = None,
149
+ on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None,
150
+ on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None,
151
+ on_result: Optional[OutputHandlerWithAsync[Result]] = None,
152
+ on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None,
153
+ envs: Optional[Dict[str, str]] = None,
154
+ timeout: Optional[float] = None,
155
+ request_timeout: Optional[float] = None,
156
+ ) -> Execution:
157
+ """
158
+ Runs the code in the specified context, if not specified, the default context is used.
159
+
160
+ Specify the `language` or `context` option to run the code as a different language or in a different `Context`.
161
+
162
+ You can reference previously defined variables, imports, and functions in the code.
163
+
164
+ :param code: Code to execute
165
+ :param context: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language.
166
+ :param on_stdout: Callback for stdout messages
167
+ :param on_stderr: Callback for stderr messages
168
+ :param on_result: Callback for the `Result` object
169
+ :param on_error: Callback for the `ExecutionError` object
170
+ :param envs: Custom environment variables
171
+ :param timeout: Timeout for the code execution in **seconds**
172
+ :param request_timeout: Timeout for the request in **seconds**
173
+
174
+ :return: `Execution` result object
175
+ """
176
+ ...
177
+
178
+ async def run_code(
179
+ self,
180
+ code: str,
181
+ language: Optional[str] = None,
182
+ context: Optional[Context] = None,
183
+ on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None,
184
+ on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None,
185
+ on_result: Optional[OutputHandlerWithAsync[Result]] = None,
186
+ on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None,
187
+ envs: Optional[Dict[str, str]] = None,
188
+ timeout: Optional[float] = None,
189
+ request_timeout: Optional[float] = None,
190
+ ) -> Execution:
191
+ logger.debug(f"Executing code {code}")
192
+
193
+ if context and language:
194
+ raise InvalidArgumentException(
195
+ "You can provide context or language, but not both at the same time."
196
+ )
197
+
198
+ timeout = None if timeout == 0 else (timeout or DEFAULT_TIMEOUT)
199
+ request_timeout = request_timeout or self.connection_config.request_timeout
200
+ context_id = context.id if context else None
201
+ try:
202
+ headers = {
203
+ "Content-Type": "application/json",
204
+ "Agentbox-Sandbox-Id": self.sandbox_id,
205
+ "Agentbox-Sandbox-Port": str(JUPYTER_PORT),
206
+ }
207
+ if self._envd_access_token:
208
+ headers["X-Access-Token"] = self._envd_access_token
209
+ if self.traffic_access_token:
210
+ headers["Agentbox-Traffic-Access-Token"] = self.traffic_access_token
211
+
212
+ async with self._client.stream(
213
+ "POST",
214
+ f"{self._jupyter_url}/execute",
215
+ json={
216
+ "code": code,
217
+ "context_id": context_id,
218
+ "language": language,
219
+ "env_vars": envs,
220
+ },
221
+ headers=headers,
222
+ # `timeout` bounds the execution, `request_timeout` only the
223
+ # connect. Every non-connect phase must carry `timeout`: the
224
+ # SDK's pyqwest-backed transport collapses the per-phase
225
+ # timeouts into a single whole-request deadline and takes the
226
+ # longest of them, so leaving `request_timeout` on the write
227
+ # and pool phases would raise the floor to
228
+ # `max(timeout, request_timeout)` and silently ignore any
229
+ # `timeout` shorter than it. This matches the JS SDK, which
230
+ # aborts the execution on a `timeout`-long timer.
231
+ # `timeout=0` disables the deadline entirely; the transport
232
+ # still bounds connect on its own.
233
+ timeout=(
234
+ httpx.Timeout(timeout, connect=request_timeout)
235
+ if timeout is not None
236
+ else httpx.Timeout(None)
237
+ ),
238
+ ) as response:
239
+ err = await aextract_exception(response)
240
+ if err:
241
+ raise err
242
+
243
+ execution = Execution()
244
+
245
+ async for line in response.aiter_lines():
246
+ await async_parse_output(
247
+ execution,
248
+ line,
249
+ on_stdout=on_stdout,
250
+ on_stderr=on_stderr,
251
+ on_result=on_result,
252
+ on_error=on_error,
253
+ )
254
+
255
+ return execution
256
+ except httpx.ReadTimeout:
257
+ raise format_execution_timeout_error()
258
+ except httpx.TimeoutException:
259
+ raise format_request_timeout_error()
260
+ except (httpx.ReadError, httpx.RemoteProtocolError) as err:
261
+ await self._handle_connection_error(err)
262
+ raise
263
+
264
+ async def create_code_context(
265
+ self,
266
+ cwd: Optional[str] = None,
267
+ language: Optional[RunCodeLanguage] = None,
268
+ request_timeout: Optional[float] = None,
269
+ ) -> Context:
270
+ """
271
+ Creates a new context to run code in.
272
+
273
+ :param cwd: Set the current working directory for the context, defaults to `/home/user`
274
+ :param language: Language of the context. If not specified, defaults to Python
275
+ :param request_timeout: Timeout for the request in **milliseconds**
276
+
277
+ :return: Context object
278
+ """
279
+ logger.debug(f"Creating new {language} context")
280
+
281
+ data = {}
282
+ if language:
283
+ data["language"] = language
284
+ if cwd:
285
+ data["cwd"] = cwd
286
+
287
+ try:
288
+ headers = {
289
+ "Content-Type": "application/json",
290
+ "Agentbox-Sandbox-Id": self.sandbox_id,
291
+ "Agentbox-Sandbox-Port": str(JUPYTER_PORT),
292
+ }
293
+ if self.traffic_access_token:
294
+ headers["Agentbox-Traffic-Access-Token"] = self.traffic_access_token
295
+
296
+ response = await self._client.post(
297
+ f"{self._jupyter_url}/contexts",
298
+ headers=headers,
299
+ json=data,
300
+ timeout=request_timeout or self.connection_config.request_timeout,
301
+ )
302
+
303
+ err = await aextract_exception(response)
304
+ if err:
305
+ raise err
306
+
307
+ data = response.json()
308
+ return Context.from_json(data)
309
+ except httpx.TimeoutException:
310
+ raise format_request_timeout_error()
311
+ except (httpx.ReadError, httpx.RemoteProtocolError) as err:
312
+ await self._handle_connection_error(err)
313
+ raise
314
+
315
+ async def remove_code_context(
316
+ self,
317
+ context: Union[Context, str],
318
+ ) -> None:
319
+ """
320
+ Removes a context.
321
+
322
+ :param context: Context to remove. Can be a Context object or a context ID string.
323
+
324
+ :return: None
325
+ """
326
+ context_id = context.id if isinstance(context, Context) else context
327
+
328
+ try:
329
+ headers = {
330
+ "Content-Type": "application/json",
331
+ "Agentbox-Sandbox-Id": self.sandbox_id,
332
+ "Agentbox-Sandbox-Port": str(JUPYTER_PORT),
333
+ }
334
+ if self.traffic_access_token:
335
+ headers["Agentbox-Traffic-Access-Token"] = self.traffic_access_token
336
+
337
+ response = await self._client.delete(
338
+ f"{self._jupyter_url}/contexts/{context_id}",
339
+ headers=headers,
340
+ timeout=self.connection_config.request_timeout,
341
+ )
342
+
343
+ err = await aextract_exception(response)
344
+ if err:
345
+ raise err
346
+ except httpx.TimeoutException:
347
+ raise format_request_timeout_error()
348
+ except (httpx.ReadError, httpx.RemoteProtocolError) as err:
349
+ await self._handle_connection_error(err)
350
+ raise
351
+
352
+ async def list_code_contexts(self) -> List[Context]:
353
+ """
354
+ List all contexts.
355
+
356
+ :return: List of contexts.
357
+ """
358
+ try:
359
+ headers = {
360
+ "Content-Type": "application/json",
361
+ "Agentbox-Sandbox-Id": self.sandbox_id,
362
+ "Agentbox-Sandbox-Port": str(JUPYTER_PORT),
363
+ }
364
+ if self.traffic_access_token:
365
+ headers["Agentbox-Traffic-Access-Token"] = self.traffic_access_token
366
+
367
+ response = await self._client.get(
368
+ f"{self._jupyter_url}/contexts",
369
+ headers=headers,
370
+ timeout=self.connection_config.request_timeout,
371
+ )
372
+
373
+ err = await aextract_exception(response)
374
+ if err:
375
+ raise err
376
+
377
+ data = response.json()
378
+ return [Context.from_json(context_data) for context_data in data]
379
+ except httpx.TimeoutException:
380
+ raise format_request_timeout_error()
381
+ except (httpx.ReadError, httpx.RemoteProtocolError) as err:
382
+ await self._handle_connection_error(err)
383
+ raise
384
+
385
+ async def restart_code_context(
386
+ self,
387
+ context: Union[Context, str],
388
+ ) -> None:
389
+ """
390
+ Restart a context.
391
+
392
+ :param context: Context to restart. Can be a Context object or a context ID string.
393
+
394
+ :return: None
395
+ """
396
+ context_id = context.id if isinstance(context, Context) else context
397
+ try:
398
+ headers = {
399
+ "Content-Type": "application/json",
400
+ "Agentbox-Sandbox-Id": self.sandbox_id,
401
+ "Agentbox-Sandbox-Port": str(JUPYTER_PORT),
402
+ }
403
+ if self.traffic_access_token:
404
+ headers["Agentbox-Traffic-Access-Token"] = self.traffic_access_token
405
+
406
+ response = await self._client.post(
407
+ f"{self._jupyter_url}/contexts/{context_id}/restart",
408
+ headers=headers,
409
+ timeout=self.connection_config.request_timeout,
410
+ )
411
+
412
+ err = await aextract_exception(response)
413
+ if err:
414
+ raise err
415
+ except httpx.TimeoutException:
416
+ raise format_request_timeout_error()
417
+ except (httpx.ReadError, httpx.RemoteProtocolError) as err:
418
+ await self._handle_connection_error(err)
419
+ raise