> ## 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.

# Anthropic Code Interpreter

> Use Claude (claude-sonnet-4-20250514) 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 Anthropic Messages API (`claude-sonnet-4-20250514`) 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
* `ANTHROPIC_API_KEY` (optional — the example runs in demo mode without it)

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

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

## Code Walkthrough

<Tabs>
  <Tab title="Python">
    ### 1. Ask Claude to generate Python code

    The Anthropic SDK uses `client.messages.create()`. The instruction to return only code is embedded in the user message:

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

    client = anthropic.Anthropic()

    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        messages=[
            {
                "role": "user",
                "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.\n\n"
                    "Question: What are the first 15 Fibonacci numbers?"
                ),
            },
        ],
    )
    ```

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

    ````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()

    raw_text = response.content[0].text
    code = strip_code_fences(raw_text)

    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)

    ```python theme={null}
    code = """\
    def fibonacci(n):
        a, b = 0, 1
        result = []
        for _ in range(n):
            result.append(a)
            a, b = b, a + b
        return result

    print("First 15 Fibonacci numbers:", fibonacci(15))
    print("Sum of first 100 integers:", sum(range(1, 101)))
    """

    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 Claude to generate Python code

    ```typescript theme={null}
    import { Sandbox } from "@declaw/sdk";
    import Anthropic from "@anthropic-ai/sdk";

    const client = new Anthropic();

    const response = await client.messages.create({
      model: "claude-sonnet-4-20250514",
      max_tokens: 1024,
      messages: [
        {
          role: "user",
          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.\n\nQuestion: What are the first 15 Fibonacci numbers?",
        },
      ],
    });
    ```

    ### 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 rawText =
      response.content[0].type === "text" ? response.content[0].text : "";
    const code = stripCodeFences(rawText);

    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 fibonacci(n):
        a, b = 0, 1
        result = []
        for _ in range(n):
            result.append(a)
            a, b = b, a + b
        return result

    print("First 15 Fibonacci numbers:", fibonacci(15))
    print("Sum of first 100 integers:", sum(range(1, 101)))
    `.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

```
============================================================
Anthropic Code Interpreter with Declaw Sandbox
============================================================

--- Question: What are the first 15 Fibonacci numbers? ---
  Generated code:
def fibonacci(n): ...

  Result:
stdout: First 15 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
stderr:
exit_code: 0

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

<Note>
  In demo mode (no `ANTHROPIC_API_KEY`), the output shows pre-written code results: the first 15 Fibonacci numbers and the sum of integers 1–100 (5050).
</Note>
