> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mka1.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Code execution

> Let Responses run shell commands or code in a sandbox, and reuse sessions and files.

Give a [Response](/docs/responses) access to the sandbox platform through either `shell` or `code_interpreter`. Both tools run on the same sandbox platform and return execution output to the model so it can continue its response.

Use `shell` for broader workspace tasks: running commands and scripts, working with files, and combining command-line tools. Use `code_interpreter` when the task is specifically to write and run code, such as a calculation or data analysis. Shell can run code too; the distinction is the interface and kind of task you want to give the model.

For sessions and commands controlled directly by your application, use the [standalone Sandbox API](/docs/sandbox).

## Choose a tool

| Tool               | Use it for                                                      | Session configuration                                                 |
| ------------------ | --------------------------------------------------------------- | --------------------------------------------------------------------- |
| `shell`            | General workspace tasks, commands, scripts, and file operations | Automatic environment or an existing session ID                       |
| `code_interpreter` | Writing and running code for calculations and analysis          | Automatic container with optional file IDs, or an existing session ID |

The API key needs both `read:sandbox` and `write:sandbox`, as well as permission to create responses. The examples use `X-On-Behalf-Of` to keep execution scoped to one end user; replace its placeholder with your end-user ID. Omit it consistently if your application operates as the API-key identity.

The OpenAI SDK examples use its custom-request method to send MKA1 tool configuration without changing field names to match another provider's tool types.

## Run a shell command

This request lets Responses provision the sandbox. The model decides when to invoke the tool; the prompt explicitly asks it to run a calculation and report the result.

<CodeGroup>
  ```ts TypeScript SDK theme={null}
  import { SDK } from '@meetkai/mka1';

  const sdk = new SDK({ bearerAuth: 'Bearer <mka1-api-key>' });

  const result = await sdk.llm.responses.create({
    xOnBehalfOf: '<end-user-id>',
    responsesCreateRequest: {
      model: 'auto',
      input: "Use the shell to calculate the sum of the integers from 1 to 100, then report the result.",
      tools: [{ type: 'shell', environment: { type: 'container_auto' } }],
    },
  });
  console.log(result);
  ```

  ```ts OpenAI SDK theme={null}
  import OpenAI from 'openai';

  const openai = new OpenAI({
    apiKey: '<mka1-api-key>',
    baseURL: 'https://apigw.mka1.com/api/v1/llm/',
    defaultHeaders: { 'X-On-Behalf-Of': '<end-user-id>' },
  });

  const result = await openai.post('/responses', {
    body: {
    "model": "auto",
    "input": "Use the shell to calculate the sum of the integers from 1 to 100, then report the result.",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_auto"
        }
      }
    ]
  },
  });
  console.log(result);
  ```

  ```python Python SDK theme={null}
  from meetkai_mka1 import SDK

  sdk = SDK(bearer_auth="Bearer <mka1-api-key>")

  result = sdk.llm.responses.create(
      x_on_behalf_of="<end-user-id>",
      model="auto",
      input="Use the shell to calculate the sum of the integers from 1 to 100, then report the result.",
      tools=[{"type": "shell", "environment": {"type": "container_auto"}}],
  )
  print(result)
  ```

  ```csharp C# SDK theme={null}
  using System.Collections.Generic;
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(bearerAuth: "Bearer <mka1-api-key>");

  var result = await sdk.Llm.Responses.CreateAsync(
      new ResponsesCreateRequest()
      {
          Model = "auto",
          Input = ResponsesCreateRequestInput.CreateStr("Use the shell to calculate the sum of the integers from 1 to 100, then report the result."),
          Tools = new List<ResponsesCreateRequestTool>
          {
              ResponsesCreateRequestTool.CreateShellToolDefinition(
                  new ShellToolDefinition()
                  {
                      Environment = ShellEnvironment.CreateContainerAuto(
                          new ShellEnvironmentContainerAuto()),
                  }),
          },
      },
      xOnBehalfOf: "<end-user-id>"
  );
  System.Console.WriteLine(result);
  ```

  ```bash CLI theme={null}
  mka1 llm responses create \
    -H 'X-On-Behalf-Of: <end-user-id>' \
    --model auto \
    --input '"Use the shell to calculate the sum of the integers from 1 to 100, then report the result."' \
    --tools '[{"type": "shell", "environment": {"type": "container_auto"}}]'
  ```

  ```bash Bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/responses \
    --request POST \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --header 'Content-Type: application/json' \
    --data '{
    "model": "auto",
    "input": "Use the shell to calculate the sum of the integers from 1 to 100, then report the result.",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_auto"
        }
      }
    ]
  }'
  ```
</CodeGroup>

## Analyze an uploaded file

[Upload a CSV file](/docs/files) first and replace `<file-id>` with its file ID. The automatic code-interpreter container accepts `file_ids` so the model can analyze the supplied file. This example expects a numeric `amount` column.

<CodeGroup>
  ```ts TypeScript SDK theme={null}
  const result = await sdk.llm.responses.create({
    xOnBehalfOf: '<end-user-id>',
    responsesCreateRequest: {
      model: 'auto',
      input: "Use code to read the supplied CSV and calculate the sum of its amount column. Explain the result.",
      tools: [{ type: 'code_interpreter', container: { type: 'auto', fileIds: ['<file-id>'] } }],
    },
  });
  console.log(result);
  ```

  ```ts OpenAI SDK theme={null}
  const result = await openai.post('/responses', {
    body: {
    "model": "auto",
    "input": "Use code to read the supplied CSV and calculate the sum of its amount column. Explain the result.",
    "tools": [
      {
        "type": "code_interpreter",
        "container": {
          "type": "auto",
          "file_ids": [
            "<file-id>"
          ]
        }
      }
    ]
  },
  });
  console.log(result);
  ```

  ```python Python SDK theme={null}
  result = sdk.llm.responses.create(
      x_on_behalf_of="<end-user-id>",
      model="auto",
      input="Use code to read the supplied CSV and calculate the sum of its amount column. Explain the result.",
      tools=[{"type": "code_interpreter", "container": {"type": "auto", "file_ids": ["<file-id>"]}}],
  )
  print(result)
  ```

  ```csharp C# SDK theme={null}
  var result = await sdk.Llm.Responses.CreateAsync(
      new ResponsesCreateRequest()
      {
          Model = "auto",
          Input = ResponsesCreateRequestInput.CreateStr("Use code to read the supplied CSV and calculate the sum of its amount column. Explain the result."),
          Tools = new List<ResponsesCreateRequestTool>
          {
              ResponsesCreateRequestTool.CreateCodeInterpreterToolDefinition(
                  new CodeInterpreterToolDefinition()
                  {
                      Container = Container.CreateCodeInterpreterContainerAuto(
                          new CodeInterpreterContainerAuto()
                          {
                              FileIds = new List<string> { "<file-id>" },
                          }),
                  }),
          },
      },
      xOnBehalfOf: "<end-user-id>"
  );
  System.Console.WriteLine(result);
  ```

  ```bash CLI theme={null}
  mka1 llm responses create \
    -H 'X-On-Behalf-Of: <end-user-id>' \
    --model auto \
    --input '"Use code to read the supplied CSV and calculate the sum of its amount column. Explain the result."' \
    --tools '[{"type": "code_interpreter", "container": {"type": "auto", "file_ids": ["<file-id>"]}}]'
  ```

  ```bash Bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/responses \
    --request POST \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --header 'Content-Type: application/json' \
    --data '{
    "model": "auto",
    "input": "Use code to read the supplied CSV and calculate the sum of its amount column. Explain the result.",
    "tools": [
      {
        "type": "code_interpreter",
        "container": {
          "type": "auto",
          "file_ids": [
            "<file-id>"
          ]
        }
      }
    ]
  }'
  ```
</CodeGroup>

## Reuse an existing session

Use an existing session when your application needs to prepare a workspace or retrieve files directly:

1. [Create a session](/docs/sandbox#step-1---create-a-session) and [wait for it to be running](/docs/sandbox#step-2---wait-for-it-to-be-ready).
2. [Upload your input files](/docs/sandbox#step-5---upload-and-download-files) if the task needs them.
3. Set the shell environment to `container_reference` and use that session's ID.
4. After the response finishes, inspect or download the workspace files through the Sandbox API.

The request below creates a small CSV artifact in the selected workspace. Replace `<session-id>` with the ID of the running session. Use the same API key and end-user identity used to create it.

<CodeGroup>
  ```ts TypeScript SDK theme={null}
  const result = await sdk.llm.responses.create({
    xOnBehalfOf: '<end-user-id>',
    responsesCreateRequest: {
      model: 'auto',
      input: "Use the shell to write /workspace/squares.csv with columns n and square for integers 1 through 10. Confirm the path when done.",
      tools: [{ type: 'shell', environment: { type: 'container_reference', containerId: '<session-id>' } }],
    },
  });
  console.log(result);
  ```

  ```ts OpenAI SDK theme={null}
  const result = await openai.post('/responses', {
    body: {
    "model": "auto",
    "input": "Use the shell to write /workspace/squares.csv with columns n and square for integers 1 through 10. Confirm the path when done.",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_reference",
          "container_id": "<session-id>"
        }
      }
    ]
  },
  });
  console.log(result);
  ```

  ```python Python SDK theme={null}
  result = sdk.llm.responses.create(
      x_on_behalf_of="<end-user-id>",
      model="auto",
      input="Use the shell to write /workspace/squares.csv with columns n and square for integers 1 through 10. Confirm the path when done.",
      tools=[{"type": "shell", "environment": {"type": "container_reference", "container_id": "<session-id>"}}],
  )
  print(result)
  ```

  ```csharp C# SDK theme={null}
  var result = await sdk.Llm.Responses.CreateAsync(
      new ResponsesCreateRequest()
      {
          Model = "auto",
          Input = ResponsesCreateRequestInput.CreateStr("Use the shell to write /workspace/squares.csv with columns n and square for integers 1 through 10. Confirm the path when done."),
          Tools = new List<ResponsesCreateRequestTool>
          {
              ResponsesCreateRequestTool.CreateShellToolDefinition(
                  new ShellToolDefinition()
                  {
                      Environment = ShellEnvironment.CreateContainerReference(
                          new ShellEnvironmentContainerReference()
                          {
                              ContainerId = "<session-id>",
                          }),
                  }),
          },
      },
      xOnBehalfOf: "<end-user-id>"
  );
  System.Console.WriteLine(result);
  ```

  ```bash CLI theme={null}
  mka1 llm responses create \
    -H 'X-On-Behalf-Of: <end-user-id>' \
    --model auto \
    --input '"Use the shell to write /workspace/squares.csv with columns n and square for integers 1 through 10. Confirm the path when done."' \
    --tools '[{"type": "shell", "environment": {"type": "container_reference", "container_id": "<session-id>"}}]'
  ```

  ```bash Bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/responses \
    --request POST \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --header 'Content-Type: application/json' \
    --data '{
    "model": "auto",
    "input": "Use the shell to write /workspace/squares.csv with columns n and square for integers 1 through 10. Confirm the path when done.",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_reference",
          "container_id": "<session-id>"
        }
      }
    ]
  }'
  ```
</CodeGroup>

For `code_interpreter`, pass the existing session ID as the tool's `container` string instead of an automatic-container object.

## Retrieve generated files

A model's statement that it wrote a file is not the file itself. For the existing-session example, [inspect the workspace](/docs/sandbox#step-6---inspect-the-workspace) and [download](/docs/sandbox#step-5---upload-and-download-files) `/workspace/squares.csv` using the same session ID and its session token. Check that the file exists before treating the task as complete.

Download artifacts before terminating the session or allowing it to expire. The standalone guide covers file transfer, workspace inspection, and session-token handling in each supported client.

## Session lifetime and identity

Automatically created tool sessions use the gateway's default idle timeout and can be reused for the same caller. Do not assume each response starts with an empty workspace. To control session lifetime or prepare a specific workspace, create the session explicitly and pass its ID.

Session access is scoped to the organization, team, and user. Keep `X-On-Behalf-Of` consistent when creating, using, and downloading from a session. A different end user cannot reuse that session simply by knowing its ID.

For an explicitly managed session, [terminate it](/docs/sandbox#step-7---terminate) once the response and any downloads have finished. See [lifetime and states](/docs/sandbox#lifetime-and-states) for expiration behavior.

## Inspect results and handle failures

Check the response status and error before relying on its output. Inspect tool output as well as the final answer: a completed response can still describe a command that failed. Confirm expected artifacts through the Sandbox API.

For longer execution, use [background responses](/docs/background-responses) and wait for completion before downloading artifacts or terminating the session. Avoid blindly retrying a command that may already have changed the workspace.
