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

# OpenAI Code Interpreter

> Use GPT-4o-mini to generate Python code from natural language questions, then execute it securely in a Declaw sandbox. Includes a demo mode that works without an API key.

## What You'll Learn

* Sending prompts to the OpenAI chat API (`gpt-4o-mini`) to generate executable Python code
* Stripping markdown code fences from LLM responses before execution
* Writing generated code into a Declaw sandbox filesystem
* Executing the code securely with `sbx.commands.run()`
* Graceful demo mode when no API key is configured

## Prerequisites

* Declaw instance running and `DECLAW_API_KEY` / `DECLAW_DOMAIN` set
* `OPENAI_API_KEY` (optional — the example runs in demo mode without it)

<Tabs>
  <Tab title="Python">
    ```bash theme={null}
    pip install declaw python-dotenv openai
    ```
  </Tab>

  <Tab title="TypeScript">
    ```bash theme={null}
    npm install @declaw/sdk dotenv openai
    ```
  </Tab>
</Tabs>

## Code Walkthrough

<Tabs>
  <Tab title="Python">
    ### 1. Ask GPT-4o-mini to generate Python code

    The system prompt instructs the model to return **only** code — no markdown, no explanation.

    ```python theme={null}
    import openai
    from declaw import Sandbox

    client = openai.OpenAI()

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": (
                    "You are a Python code interpreter. When asked a question, "
                    "respond ONLY with Python code that computes the answer and "
                    "prints it. No markdown, no explanation, just code."
                ),
            },
            {"role": "user", "content": "What are the first 20 prime numbers?"},
        ],
        temperature=0,
    )
    ```

    ### 2. Strip code fences and execute in a sandbox

    Models occasionally wrap code in triple-backtick fences even when asked not to. Strip them before writing to disk:

    ````python theme={null}
    def strip_code_fences(code: str) -> str:
        code = code.strip()
        if code.startswith("```"):
            code = "\n".join(code.split("\n")[1:])
        if code.endswith("```"):
            code = "\n".join(code.split("\n")[:-1])
        return code.strip()

    code = strip_code_fences(response.choices[0].message.content or "")

    sbx = Sandbox.create(template="python", timeout=300)
    try:
        sbx.files.write("/tmp/solution.py", code)
        result = sbx.commands.run("python3 /tmp/solution.py", timeout=30)
        print(result.stdout)
        print(result.exit_code)
    finally:
        sbx.kill()
    ````

    ### 3. Demo mode (no API key needed)

    When `OPENAI_API_KEY` is not set the example runs pre-written code to show the Declaw integration:

    ```python theme={null}
    code = """\
    def primes(n):
        result = []
        candidate = 2
        while len(result) < n:
            if all(candidate % p != 0 for p in result):
                result.append(candidate)
            candidate += 1
        return result

    print("First 20 primes:", primes(20))
    print("Factorial of 15:", __import__('math').factorial(15))
    """

    sbx = Sandbox.create(template="python", timeout=300)
    try:
        sbx.files.write("/tmp/demo.py", code)
        result = sbx.commands.run("python3 /tmp/demo.py", timeout=30)
        print(result.stdout)
    finally:
        sbx.kill()
    ```
  </Tab>

  <Tab title="TypeScript">
    ### 1. Ask GPT-4o-mini to generate Python code

    ```typescript theme={null}
    import { Sandbox } from "@declaw/sdk";
    import OpenAI from "openai";

    const client = new OpenAI();

    const response = await client.chat.completions.create({
      model: "gpt-4o-mini",
      messages: [
        {
          role: "system",
          content:
            "You are a Python code interpreter. When asked a question, respond ONLY with Python code that computes the answer and prints it. No markdown, no explanation, just code.",
        },
        { role: "user", content: "What are the first 20 prime numbers?" },
      ],
      temperature: 0,
    });
    ```

    ### 2. Strip code fences and execute in a sandbox

    ````typescript theme={null}
    function stripCodeFences(code: string): string {
      let cleaned = code.trim();
      if (cleaned.startsWith("```")) {
        cleaned = cleaned.split("\n").slice(1).join("\n");
      }
      if (cleaned.endsWith("```")) {
        cleaned = cleaned.split("\n").slice(0, -1).join("\n");
      }
      return cleaned.trim();
    }

    const code = stripCodeFences(response.choices[0].message.content || "");

    const sbx = await Sandbox.create({ template: "python", timeout: 300 });
    try {
      await sbx.files.write("/tmp/solution.py", code);
      const result = await sbx.commands.run("python3 /tmp/solution.py", {
        timeout: 30,
      });
      console.log(result.stdout);
      console.log(result.exitCode);
    } finally {
      await sbx.kill();
    }
    ````

    ### 3. Demo mode (no API key needed)

    ```typescript theme={null}
    const code = `
    def primes(n):
        result = []
        candidate = 2
        while len(result) < n:
            if all(candidate % p != 0 for p in result):
                result.append(candidate)
            candidate += 1
        return result

    print("First 20 primes:", primes(20))
    print("Factorial of 15:", __import__('math').factorial(15))
    `.trim();

    const sbx = await Sandbox.create({ template: "python", timeout: 300 });
    try {
      await sbx.files.write("/tmp/demo.py", code);
      const result = await sbx.commands.run("python3 /tmp/demo.py", { timeout: 30 });
      console.log(result.stdout);
    } finally {
      await sbx.kill();
    }
    ```
  </Tab>
</Tabs>

## Expected Output

```
============================================================
OpenAI Code Interpreter with Declaw Sandbox
============================================================

--- Question: What are the first 20 prime numbers? ---
  Generated code:
def primes(n): ...

  Result:
stdout: First 20 primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
stderr:
exit_code: 0

============================================================
Done!
============================================================
```

<Note>
  In demo mode (no `OPENAI_API_KEY`), the output shows pre-written code results: the first 20 primes and `factorial(15) = 1307674368000`.
</Note>
