Skip to main content

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)
pip install declaw python-dotenv anthropic

Code Walkthrough

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:
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

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)

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

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!
============================================================
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).