Bước 1: Thêm binding Workers AI Step 1: Add the Workers AI Binding ជំហាន 1: បន្ថែម binding Workers AI
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- Workers AI configured in your project and accessible from your Worker.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Workers AI is the fastest way to run LLMs on Cloudflare — no external API keys needed for local development.
Open wrangler.jsonc and add the AI binding:
Open wrangler.jsonc and add the AI binding:
Open wrangler.jsonc and add the AI binding:
{
"name": "my-sandbox",
"main": "src/index.ts",
...
"ai": {
"binding": "AI"
},
"containers": [{ ... }],
"durable_objects": { ... },
"migrations": [ ... ]
} If you’re using TypeScript and have a generated worker-configuration.d.ts, regenerate it:
If you’re using TypeScript and have a generated worker-configuration.d.ts, regenerate it:
If you’re using TypeScript and have a generated worker-configuration.d.ts, regenerate it:
npm run cf-typegen Otherwise, you can manually add the AI type to src/index.ts for autocomplete:
Otherwise, you can manually add the AI type to src/index.ts for autocomplete:
Otherwise, you can manually add the AI type to src/index.ts for autocomplete:
interface Env {
Sandbox: DurableObjectNamespace;
AI: Ai;
} Bước 2: Tạo endpoint /vibe Step 2: Create the /vibe Endpoint ជំហាន 2: បង្កើត endpoint /vibe
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- A complete AI code executor endpoint that takes a prompt and returns execution results.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- This single endpoint demonstrates the full vibe coding loop from natural language to running code.
Add a helper function to extract code from LLM responses, then add the /vibe route. Open src/index.ts and add before the export default:
Add a helper function to extract code from LLM responses, then add the /vibe route. Open src/index.ts and add before the export default:
Add a helper function to extract code from LLM responses, then add the /vibe route. Open src/index.ts and add before the export default:
function extractCodeFromResponse(response: string): string {
// Try to find a fenced code block (```js, ```javascript, ```typescript, etc.)
const fencedMatch = response.match(
/```(?:javascript|js|typescript|ts|node)?\n?([\s\S]*?)```/,
);
if (fencedMatch) return fencedMatch[1].trim();
// Try inline code as a fallback
const inlineMatch = response.match(/`([^`\n]+)`/);
if (inlineMatch && inlineMatch[1].includes(";")) return inlineMatch[1];
// Return the raw response — maybe the LLM returned code directly
return response.trim();
} Now add the route inside your fetch handler:
Now add the route inside your fetch handler:
Now add the route inside your fetch handler:
if (url.pathname === "/vibe" && request.method === "POST") {
const { input } = (await request.json()) as { input: string };
if (!input || typeof input !== "string") {
return Response.json({ error: "input is required" }, { status: 400 });
}
// Step 2: Generate code with Workers AI
const aiResponse = await env.AI.run("@cf/zai-org/glm-4.7-flash", {
messages: [
{
role: "system",
content: `You are a JavaScript developer. Based on the user's request, write correct JavaScript code.
Return ONLY the code in a single fenced code block (\`\`\`javascript ... \`\`\`).
Do not include any explanation, comments outside the code, or markdown other than the code block.`,
},
{ role: "user", content: input },
],
});
// Step 3: Extract the code from the LLM response
const extractedCode = extractCodeFromResponse(
aiResponse.choices[0].message.content,
);
// Step 4: Execute the code in the sandbox
const ctx = await sandbox.createCodeContext({ language: "javascript" });
const result = await sandbox.runCode(extractedCode, { context: ctx });
// Step 5: Return results
return Response.json({
prompt: input,
generatedCode: extractedCode,
execution: {
success: !result.error,
stdout: result.logs.stdout,
stderr: result.logs.stderr,
error: result.error,
},
});
} Bước 3: Test cả pipeline Step 3: Test the Full Pipeline ជំហាន 3: Test pipeline ទាំងមូល
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- A working end-to-end AI code generation and execution flow.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Validates the complete pipeline from natural language prompt to sandbox execution result.
curl -X POST http://localhost:8787/vibe \
-H "Content-Type: application/json" \
-d '{"input": "write a function to calculate the factorial of a number and print factorial(7)"}' {
"prompt": "write a function to calculate the factorial of a number and print factorial(7)",
"generatedCode": "function factorial(n) {\n if (n <= 1) return 1;\n return n * factorial(n - 1);\n}\nconsole.log(factorial(7));",
"execution": {
"success": true,
"stdout": ["5040"],
"stderr": [],
"error": null
}
} Try a few more prompts:
Try a few more prompts:
Try a few more prompts:
# Data manipulation
curl -X POST http://localhost:8787/vibe \
-H "Content-Type: application/json" \
-d '{"input": "create an array of the first 10 fibonacci numbers and print each one"}'
# String processing
curl -X POST http://localhost:8787/vibe \
-H "Content-Type: application/json" \
-d '{"input": "write a function that reverses a string and test it with hello world"}' Bước 4: Xử lý lỗi chắc chắn Step 4: Add Robust Error Handling ជំហាន 4: ដោះស្រាយ error ឲ្យរឹងមាំ
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- A production-quality handler that gracefully deals with AI failures and bad code.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- AI calls can fail, the network can drop, and LLMs produce broken code — always handle these cases.
Replace the /vibe handler with this version that wraps each stage in its own error boundary:
Replace the /vibe handler with this version that wraps each stage in its own error boundary:
Replace the /vibe handler with this version that wraps each stage in its own error boundary:
if (url.pathname === "/vibe" && request.method === "POST") {
try {
const { input } = (await request.json()) as { input: string };
if (!input || typeof input !== "string") {
return Response.json({ error: "input is required" }, { status: 400 });
}
// Generate code — catch AI-specific failures
let generatedCode: string;
try {
const aiResponse = await env.AI.run("@cf/zai-org/glm-4.7-flash", {
messages: [
{
role: "system",
content: `You are a JavaScript developer. Based on the user's request, write correct JavaScript code.
Return ONLY the code in a single fenced code block (\`\`\`javascript ... \`\`\`).
Do not include any explanation, comments outside the code, or markdown other than the code block.`,
},
{ role: "user", content: input },
],
});
generatedCode = extractCodeFromResponse(
aiResponse.choices[0].message.content,
);
} catch (aiErr) {
return Response.json(
{
error: "AI generation failed",
details: aiErr instanceof Error ? aiErr.message : "Unknown AI error",
},
{ status: 502 },
);
}
// Execute — the sandbox itself is isolated, so execution errors are safe
const ctx = await sandbox.createCodeContext({ language: "javascript" });
const result = await sandbox.runCode(generatedCode, { context: ctx });
return Response.json({
prompt: input,
generatedCode,
execution: {
success: result.code === 0,
stdout: result.logs.stdout,
stderr: result.logs.stderr,
error: result.error,
},
});
} catch (err) {
return Response.json(
{ error: err instanceof Error ? err.message : "Request failed" },
{ status: 500 },
);
}
} ✅ AI code executor working! You’ve built the complete vibe coding loop. Next, you’ll go further and create live, running app previews inside the sandbox.
✅ AI code executor working! You’ve built the complete vibe coding loop. Next, you’ll go further and create live, running app previews inside the sandbox.
✅ AI code executor working! You’ve built the complete vibe coding loop. Next, you’ll go further and create live, running app previews inside the sandbox.