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)

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.

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:

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:

Expected Output

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