This is a simplified chat bot example. For a full-featured AI chat application with tools, approval workflows, and advanced features, see the AI Chat Example.
What it demonstrates
- Persistent message history - Messages stored in agent state
- Streaming responses - Real-time text streaming to the client
- Simple AI integration - Using Workers AI (no API key needed)
- State management - Chat history survives restarts
- React integration - Clean UI with
useAgentanduseAgentChat
Server Implementation
src/server.ts
Client Implementation
src/client.tsx
How It Works
1
User sends message
When the user submits the form,
sendMessage(input) is called. This adds the user’s message to the agent’s message history.2
Agent receives message
The
onChatMessage method is triggered. It converts the message history into the format expected by the AI SDK.3
LLM generates response
streamText() sends the messages to Workers AI and receives a streaming response.4
Response streams to client
toUIMessageStreamResponse() converts the AI SDK stream into a format that the useAgentChat hook understands.5
UI updates in real-time
As the response streams in, the
messages array updates automatically, showing the AI’s response word by word.Message History
Messages are automatically stored in SQLite byAIChatAgent:
- Page refreshes
- Agent hibernation
- Worker redeployments
Streaming Responses
The response streams in chunks:Running the Example
1
Install dependencies
2
Start development server
3
Try it out
Visit http://localhost:5173 and start chatting:
- “Hello!” - Simple greeting
- “Tell me a joke” - Request for content
- “What’s 25 * 17?” - Math question
- “Write a haiku about clouds” - Creative task
This example uses Workers AI (no API key needed) with the
@cf/zai-org/glm-4.7-flash model. It’s free and runs on Cloudflare’s edge network.Customization
Change the System Prompt
Limit Message History
Use a Different Model
Comparison: Simple Bot vs AI Chat Example
Next Steps
AI Chat Example
Full-featured chat with tools and approval
Dynamic Tools
Client-defined tools for chat agents
Codemode
LLMs write code to orchestrate tools
AI Chat Guide
In-depth guide to building chat agents
Extending This Example
Ideas for enhancements:- Add tools - Let the bot check weather, search, calculate, etc.
- User avatars - Show profile pictures for each message
- Typing indicator - Show when the bot is thinking
- Message timestamps - Display when each message was sent
- Clear history - Add a button to start a new conversation
- Export chat - Download the conversation as text or JSON
- Voice input - Use browser speech recognition API
- Multiple bots - Switch between different AI personalities