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)

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:

2. Strip code fences and execute in a sandbox

3. Demo mode (no API key needed)

Expected Output

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