scalebox-sdk 0.1.11__py3-none-any.whl → 0.1.13__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.
Files changed (38) hide show
  1. scalebox/__init__.py +1 -1
  2. scalebox/code_interpreter/code_interpreter_async.py +12 -12
  3. scalebox/code_interpreter/code_interpreter_sync.py +11 -11
  4. scalebox/generated/api_pb2_connect.py +3 -3
  5. scalebox/sandbox_sync/main.py +1 -1
  6. scalebox/test/aclient.py +72 -72
  7. scalebox/test/code_interpreter_centext.py +21 -21
  8. scalebox/test/code_interpreter_centext_sync.py +21 -21
  9. scalebox/test/code_interpreter_test.py +34 -34
  10. scalebox/test/code_interpreter_test_sync.py +34 -34
  11. scalebox/test/run_all_validation_tests.py +334 -334
  12. scalebox/test/test_basic.py +78 -78
  13. scalebox/test/test_code_interpreter_async_comprehensive.py +2653 -2653
  14. scalebox/test/test_code_interpreter_e2basync_comprehensive.py +2655 -2655
  15. scalebox/test/test_code_interpreter_e2bsync_comprehensive.py +3416 -3416
  16. scalebox/test/test_code_interpreter_execcode.py +3352 -0
  17. scalebox/test/test_code_interpreter_sync_comprehensive.py +3416 -3412
  18. scalebox/test/test_csx_desktop_examples.py +130 -0
  19. scalebox/test/test_e2b_first.py +11 -11
  20. scalebox/test/test_sandbox_async_comprehensive.py +736 -738
  21. scalebox/test/test_sandbox_stress_and_edge_cases.py +778 -778
  22. scalebox/test/test_sandbox_sync_comprehensive.py +779 -770
  23. scalebox/test/test_sandbox_usage_examples.py +987 -987
  24. scalebox/test/testacreate.py +24 -24
  25. scalebox/test/testagetinfo.py +18 -18
  26. scalebox/test/testcodeinterpreter_async.py +508 -508
  27. scalebox/test/testcodeinterpreter_sync.py +239 -239
  28. scalebox/test/testcomputeuse.py +245 -243
  29. scalebox/test/testnovnc.py +12 -12
  30. scalebox/test/testsandbox_async.py +202 -118
  31. scalebox/test/testsandbox_sync.py +71 -38
  32. scalebox/version.py +2 -2
  33. {scalebox_sdk-0.1.11.dist-info → scalebox_sdk-0.1.13.dist-info}/METADATA +1 -1
  34. {scalebox_sdk-0.1.11.dist-info → scalebox_sdk-0.1.13.dist-info}/RECORD +38 -36
  35. {scalebox_sdk-0.1.11.dist-info → scalebox_sdk-0.1.13.dist-info}/WHEEL +0 -0
  36. {scalebox_sdk-0.1.11.dist-info → scalebox_sdk-0.1.13.dist-info}/entry_points.txt +0 -0
  37. {scalebox_sdk-0.1.11.dist-info → scalebox_sdk-0.1.13.dist-info}/licenses/LICENSE +0 -0
  38. {scalebox_sdk-0.1.11.dist-info → scalebox_sdk-0.1.13.dist-info}/top_level.txt +0 -0
@@ -1,508 +1,508 @@
1
- #!/usr/bin/env python3
2
- """
3
- Simple async CodeInterpreter test example.
4
- Similar to testsandbox_async.py but for code interpreter functionality.
5
- """
6
-
7
- import asyncio
8
-
9
- from scalebox.code_interpreter import AsyncSandbox, Context
10
-
11
-
12
- async def async_output_handler(output):
13
- """处理异步输出的回调函数"""
14
- print(f"异步输出: {output.content}")
15
-
16
-
17
- async def async_result_handler(result):
18
- """处理异步结果的回调函数"""
19
- print(f"异步结果: {result}")
20
-
21
-
22
- async def async_error_handler(error):
23
- """处理异步错误的回调函数"""
24
- print(f"异步错误: {error.name} - {error.value}")
25
-
26
-
27
- async def main():
28
- # 创建异步代码解释器沙箱
29
- sandbox = AsyncSandbox(template="code-interpreter-v1")
30
-
31
- print("=== 基础异步Python代码执行 ===")
32
- # 基础异步Python代码执行
33
- result = await sandbox.run_code(
34
- """
35
- import asyncio
36
-
37
- print("开始异步代码执行")
38
-
39
- async def async_task():
40
- print("异步任务开始")
41
- await asyncio.sleep(0.1)
42
- result = sum(range(10))
43
- print(f"异步任务完成,结果: {result}")
44
- return result
45
-
46
- result = await async_task()
47
- print(f"最终结果: {result}")
48
- result
49
- """,
50
- language="python",
51
- )
52
-
53
- print(f"异步执行结果: {result}")
54
- print(f"标准输出: {result.logs.stdout}")
55
-
56
- print("\n=== 并发代码执行 ===")
57
- # 并发执行多个代码片段
58
- codes = [
59
- """
60
- import asyncio
61
- print("任务1开始")
62
- await asyncio.sleep(0.1)
63
- result = {"task": 1, "value": 100}
64
- print(f"任务1完成: {result}")
65
- result
66
- """,
67
- """
68
- import asyncio
69
- print("任务2开始")
70
- await asyncio.sleep(0.1)
71
- result = {"task": 2, "value": 200}
72
- print(f"任务2完成: {result}")
73
- result
74
- """,
75
- """
76
- import asyncio
77
- print("任务3开始")
78
- await asyncio.sleep(0.1)
79
- result = {"task": 3, "value": 300}
80
- print(f"任务3完成: {result}")
81
- result
82
- """,
83
- ]
84
-
85
- # 并发执行
86
- import time
87
-
88
- start_time = time.time()
89
- tasks = [sandbox.run_code(code) for code in codes]
90
- results = await asyncio.gather(*tasks)
91
- duration = time.time() - start_time
92
-
93
- print(f"并发执行完成,耗时: {duration:.3f}s")
94
- for i, result in enumerate(results):
95
- print(f"任务 {i+1} 结果: {result.logs.stdout}")
96
-
97
- print("\n=== 异步数据处理 ===")
98
- # 异步数据处理
99
- async_data_result = await sandbox.run_code(
100
- """
101
- import asyncio
102
- import pandas as pd
103
- import json
104
-
105
- async def process_data_async():
106
- print("开始异步数据处理")
107
-
108
- # 模拟异步数据获取
109
- await asyncio.sleep(0.05)
110
-
111
- data = {
112
- 'id': range(1, 11),
113
- 'value': [i * 10 for i in range(1, 11)],
114
- 'category': ['A' if i % 2 == 0 else 'B' for i in range(1, 11)]
115
- }
116
-
117
- df = pd.DataFrame(data)
118
- print("数据处理完成")
119
-
120
- # 分析数据
121
- summary = {
122
- "total_rows": len(df),
123
- "avg_value": df['value'].mean(),
124
- "category_counts": df['category'].value_counts().to_dict()
125
- }
126
-
127
- return summary
128
-
129
- result = await process_data_async()
130
- print(f"异步数据处理结果: {json.dumps(result, indent=2)}")
131
- result
132
- """
133
- )
134
-
135
- print(f"异步数据处理结果: {async_data_result}")
136
-
137
- print("\n=== 使用异步回调函数 ===")
138
- # 使用异步回调函数
139
- callback_result = await sandbox.run_code(
140
- """
141
- import asyncio
142
-
143
- print("开始执行带异步回调的代码")
144
-
145
- async def async_workflow():
146
- for i in range(3):
147
- print(f"异步步骤 {i+1}")
148
- await asyncio.sleep(0.05)
149
-
150
- result = {"steps": 3, "status": "async_completed"}
151
- print(f"异步流程完成: {result}")
152
- return result
153
-
154
- result = await async_workflow()
155
- result
156
- """,
157
- on_stdout=async_output_handler,
158
- on_result=async_result_handler,
159
- on_error=async_error_handler,
160
- )
161
-
162
- print("\n=== 异步上下文管理 ===")
163
- # 创建异步上下文
164
- context = await sandbox.create_code_context(language="python", cwd="/tmp")
165
- print(f"创建异步上下文: {context.id}")
166
-
167
- # 在异步上下文中执行代码
168
- context_result1 = await sandbox.run_code(
169
- """
170
- import asyncio
171
-
172
- # 在异步上下文中定义变量
173
- async_context_var = "Hello from async context"
174
- async_data = {"status": "initialized", "items": []}
175
-
176
- async def add_item(item):
177
- async_data["items"].append(item)
178
- await asyncio.sleep(0.01)
179
- return len(async_data["items"])
180
-
181
- # 添加一些项目
182
- for i in range(3):
183
- count = await add_item(f"item_{i}")
184
- print(f"添加项目 {i}, 当前总数: {count}")
185
-
186
- print(f"异步上下文变量: {async_context_var}")
187
- print(f"异步数据: {async_data}")
188
- """,
189
- context=context,
190
- )
191
-
192
- # 在同一异步上下文中使用变量
193
- context_result2 = await sandbox.run_code(
194
- """
195
- print(f"从异步上下文读取: {async_context_var}")
196
- print(f"当前数据: {async_data}")
197
-
198
- # 继续处理数据
199
- async def process_items():
200
- results = []
201
- for item in async_data["items"]:
202
- processed = f"processed_{item}"
203
- results.append(processed)
204
- await asyncio.sleep(0.01)
205
- return results
206
-
207
- processed_items = await process_items()
208
- async_data["processed"] = processed_items
209
-
210
- print(f"处理完成: {len(processed_items)} 个项目")
211
- {"original_items": len(async_data["items"]), "processed_items": len(processed_items)}
212
- """,
213
- context=context,
214
- )
215
-
216
- print(f"异步上下文测试结果: {context_result2}")
217
-
218
- print("\n=== 异步错误处理示例 ===")
219
- # 异步错误处理
220
- async_error_result = await sandbox.run_code(
221
- """
222
- import asyncio
223
-
224
- async def failing_async_task():
225
- print("异步任务开始")
226
- await asyncio.sleep(0.1)
227
- # 这里会产生错误
228
- result = 10 / 0
229
- return result
230
-
231
- print("开始可能失败的异步任务")
232
- result = await failing_async_task()
233
- """,
234
- on_error=async_error_handler,
235
- )
236
-
237
- print(f"异步错误处理结果: {async_error_result.error}")
238
-
239
- print("\n=== 异步批处理示例 ===")
240
- # 异步批处理
241
- batch_result = await sandbox.run_code(
242
- '''
243
- import asyncio
244
- import time
245
-
246
- async def process_item(item_id):
247
- """处理单个项目"""
248
- await asyncio.sleep(0.02) # 模拟处理时间
249
- return {"id": item_id, "processed": True, "value": item_id * 10}
250
-
251
- async def batch_processor(items):
252
- """批量处理器"""
253
- print(f"开始批量处理 {len(items)} 个项目")
254
- start_time = time.time()
255
-
256
- # 并发处理所有项目
257
- tasks = [process_item(item) for item in items]
258
- results = await asyncio.gather(*tasks)
259
-
260
- processing_time = time.time() - start_time
261
- print(f"批量处理完成,耗时: {processing_time:.3f}s")
262
-
263
- return {
264
- "processed_items": results,
265
- "processing_time": processing_time,
266
- "throughput": len(items) / processing_time
267
- }
268
-
269
- # 处理一批项目
270
- items_to_process = list(range(1, 11)) # 处理10个项目
271
- result = await batch_processor(items_to_process)
272
-
273
- print(f"批处理结果:")
274
- print(f" 处理项目数: {len(result['processed_items'])}")
275
- print(f" 处理时间: {result['processing_time']:.3f}s")
276
- print(f" 吞吐量: {result['throughput']:.1f} items/s")
277
-
278
- result
279
- '''
280
- )
281
-
282
- print(f"异步批处理结果: {batch_result}")
283
-
284
- print("\n=== 异步结果格式示例 ===")
285
- # 展示异步多格式结果生成
286
- async_format_result = await sandbox.run_code(
287
- '''
288
- import asyncio
289
- import json
290
- import base64
291
- import matplotlib.pyplot as plt
292
- import numpy as np
293
- import io
294
-
295
- async def generate_async_format_demo():
296
- print("开始异步多格式结果演示...")
297
-
298
- # 1. 异步文本生成
299
- await asyncio.sleep(0.05)
300
- text_content = """
301
- 异步CodeInterpreter多格式结果演示
302
- ================================
303
- 执行模式: 异步
304
- 生成时间: 2024-09-17
305
- 状态: 成功
306
- """
307
- print(f"异步文本格式生成完成")
308
-
309
- # 2. 异步JSON数据编译
310
- await asyncio.sleep(0.05)
311
- json_data = {
312
- "async_demo": {
313
- "execution_type": "asynchronous",
314
- "formats": ["text", "json", "html", "chart", "image"],
315
- "performance": {
316
- "concurrent_tasks": 3,
317
- "total_time": "< 0.5s",
318
- "efficiency": "高效"
319
- }
320
- },
321
- "results": {
322
- "format_count": 5,
323
- "async_benefits": [
324
- "非阻塞执行",
325
- "并发处理",
326
- "资源优化"
327
- ]
328
- }
329
- }
330
- print(f"异步JSON数据生成完成")
331
-
332
- # 3. 异步HTML内容生成
333
- await asyncio.sleep(0.05)
334
- html_content = """
335
- <div class="async-demo-results">
336
- <h2>异步CodeInterpreter演示</h2>
337
- <div class="async-status">
338
- <span class="badge success">异步执行成功</span>
339
- </div>
340
- <div class="format-list">
341
- <h3>支持的格式:</h3>
342
- <ul>
343
- <li>异步文本生成</li>
344
- <li>异步JSON编译</li>
345
- <li>异步HTML渲染</li>
346
- <li>异步图表数据</li>
347
- <li>异步图像处理</li>
348
- </ul>
349
- </div>
350
- <div class="performance-info">
351
- <p><strong>性能优势:</strong> 并发处理多种格式,显著提升效率</p>
352
- </div>
353
- </div>
354
- """
355
- print(f"异步HTML内容生成完成")
356
-
357
- return {
358
- "text": text_content.strip(),
359
- "json_data": json_data,
360
- "html": html_content.strip(),
361
- "execution_summary": {
362
- "mode": "async",
363
- "formats_generated": 3,
364
- "performance": "excellent"
365
- }
366
- }
367
-
368
- # 异步并发执行格式生成任务
369
- async def concurrent_format_generation():
370
- # 并发生成多个格式的示例
371
- tasks = []
372
-
373
- # 任务1: 图表数据生成
374
- async def generate_chart_data():
375
- await asyncio.sleep(0.1)
376
- return {
377
- "type": "performance_chart",
378
- "data": {
379
- "labels": ["异步执行", "同步执行"],
380
- "values": [95, 65],
381
- "colors": ["#28a745", "#6c757d"]
382
- },
383
- "description": "异步vs同步性能对比"
384
- }
385
-
386
- # 任务2: 数据统计
387
- async def generate_statistics():
388
- await asyncio.sleep(0.08)
389
- return {
390
- "execution_stats": {
391
- "total_formats": 5,
392
- "async_tasks": 3,
393
- "completion_rate": "100%",
394
- "average_response_time": "0.087s"
395
- }
396
- }
397
-
398
- # 任务3: 简单图像处理
399
- async def generate_simple_chart():
400
- await asyncio.sleep(0.12)
401
-
402
- # 在异步任务中生成图像
403
- fig, ax = plt.subplots(figsize=(8, 6))
404
-
405
- # 异步性能对比数据
406
- categories = ['文本', 'JSON', 'HTML', '图表', '图像']
407
- async_times = [0.05, 0.05, 0.05, 0.10, 0.12]
408
- sync_times = [0.02, 0.03, 0.02, 0.15, 0.18]
409
-
410
- x = np.arange(len(categories))
411
- width = 0.35
412
-
413
- ax.bar(x - width/2, async_times, width, label='异步执行', color='#28a745', alpha=0.8)
414
- ax.bar(x + width/2, sync_times, width, label='同步执行', color='#6c757d', alpha=0.8)
415
-
416
- ax.set_xlabel('结果格式类型')
417
- ax.set_ylabel('执行时间 (秒)')
418
- ax.set_title('异步vs同步格式生成性能对比')
419
- ax.set_xticks(x)
420
- ax.set_xticklabels(categories)
421
- ax.legend()
422
- ax.grid(True, alpha=0.3)
423
-
424
- plt.tight_layout()
425
-
426
- # 转换为base64
427
- img_buffer = io.BytesIO()
428
- plt.savefig(img_buffer, format='png', dpi=100, bbox_inches='tight')
429
- img_buffer.seek(0)
430
- img_base64 = base64.b64encode(img_buffer.getvalue()).decode()
431
- img_buffer.close()
432
- plt.close()
433
-
434
- return {
435
- "image_data": img_base64,
436
- "format": "png_base64",
437
- "size": len(img_base64),
438
- "description": "异步vs同步性能对比图表"
439
- }
440
-
441
- # 并发执行所有任务
442
- print("启动并发格式生成任务...")
443
- chart_task = asyncio.create_task(generate_chart_data())
444
- stats_task = asyncio.create_task(generate_statistics())
445
- image_task = asyncio.create_task(generate_simple_chart())
446
-
447
- chart_data, statistics, image_data = await asyncio.gather(
448
- chart_task, stats_task, image_task
449
- )
450
-
451
- print("所有并发任务完成")
452
-
453
- return {
454
- "chart_data": chart_data,
455
- "statistics": statistics,
456
- "image_result": {
457
- "size": image_data["size"],
458
- "format": image_data["format"],
459
- "description": image_data["description"]
460
- }
461
- }
462
-
463
- # 执行异步格式演示
464
- print("开始异步结果格式演示...")
465
-
466
- # 1. 基础格式生成
467
- basic_formats = await generate_async_format_demo()
468
- print(f"基础格式生成完成: {list(basic_formats.keys())}")
469
-
470
- # 2. 并发格式生成
471
- concurrent_results = await concurrent_format_generation()
472
- print(f"并发格式生成完成")
473
-
474
- # 综合结果
475
- final_result = {
476
- "demo_type": "async_multi_format",
477
- "basic_formats": basic_formats,
478
- "concurrent_results": concurrent_results,
479
- "summary": {
480
- "total_format_types": 7,
481
- "concurrent_tasks": 3,
482
- "execution_mode": "fully_asynchronous",
483
- "performance_rating": "优秀",
484
- "async_advantages": [
485
- "并发执行多种格式生成",
486
- "非阻塞I/O操作",
487
- "高效的资源利用",
488
- "优秀的响应时间"
489
- ]
490
- }
491
- }
492
-
493
- print("\\n异步多格式结果演示完成!")
494
- final_result
495
- '''
496
- )
497
-
498
- print(f"异步格式结果测试: {async_format_result}")
499
-
500
- print("\n=== 异步测试完成 ===")
501
- print("AsyncCodeInterpreter功能测试完成!")
502
-
503
- # 清理
504
- await sandbox.kill()
505
-
506
-
507
- if __name__ == "__main__":
508
- asyncio.run(main())
1
+ #!/usr/bin/env python3
2
+ """
3
+ Simple async CodeInterpreter test example.
4
+ Similar to testsandbox_async.py but for code interpreter functionality.
5
+ """
6
+
7
+ import asyncio
8
+
9
+ from scalebox.code_interpreter import AsyncSandbox, Context
10
+
11
+
12
+ async def async_output_handler(output):
13
+ """处理异步输出的回调函数"""
14
+ print(f"异步输出: {output.content}")
15
+
16
+
17
+ async def async_result_handler(result):
18
+ """处理异步结果的回调函数"""
19
+ print(f"异步结果: {result}")
20
+
21
+
22
+ async def async_error_handler(error):
23
+ """处理异步错误的回调函数"""
24
+ print(f"异步错误: {error.name} - {error.value}")
25
+
26
+
27
+ async def main():
28
+ # 创建异步代码解释器沙箱
29
+ sandbox = AsyncSandbox(template="code-interpreter-v1")
30
+
31
+ print("=== 基础异步Python代码执行 ===")
32
+ # 基础异步Python代码执行
33
+ result = await sandbox.run_code(
34
+ """
35
+ import asyncio
36
+
37
+ print("开始异步代码执行")
38
+
39
+ async def async_task():
40
+ print("异步任务开始")
41
+ await asyncio.sleep(0.1)
42
+ result = sum(range(10))
43
+ print(f"异步任务完成,结果: {result}")
44
+ return result
45
+
46
+ result = await async_task()
47
+ print(f"最终结果: {result}")
48
+ result
49
+ """,
50
+ language="python",
51
+ )
52
+
53
+ print(f"异步执行结果: {result}")
54
+ print(f"标准输出: {result.logs.stdout}")
55
+
56
+ print("\n=== 并发代码执行 ===")
57
+ # 并发执行多个代码片段
58
+ codes = [
59
+ """
60
+ import asyncio
61
+ print("任务1开始")
62
+ await asyncio.sleep(0.1)
63
+ result = {"task": 1, "value": 100}
64
+ print(f"任务1完成: {result}")
65
+ result
66
+ """,
67
+ """
68
+ import asyncio
69
+ print("任务2开始")
70
+ await asyncio.sleep(0.1)
71
+ result = {"task": 2, "value": 200}
72
+ print(f"任务2完成: {result}")
73
+ result
74
+ """,
75
+ """
76
+ import asyncio
77
+ print("任务3开始")
78
+ await asyncio.sleep(0.1)
79
+ result = {"task": 3, "value": 300}
80
+ print(f"任务3完成: {result}")
81
+ result
82
+ """,
83
+ ]
84
+
85
+ # 并发执行
86
+ import time
87
+
88
+ start_time = time.time()
89
+ tasks = [sandbox.run_code(code) for code in codes]
90
+ results = await asyncio.gather(*tasks)
91
+ duration = time.time() - start_time
92
+
93
+ print(f"并发执行完成,耗时: {duration:.3f}s")
94
+ for i, result in enumerate(results):
95
+ print(f"任务 {i+1} 结果: {result.logs.stdout}")
96
+
97
+ print("\n=== 异步数据处理 ===")
98
+ # 异步数据处理
99
+ async_data_result = await sandbox.run_code(
100
+ """
101
+ import asyncio
102
+ import pandas as pd
103
+ import json
104
+
105
+ async def process_data_async():
106
+ print("开始异步数据处理")
107
+
108
+ # 模拟异步数据获取
109
+ await asyncio.sleep(0.05)
110
+
111
+ data = {
112
+ 'id': range(1, 11),
113
+ 'value': [i * 10 for i in range(1, 11)],
114
+ 'category': ['A' if i % 2 == 0 else 'B' for i in range(1, 11)]
115
+ }
116
+
117
+ df = pd.DataFrame(data)
118
+ print("数据处理完成")
119
+
120
+ # 分析数据
121
+ summary = {
122
+ "total_rows": len(df),
123
+ "avg_value": df['value'].mean(),
124
+ "category_counts": df['category'].value_counts().to_dict()
125
+ }
126
+
127
+ return summary
128
+
129
+ result = await process_data_async()
130
+ print(f"异步数据处理结果: {json.dumps(result, indent=2)}")
131
+ result
132
+ """
133
+ )
134
+
135
+ print(f"异步数据处理结果: {async_data_result}")
136
+
137
+ print("\n=== 使用异步回调函数 ===")
138
+ # 使用异步回调函数
139
+ callback_result = await sandbox.run_code(
140
+ """
141
+ import asyncio
142
+
143
+ print("开始执行带异步回调的代码")
144
+
145
+ async def async_workflow():
146
+ for i in range(3):
147
+ print(f"异步步骤 {i+1}")
148
+ await asyncio.sleep(0.05)
149
+
150
+ result = {"steps": 3, "status": "async_completed"}
151
+ print(f"异步流程完成: {result}")
152
+ return result
153
+
154
+ result = await async_workflow()
155
+ result
156
+ """,
157
+ on_stdout=async_output_handler,
158
+ on_result=async_result_handler,
159
+ on_error=async_error_handler,
160
+ )
161
+
162
+ print("\n=== 异步上下文管理 ===")
163
+ # 创建异步上下文
164
+ context = await sandbox.create_code_context(language="python", cwd="/tmp")
165
+ print(f"创建异步上下文: {context.id}")
166
+
167
+ # 在异步上下文中执行代码
168
+ context_result1 = await sandbox.run_code(
169
+ """
170
+ import asyncio
171
+
172
+ # 在异步上下文中定义变量
173
+ async_context_var = "Hello from async context"
174
+ async_data = {"status": "initialized", "items": []}
175
+
176
+ async def add_item(item):
177
+ async_data["items"].append(item)
178
+ await asyncio.sleep(0.01)
179
+ return len(async_data["items"])
180
+
181
+ # 添加一些项目
182
+ for i in range(3):
183
+ count = await add_item(f"item_{i}")
184
+ print(f"添加项目 {i}, 当前总数: {count}")
185
+
186
+ print(f"异步上下文变量: {async_context_var}")
187
+ print(f"异步数据: {async_data}")
188
+ """,
189
+ context=context,
190
+ )
191
+
192
+ # 在同一异步上下文中使用变量
193
+ context_result2 = await sandbox.run_code(
194
+ """
195
+ print(f"从异步上下文读取: {async_context_var}")
196
+ print(f"当前数据: {async_data}")
197
+
198
+ # 继续处理数据
199
+ async def process_items():
200
+ results = []
201
+ for item in async_data["items"]:
202
+ processed = f"processed_{item}"
203
+ results.append(processed)
204
+ await asyncio.sleep(0.01)
205
+ return results
206
+
207
+ processed_items = await process_items()
208
+ async_data["processed"] = processed_items
209
+
210
+ print(f"处理完成: {len(processed_items)} 个项目")
211
+ {"original_items": len(async_data["items"]), "processed_items": len(processed_items)}
212
+ """,
213
+ context=context,
214
+ )
215
+
216
+ print(f"异步上下文测试结果: {context_result2}")
217
+
218
+ print("\n=== 异步错误处理示例 ===")
219
+ # 异步错误处理
220
+ async_error_result = await sandbox.run_code(
221
+ """
222
+ import asyncio
223
+
224
+ async def failing_async_task():
225
+ print("异步任务开始")
226
+ await asyncio.sleep(0.1)
227
+ # 这里会产生错误
228
+ result = 10 / 0
229
+ return result
230
+
231
+ print("开始可能失败的异步任务")
232
+ result = await failing_async_task()
233
+ """,
234
+ on_error=async_error_handler,
235
+ )
236
+
237
+ print(f"异步错误处理结果: {async_error_result.error}")
238
+
239
+ print("\n=== 异步批处理示例 ===")
240
+ # 异步批处理
241
+ batch_result = await sandbox.run_code(
242
+ '''
243
+ import asyncio
244
+ import time
245
+
246
+ async def process_item(item_id):
247
+ """处理单个项目"""
248
+ await asyncio.sleep(0.02) # 模拟处理时间
249
+ return {"id": item_id, "processed": True, "value": item_id * 10}
250
+
251
+ async def batch_processor(items):
252
+ """批量处理器"""
253
+ print(f"开始批量处理 {len(items)} 个项目")
254
+ start_time = time.time()
255
+
256
+ # 并发处理所有项目
257
+ tasks = [process_item(item) for item in items]
258
+ results = await asyncio.gather(*tasks)
259
+
260
+ processing_time = time.time() - start_time
261
+ print(f"批量处理完成,耗时: {processing_time:.3f}s")
262
+
263
+ return {
264
+ "processed_items": results,
265
+ "processing_time": processing_time,
266
+ "throughput": len(items) / processing_time
267
+ }
268
+
269
+ # 处理一批项目
270
+ items_to_process = list(range(1, 11)) # 处理10个项目
271
+ result = await batch_processor(items_to_process)
272
+
273
+ print(f"批处理结果:")
274
+ print(f" 处理项目数: {len(result['processed_items'])}")
275
+ print(f" 处理时间: {result['processing_time']:.3f}s")
276
+ print(f" 吞吐量: {result['throughput']:.1f} items/s")
277
+
278
+ result
279
+ '''
280
+ )
281
+
282
+ print(f"异步批处理结果: {batch_result}")
283
+
284
+ print("\n=== 异步结果格式示例 ===")
285
+ # 展示异步多格式结果生成
286
+ async_format_result = await sandbox.run_code(
287
+ '''
288
+ import asyncio
289
+ import json
290
+ import base64
291
+ import matplotlib.pyplot as plt
292
+ import numpy as np
293
+ import io
294
+
295
+ async def generate_async_format_demo():
296
+ print("开始异步多格式结果演示...")
297
+
298
+ # 1. 异步文本生成
299
+ await asyncio.sleep(0.05)
300
+ text_content = """
301
+ 异步CodeInterpreter多格式结果演示
302
+ ================================
303
+ 执行模式: 异步
304
+ 生成时间: 2024-09-17
305
+ 状态: 成功
306
+ """
307
+ print(f"异步文本格式生成完成")
308
+
309
+ # 2. 异步JSON数据编译
310
+ await asyncio.sleep(0.05)
311
+ json_data = {
312
+ "async_demo": {
313
+ "execution_type": "asynchronous",
314
+ "formats": ["text", "json", "html", "chart", "image"],
315
+ "performance": {
316
+ "concurrent_tasks": 3,
317
+ "total_time": "< 0.5s",
318
+ "efficiency": "高效"
319
+ }
320
+ },
321
+ "results": {
322
+ "format_count": 5,
323
+ "async_benefits": [
324
+ "非阻塞执行",
325
+ "并发处理",
326
+ "资源优化"
327
+ ]
328
+ }
329
+ }
330
+ print(f"异步JSON数据生成完成")
331
+
332
+ # 3. 异步HTML内容生成
333
+ await asyncio.sleep(0.05)
334
+ html_content = """
335
+ <div class="async-demo-results">
336
+ <h2>异步CodeInterpreter演示</h2>
337
+ <div class="async-status">
338
+ <span class="badge success">异步执行成功</span>
339
+ </div>
340
+ <div class="format-list">
341
+ <h3>支持的格式:</h3>
342
+ <ul>
343
+ <li>异步文本生成</li>
344
+ <li>异步JSON编译</li>
345
+ <li>异步HTML渲染</li>
346
+ <li>异步图表数据</li>
347
+ <li>异步图像处理</li>
348
+ </ul>
349
+ </div>
350
+ <div class="performance-info">
351
+ <p><strong>性能优势:</strong> 并发处理多种格式,显著提升效率</p>
352
+ </div>
353
+ </div>
354
+ """
355
+ print(f"异步HTML内容生成完成")
356
+
357
+ return {
358
+ "text": text_content.strip(),
359
+ "json_data": json_data,
360
+ "html": html_content.strip(),
361
+ "execution_summary": {
362
+ "mode": "async",
363
+ "formats_generated": 3,
364
+ "performance": "excellent"
365
+ }
366
+ }
367
+
368
+ # 异步并发执行格式生成任务
369
+ async def concurrent_format_generation():
370
+ # 并发生成多个格式的示例
371
+ tasks = []
372
+
373
+ # 任务1: 图表数据生成
374
+ async def generate_chart_data():
375
+ await asyncio.sleep(0.1)
376
+ return {
377
+ "type": "performance_chart",
378
+ "data": {
379
+ "labels": ["异步执行", "同步执行"],
380
+ "values": [95, 65],
381
+ "colors": ["#28a745", "#6c757d"]
382
+ },
383
+ "description": "异步vs同步性能对比"
384
+ }
385
+
386
+ # 任务2: 数据统计
387
+ async def generate_statistics():
388
+ await asyncio.sleep(0.08)
389
+ return {
390
+ "execution_stats": {
391
+ "total_formats": 5,
392
+ "async_tasks": 3,
393
+ "completion_rate": "100%",
394
+ "average_response_time": "0.087s"
395
+ }
396
+ }
397
+
398
+ # 任务3: 简单图像处理
399
+ async def generate_simple_chart():
400
+ await asyncio.sleep(0.12)
401
+
402
+ # 在异步任务中生成图像
403
+ fig, ax = plt.subplots(figsize=(8, 6))
404
+
405
+ # 异步性能对比数据
406
+ categories = ['文本', 'JSON', 'HTML', '图表', '图像']
407
+ async_times = [0.05, 0.05, 0.05, 0.10, 0.12]
408
+ sync_times = [0.02, 0.03, 0.02, 0.15, 0.18]
409
+
410
+ x = np.arange(len(categories))
411
+ width = 0.35
412
+
413
+ ax.bar(x - width/2, async_times, width, label='异步执行', color='#28a745', alpha=0.8)
414
+ ax.bar(x + width/2, sync_times, width, label='同步执行', color='#6c757d', alpha=0.8)
415
+
416
+ ax.set_xlabel('结果格式类型')
417
+ ax.set_ylabel('执行时间 (秒)')
418
+ ax.set_title('异步vs同步格式生成性能对比')
419
+ ax.set_xticks(x)
420
+ ax.set_xticklabels(categories)
421
+ ax.legend()
422
+ ax.grid(True, alpha=0.3)
423
+
424
+ plt.tight_layout()
425
+
426
+ # 转换为base64
427
+ img_buffer = io.BytesIO()
428
+ plt.savefig(img_buffer, format='png', dpi=100, bbox_inches='tight')
429
+ img_buffer.seek(0)
430
+ img_base64 = base64.b64encode(img_buffer.getvalue()).decode()
431
+ img_buffer.close()
432
+ plt.close()
433
+
434
+ return {
435
+ "image_data": img_base64,
436
+ "format": "png_base64",
437
+ "size": len(img_base64),
438
+ "description": "异步vs同步性能对比图表"
439
+ }
440
+
441
+ # 并发执行所有任务
442
+ print("启动并发格式生成任务...")
443
+ chart_task = asyncio.create_task(generate_chart_data())
444
+ stats_task = asyncio.create_task(generate_statistics())
445
+ image_task = asyncio.create_task(generate_simple_chart())
446
+
447
+ chart_data, statistics, image_data = await asyncio.gather(
448
+ chart_task, stats_task, image_task
449
+ )
450
+
451
+ print("所有并发任务完成")
452
+
453
+ return {
454
+ "chart_data": chart_data,
455
+ "statistics": statistics,
456
+ "image_result": {
457
+ "size": image_data["size"],
458
+ "format": image_data["format"],
459
+ "description": image_data["description"]
460
+ }
461
+ }
462
+
463
+ # 执行异步格式演示
464
+ print("开始异步结果格式演示...")
465
+
466
+ # 1. 基础格式生成
467
+ basic_formats = await generate_async_format_demo()
468
+ print(f"基础格式生成完成: {list(basic_formats.keys())}")
469
+
470
+ # 2. 并发格式生成
471
+ concurrent_results = await concurrent_format_generation()
472
+ print(f"并发格式生成完成")
473
+
474
+ # 综合结果
475
+ final_result = {
476
+ "demo_type": "async_multi_format",
477
+ "basic_formats": basic_formats,
478
+ "concurrent_results": concurrent_results,
479
+ "summary": {
480
+ "total_format_types": 7,
481
+ "concurrent_tasks": 3,
482
+ "execution_mode": "fully_asynchronous",
483
+ "performance_rating": "优秀",
484
+ "async_advantages": [
485
+ "并发执行多种格式生成",
486
+ "非阻塞I/O操作",
487
+ "高效的资源利用",
488
+ "优秀的响应时间"
489
+ ]
490
+ }
491
+ }
492
+
493
+ print("\\n异步多格式结果演示完成!")
494
+ final_result
495
+ '''
496
+ )
497
+
498
+ print(f"异步格式结果测试: {async_format_result}")
499
+
500
+ print("\n=== 异步测试完成 ===")
501
+ print("AsyncCodeInterpreter功能测试完成!")
502
+
503
+ # 清理
504
+ await sandbox.kill()
505
+
506
+
507
+ if __name__ == "__main__":
508
+ asyncio.run(main())