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

# Run Code

> Execute Python and JavaScript code inside agent runtimes

Execute arbitrary code natively inside the runtime. Code execution is stateful and returns structured output, including `stdout`, `stderr`, and any unhandled exceptions.

`POST /v1/agents/runtime/{runtime_id}/code/run`

## Basic (Python)

<CodeGroup>
  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  from gravixlayer import GravixLayer

  client = GravixLayer()  # defaults to cloud="aws", region="us-east-1"
  sandbox = client.runtime.create()  # defaults to template="base-small"

  # Python is the default language
  result = sandbox.run_code(code="import math\nprint(math.sqrt(81))")

  print(result.text)  # 9.0

  sandbox.kill()
  ```

  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import { GravixLayer } from 'gravixlayer';

  const client = new GravixLayer(); // defaults to cloud="aws", region="us-east-1"
  const sandbox = await client.runtime.create(); // defaults to template="base-small"

  // Python is the default language
  const result = await sandbox.runCode('import math\nprint(math.sqrt(81))');

  console.log(result.text); // 9.0

  await sandbox.kill();
  ```

  ```bash CLI theme={"theme":{"light":"github-light","dark":"github-dark"}}
  cat > /tmp/sqrt.py <<'EOF'
  import math
  print(math.sqrt(81))
  EOF

  gravixlayer runtime run "$RT" /tmp/sqrt.py --timeout 300
  ```

  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -sS -X POST "https://api.gravixlayer.ai/v1/agents/runtime/$RT/code/run" \
    -H "Authorization: Bearer $GRAVIXLAYER_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "code": "import math\nprint(math.sqrt(81))",
      "language": "python",
      "timeout": 300
    }' | jq .
  ```
</CodeGroup>

## JavaScript and contexts

Create a persistent context, then run JavaScript so state survives across calls.

<Info>
  `gravixlayer runtime run` infers language from the file extension (`.py`, `.js`) but does not accept `--context-id`. Use Python or cURL for context-bound runs.
</Info>

<CodeGroup>
  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  from gravixlayer import GravixLayer

  client = GravixLayer()  # defaults to cloud="aws", region="us-east-1"
  sandbox = client.runtime.create()  # defaults to template="base-small"

  ctx = client.runtime.create_context(sandbox.runtime_id, language="javascript")

  client.runtime.run_code(
      sandbox.runtime_id,
      code="let count = 0;",
      language="javascript",
      context_id=ctx.context_id,
  )

  result = client.runtime.run_code(
      sandbox.runtime_id,
      code="count += 5;\nconsole.log(`Count is ${count}`);",
      language="javascript",
      context_id=ctx.context_id,
      timeout=30,  # 30 second execution limit
  )

  print(result.text)  # Count is 5

  sandbox.kill()
  ```

  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import { GravixLayer } from 'gravixlayer';

  const client = new GravixLayer(); // defaults to cloud="aws", region="us-east-1"
  const sandbox = await client.runtime.create(); // defaults to template="base-small"

  // Create a persistent context to preserve state across calls
  const ctx = await sandbox.createContext({ language: 'javascript' });

  await sandbox.runCode('let count = 0;', { language: 'javascript', contextId: ctx.contextId });

  const result = await sandbox.runCode('count += 5;\nconsole.log(`Count is ${count}`);', {
    language: 'javascript',
    contextId: ctx.contextId,
    timeoutSeconds: 30,
  });

  console.log(result.text); // Count is 5

  await sandbox.kill();
  ```

  ```bash CLI theme={"theme":{"light":"github-light","dark":"github-dark"}}
  CTX=$(gravixlayer runtime code-context create "$RT" --language javascript --output json | jq -r '.context_id')
  echo "$CTX"

  # Without a context, you can still run a .js file via runtime run:
  cat > /tmp/hello.js <<'EOF'
  console.log("Hello from JavaScript")
  EOF
  gravixlayer runtime run "$RT" /tmp/hello.js --timeout 30

  # Context-bound runs: use Python or cURL with context_id.
  ```

  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  CTX=$(curl -sS -X POST "https://api.gravixlayer.ai/v1/agents/runtime/$RT/code/contexts" \
    -H "Authorization: Bearer $GRAVIXLAYER_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"language": "javascript"}' | jq -r '.id // .context_id')

  curl -sS -X POST "https://api.gravixlayer.ai/v1/agents/runtime/$RT/code/run" \
    -H "Authorization: Bearer $GRAVIXLAYER_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"code\": \"let count = 0;\", \"language\": \"javascript\", \"context_id\": \"$CTX\"}" | jq .

  curl -sS -X POST "https://api.gravixlayer.ai/v1/agents/runtime/$RT/code/run" \
    -H "Authorization: Bearer $GRAVIXLAYER_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{
      \"code\": \"count += 5;\\nconsole.log('Count is ' + count);\",
      \"language\": \"javascript\",
      \"context_id\": \"$CTX\",
      \"timeout\": 30
    }" | jq .
  ```
</CodeGroup>

## Parameters

<ParamField body="code" type="string" required>
  The source code to execute.
</ParamField>

<ParamField body="language" type="string">
  The programming language of the code. Defaults to `"python"`. Use `"javascript"` for Node.js execution.

  <Warning>
    Base templates include both Python and Node.js. Use `base-small`, `base-medium`, or `base-large`.
  </Warning>
</ParamField>

<ParamField body="context_id" type="string">
  An identifier for a persistent execution context.

  <Expandable title="Why do I need this?">
    By default, every `run_code` call executes in an isolated scope. By providing a `context_id`, variables, function definitions, and imports will persist across multiple calls.
  </Expandable>
</ParamField>

<ParamField body="environment" type="object">
  Environment variables specific to this code execution block.
</ParamField>

<ParamField body="timeout" type="integer">
  Execution timeout in seconds. Kills the process if it exceeds this limit.
</ParamField>

## Response

<ResponseField name="text" type="string">
  The standard output (`stdout`) produced by the executed code.
</ResponseField>

<ResponseField name="success" type="boolean">
  `True` if the code executed without raising unhandled exceptions.
</ResponseField>

<ResponseField name="error" type="object">
  Detailed error information if `success` is `False`. Includes `name` (e.g., `ValueError`), `value` (the error message), and `traceback` (the full stack trace).
</ResponseField>

<ResponseField name="logs" type="object">
  The raw `stdout` and `stderr` streams, formatted as lists of strings.
</ResponseField>
