Skip to main content

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

Code Walkthrough

1. Ask GPT-4o-mini to generate Python code

The system prompt instructs the model to return only code — no markdown, no explanation.
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:
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:
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()

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!
============================================================
In demo mode (no OPENAI_API_KEY), the output shows pre-written code results: the first 20 primes and factorial(15) = 1307674368000.