Sandbox SDK Sandbox SDK Sandbox SDK · Lab 4/7 Lab 4/7 Lab 4/7 · 30 phút · 30 min · 30 នាទី

04

Sinh code bằng Workers AI AI-Powered Code Generation បង្កើត code ដោយ Workers AI

Gắn Workers AI để sinh và chạy code từ prompt — pattern vibe coding: input → LLM → extract → sandbox → output. Integrate Workers AI to generate and execute code from natural language prompts. Build the complete 'vibe coding' pattern: input → LLM → extract → sandbox → output. ភ្ជាប់ Workers AI ដើម្បីបង្កើត និងរត់ code ពី prompt — pattern vibe coding៖ input → LLM → extract → sandbox → output។

Nội dung bước (lệnh, code) giữ nguyên tiếng Anh từ nguồn chính thức. Step body (commands, code) stays in English from the official source. ខ្លឹមសារជំហាន (ពាក្យបញ្ជា និង code) រក្សាភាសាអង់គ្លេសពីប្រភពផ្លូវការ។ labs.cloudflare.dev ↗

Cần trước Prerequisites តម្រូវការជាមុន

  • Đã xong bước 3 Completed Step 3 បានបញ្ចប់ជំហាន 3
  • Code executor đang chạy Code executor working Code executor កំពុងដំណើរការ
  • Hiểu LLM ở mức cơ bản Basic understanding of LLMs យល់ LLM កម្រិតមូលដ្ឋាន

Bạn sẽ làm được Learning objectives គោលបំណងសិក្សា

  • Thêm binding Workers AI vào project Add a Workers AI binding to your project បន្ថែម binding Workers AI ទៅ project
  • Sinh code từ ngôn ngữ tự nhiên bằng LLM Generate code from natural language using an LLM បង្កើត code ពីភាសាធម្មជាតិដោយ LLM
  • Trích code block chắc chắn từ response LLM Robustly extract code blocks from LLM responses ស្រង់ code block ឲ្យជាក់លាក់ពី response LLM
  • Nối sinh code AI với chạy sandbox một cách an toàn Chain AI generation with sandbox execution safely ភ្ជាប់ការបង្កើត code AI ជាមួយការរត់ sandbox ឲ្យសុវត្ថិភាព
  • Xử lý AI fail mà không sập luồng chính Handle AI failures gracefully ដោះស្រាយ AI fail ដោយមិនធ្វើឲ្យលំហូរគន្លឹះដួល

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:

json
{
  "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:

bash
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:

typescript
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:

typescript
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:

typescript
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.
bash
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)"}'
json
{
  "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:

bash
# 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:

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