@cloudflare/codemode and @cloudflare/ai-chat.
What it demonstrates
Server (src/server.ts):
AIChatAgentwithcreateCodeTool- the LLM gets a single “write code” toolDynamicWorkerExecutor- runs LLM-generated code in isolated Worker sandboxesNodeServerExecutor- alternative executor using a Node.js VM (for local dev)- SQLite-backed tools (projects, tasks, sprints, comments) via
SqlStorage - Switchable executor at runtime via HTTP endpoint
src/client.tsx):
useAgentChatfor streaming chat with message persistence- Collapsible tool cards showing generated code, results, and console output
- Settings panel to switch between Dynamic Worker and Node Server executors
- Kumo design system components with dark/light mode
src/tools.ts):
- 10 project management tools:
createProject,listProjects,createTask,listTasks,updateTask,deleteTask,createSprint,listSprints,addComment,listComments - All backed by SQLite - data persists across conversations
Why Codemode?
Traditional tool calling requires the LLM to call tools one at a time:Tool Definitions
src/tools.ts
Example Conversations
Simple creation:Executors
Codemode supports two execution modes:Dynamic Worker Executor (Production)
Runs code in isolated Cloudflare Workers:- Secure - Full sandbox isolation
- Fast - V8 isolates, no cold starts
- Scalable - Runs on Cloudflare’s edge
Node Server Executor (Development)
Runs code in a Node.js VM:- Debugging - Full Node.js inspector support
- Local - No network latency
- Quick iteration - Hot reload
Running the Example
1
Install dependencies
2
Start the example
3
Try it out
Visit http://localhost:5173 and try:
- “Create a project called Alpha”
- “Add 3 tasks to Alpha”
- “What is 17 + 25?” (simple calculation)
- “List all projects and their tasks”
4
(Optional) Start Node executor
For local debugging:Then switch to Node executor in the Settings panel.
This example uses Workers AI (no API key needed) with
@cf/zai-org/glm-4.7-flash.Key Concepts
Code Generation
The LLM receives a special “write code” tool:- Validated and transpiled
- Executed in a secure sandbox
- Results returned to the LLM
Tool Access
Generated code has access to tools via thecodemode object:
Error Handling
The LLM can handle errors in its code:Security
Codemode is safe because:- Sandboxed execution - Code runs in isolated Workers/VMs
- No file system access - Can’t read/write files
- No network access - Can’t make arbitrary HTTP requests
- Limited APIs - Only approved tools are available
- Timeout enforcement - Code execution is time-limited
Related Examples
AI Chat
Traditional tool calling with streaming
Dynamic Tools
Client-defined tools at runtime
Workflows
Multi-step workflows with approval gates
Codemode Package
Full Codemode package documentation