Skip to main content

POST /api/generate/stream

Generates code using AI based on a user prompt. Supports both creating new code and editing existing files with intelligent file selection.

Request body

prompt
string
required
The user’s code generation request or instruction
isEdit
boolean
Whether this is an edit operation on existing code. Defaults to false
sandboxId
string
The sandbox ID to operate on. Required when isEdit is true
context
object
Additional context for code generation
conversationId
string
Optional conversation ID for tracking multi-turn interactions

Response

Returns a server-sent events (SSE) stream with Content-Type: text/event-stream. Events are sent as JSON objects prefixed with data: .

Stream event types

heartbeat
object
Sent every 5 seconds to prevent connection timeout
status
object
Progress updates during generation
stream
object
Incremental chunks of generated content
file
object
A complete generated file
package
object
A required npm package
complete
object
Final event indicating generation is complete
error
object
Error event if generation fails

Error codes

400
Bad Request
Invalid JSON body or missing required prompt field

Example request

curl -X POST https://your-domain.com/api/generate/stream \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Create a React counter component with increment and decrement buttons",
    "isEdit": false
  }'

Example with context

curl -X POST https://your-domain.com/api/generate/stream \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Add a reset button to the counter",
    "isEdit": true,
    "sandboxId": "sb_abc123",
    "context": {
      "files": {
        "src/Counter.tsx": "export default function Counter() { ... }"
      },
      "recentMessages": [
        {
          "role": "user",
          "content": "Create a counter component"
        },
        {
          "role": "assistant",
          "content": "I created a Counter component with increment and decrement."
        }
      ]
    }
  }'

Example SSE response

data: {"type":"status","message":"Analyzing request..."}

data: {"type":"stream","data":{"content":"Creating Counter component","index":0}}

data: {"type":"file","data":{"path":"src/Counter.tsx","content":"import { useState } from 'react';\n\nexport default function Counter() { ... }"}}

data: {"type":"package","data":{"name":"react"}}

data: {"type":"complete","data":{"files":[{"path":"src/Counter.tsx","content":"..."}],"packages":["react"]}}

Smart file selection

When isEdit is true and sandboxId is provided without explicit context.files, the endpoint automatically:
  1. Retrieves the sandbox file list
  2. Uses LLM-based intent analysis to identify relevant files
  3. Fetches only the targeted file contents
  4. Falls back to App.tsx/App.jsx if no files are selected
This ensures efficient context usage while maintaining high edit accuracy.

Build docs developers (and LLMs) love