What You’ll Learn
- Sending prompts to the Google Gemini API (
gemini-2.0-flash) using the google-genai SDK
- Using
client.models.generate_content() — the newer Google AI SDK interface
- 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
GOOGLE_API_KEY (optional — the example runs in demo mode without it)
pip install declaw python-dotenv google-genai
Code Walkthrough
This example is available in Python. TypeScript support coming soon.
1. Ask Gemini to generate Python code
The google-genai SDK (the newer Google AI SDK, distinct from the older google-generativeai) uses a Client with models.generate_content():
from google import genai
from declaw import Sandbox
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=(
"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: Count the frequency of each word in "
"'the quick brown fox jumps over the lazy dog the fox the dog'"
),
)
Use google-genai (not google-generativeai). The newer SDK ships as from google import genai and uses the genai.Client() pattern shown above.
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()
code = strip_code_fences(response.text 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)
code = """\
from collections import Counter
text = "the quick brown fox jumps over the lazy dog the fox the dog"
words = text.split()
counter = Counter(words)
print("Word frequencies:")
for word, count in counter.most_common():
print(f" {word}: {count}")
print(f"\\nTotal words: {len(words)}")
print(f"Unique words: {len(counter)}")
"""
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
============================================================
Gemini Code Interpreter with Declaw Sandbox
============================================================
--- Demo: Running pre-written code in Declaw sandbox ---
Sandbox created: sbx_abc123
Output:
Word frequencies:
the: 4
fox: 2
dog: 2
quick: 1
brown: 1
jumps: 1
over: 1
lazy: 1
Total words: 12
Unique words: 8
Sandbox killed.