/ sdks / code-interpreter / kotlin / README_zh.md
README_zh.md
  1  # Alibaba Code Interpreter SDK for Kotlin
  2  
  3  中文 | [English](README.md)
  4  
  5  一个用于在安全、隔离的沙箱环境中执行代码的 Kotlin SDK。该 SDK 提供了高级 API,支持安全地运行 Python、Java、Go、TypeScript 等语言,并具备代码执行上下文(Context)能力。
  6  
  7  ## 前置要求
  8  
  9  本 SDK 需要配合包含 Code Interpreter 运行时环境的特定 Docker 镜像使用。请务必使用 `opensandbox/code-interpreter` 镜像(或其衍生镜像),其中预装了 Python、Java、Go、Node.js 等语言的运行环境。
 10  
 11  ## 安装指南
 12  
 13  ### Gradle (Kotlin DSL)
 14  
 15  ```kotlin
 16  dependencies {
 17      implementation("com.alibaba.opensandbox:code-interpreter:{latest_version}")
 18  }
 19  ```
 20  
 21  ### Maven
 22  
 23  ```xml
 24  <dependency>
 25      <groupId>com.alibaba.opensandbox</groupId>
 26      <artifactId>code-interpreter</artifactId>
 27      <version>{latest_version}</version>
 28  </dependency>
 29  ```
 30  
 31  ## 快速开始
 32  
 33  以下示例展示了如何初始化客户端,指定 Python 版本并执行一段简单的脚本。
 34  
 35  ```java
 36  import com.alibaba.opensandbox.codeinterpreter.CodeInterpreter;
 37  import com.alibaba.opensandbox.codeinterpreter.domain.models.execd.executions.CodeContext;
 38  import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.Execution;
 39  import com.alibaba.opensandbox.codeinterpreter.domain.models.execd.executions.RunCodeRequest;
 40  import com.alibaba.opensandbox.codeinterpreter.domain.models.execd.executions.SupportedLanguage;
 41  import com.alibaba.opensandbox.sandbox.Sandbox;
 42  import com.alibaba.opensandbox.sandbox.config.ConnectionConfig;
 43  import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxException;
 44  
 45  public class QuickStart {
 46      public static void main(String[] args) {
 47          // 1. 配置连接信息
 48          ConnectionConfig config = ConnectionConfig.builder()
 49              .domain("api.opensandbox.io")
 50              .apiKey("your-api-key")
 51              .build();
 52  
 53          // 2. 创建 Sandbox 实例
 54          // 注意: 必须使用 code-interpreter 专用镜像
 55          // 使用 try-with-resources 确保资源正确关闭
 56          try (Sandbox sandbox = Sandbox.builder()
 57                  .connectionConfig(config)
 58                  .image("sandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/code-interpreter:v1.0.2")
 59                  .entrypoint("/opt/opensandbox/code-interpreter.sh")
 60                  .env("PYTHON_VERSION", "3.11") // 指定语言版本
 61                  .build()) {
 62  
 63              // 3. 创建 CodeInterpreter 包装器
 64              CodeInterpreter interpreter = CodeInterpreter.builder()
 65                  .fromSandbox(sandbox)
 66                  .build();
 67  
 68              // 4. 创建执行上下文 (Python)
 69              CodeContext context = interpreter.codes().createContext(SupportedLanguage.PYTHON);
 70  
 71              // 5. 运行代码
 72              Execution result = interpreter.codes().run(
 73                  RunCodeRequest.builder()
 74                      .code("import sys; print(f'Running on Python {sys.version}')")
 75                      .context(context)
 76                      .build()
 77              );
 78  
 79              // 6. 打印输出
 80              if (!result.getLogs().getStdout().isEmpty()) {
 81                  System.out.println(result.getLogs().getStdout().get(0).getText());
 82              }
 83  
 84              // 7. 清理资源
 85              // 注意: kill() 会立即终止远程沙箱实例;try-with-resources 会自动调用 close() 清理本地资源
 86              sandbox.kill();
 87          } catch (SandboxException e) {
 88              // 处理 Sandbox 特定异常
 89              System.err.println("沙箱错误: [" + e.getError().getCode() + "] " + e.getError().getMessage());
 90          } catch (Exception e) {
 91              e.printStackTrace();
 92          }
 93      }
 94  }
 95  ```
 96  
 97  ## 运行时配置
 98  
 99  ### Docker 镜像
100  
101  Code Interpreter SDK 依赖于特定的运行环境。请确保你的沙箱服务提供商支持 `opensandbox/code-interpreter` 镜像。
102  
103  关于支持的语言和具体版本的详细信息,请参考 [环境文档](../../../sandboxes/code-interpreter/README_zh.md)。
104  
105  ### 语言版本选择
106  
107  你可以在创建 `Sandbox` 时通过环境变量指定所需的编程语言版本。
108  
109  | 语言    | 环境变量         | 示例值 | 默认值 (若不设置) |
110  | ------- | ---------------- | ------ | ----------------- |
111  | Python  | `PYTHON_VERSION` | `3.11` | 镜像默认值        |
112  | Java    | `JAVA_VERSION`   | `17`   | 镜像默认值        |
113  | Node.js | `NODE_VERSION`   | `20`   | 镜像默认值        |
114  | Go      | `GO_VERSION`     | `1.24` | 镜像默认值        |
115  
116  ```java
117  Sandbox sandbox = Sandbox.builder()
118      .image("opensandbox/code-interpreter:v1.0.2")
119      .entrypoint("/opt/opensandbox/code-interpreter.sh")
120      .env("JAVA_VERSION", "17")
121      .env("GO_VERSION", "1.23")
122      .build();
123  ```
124  
125  ## 核心功能示例
126  
127  ### 0. 直接传 `language`(使用该语言默认上下文)
128  
129  如果你不需要显式管理 session id,可以只传 `language` 来执行代码。
130  当 `context.id` 省略时,**execd 会为该语言创建/复用默认 session**,因此状态可以跨次执行保持:
131  
132  ```java
133  import com.alibaba.opensandbox.codeinterpreter.domain.models.execd.executions.SupportedLanguage;
134  
135  // Python 默认上下文:状态会在多次 run 之间保持
136  interpreter.codes().run("x = 42", SupportedLanguage.PYTHON);
137  Execution execution = interpreter.codes().run("result = x\nresult", SupportedLanguage.PYTHON);
138  System.out.println(execution.getResult().get(0).getText()); // 42
139  ```
140  
141  ### 1. Java 代码执行
142  
143  动态执行 Java 代码片段。
144  
145  ```java
146  CodeContext javaContext = interpreter.codes().createContext(SupportedLanguage.JAVA);
147  
148  RunCodeRequest request = RunCodeRequest.builder()
149      .code(
150          "System.out.println(\"Calculating sum...\");\n" +
151          "int a = 10;\n" +
152          "int b = 20;\n" +
153          "int sum = a + b;\n" +
154          "System.out.println(\"Sum: \" + sum);\n" +
155          "sum" // 返回值
156      )
157      .context(javaContext)
158      .build();
159  
160  Execution execution = interpreter.codes().run(request);
161  
162  // 处理结果
163  System.out.println("Execution ID: " + execution.getId());
164  execution.getLogs().getStdout().forEach(log -> System.out.println(log.getText()));
165  ```
166  
167  ### 2. Python 持久化状态
168  
169  在同一个上下文中,变量状态可以跨次执行保持。
170  
171  ```java
172  CodeContext pythonContext = interpreter.codes().createContext(SupportedLanguage.PYTHON);
173  
174  // 步骤 1: 定义变量
175  RunCodeRequest step1 = RunCodeRequest.builder()
176      .code(
177          "users = ['Alice', 'Bob', 'Charlie']\n" +
178          "print(f'Initialized {len(users)} users')"
179      )
180      .context(pythonContext)
181      .build();
182  interpreter.codes().run(step1);
183  
184  // 步骤 2: 使用上一步的变量
185  RunCodeRequest step2 = RunCodeRequest.builder()
186      .code(
187          "users.append('Dave')\n" +
188          "print(f'Updated users: {users}')"
189      )
190      .context(pythonContext)
191      .build();
192  
193  Execution result = interpreter.codes().run(step2);
194  // 输出: Updated users: ['Alice', 'Bob', 'Charlie', 'Dave']
195  ```
196  
197  ### 3. 流式输出处理
198  
199  实时处理标准输出、错误输出和执行事件。
200  
201  ```java
202  ExecutionHandlers handlers = ExecutionHandlers.builder()
203      .onStdout(msg -> System.out.println("STDOUT: " + msg.getText()))
204      .onStderr(msg -> System.err.println("STDERR: " + msg.getText()))
205      .onResult(res -> System.out.println("Result: " + res.getText()))
206      .onError(err -> System.err.println("Error: " + err.getValue()))
207      .onExecutionComplete(complete ->
208          System.out.println("Finished in " + complete.getExecutionTimeInMillis() + "ms")
209      )
210      .build();
211  
212  RunCodeRequest request = RunCodeRequest.builder()
213      .code("import time\nfor i in range(5):\n    print(i)\n    time.sleep(0.5)")
214      .context(pythonContext)
215      .handlers(handlers)
216      .build();
217  
218  interpreter.codes().run(request);
219  ```
220  
221  ### 4. 多语言上下文隔离
222  
223  不同语言在隔离的环境中运行。
224  
225  ```java
226  CodeContext pyCtx = interpreter.codes().createContext(SupportedLanguage.PYTHON);
227  CodeContext goCtx = interpreter.codes().createContext(SupportedLanguage.GO);
228  
229  // Python 上下文
230  interpreter.codes().run(
231      RunCodeRequest.builder()
232          .code("print('Running in Python')")
233          .context(pyCtx)
234          .build()
235  );
236  
237  // Go 上下文
238  interpreter.codes().run(
239      RunCodeRequest.builder()
240          .code(
241              "package main\n" +
242              "func main() { println(\"Running in Go\") }"
243          )
244          .context(goCtx)
245          .build()
246  );
247  ```