Documentation Index
Fetch the complete documentation index at: https://mintlify.com/cloudflare/agents/llms.txt
Use this file to discover all available pages before exploring further.
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
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.Agent receives message
The
onChatMessage method is triggered. It converts the message history into the format expected by the AI SDK.LLM generates response
streamText() sends the messages to Workers AI and receives a streaming response.Response streams to client
toUIMessageStreamResponse() converts the AI SDK stream into a format that the useAgentChat hook understands.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
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
| Feature | Simple Chat Bot | AI Chat Example |
|---|---|---|
| Streaming | ✓ | ✓ |
| Message history | ✓ | ✓ |
| Server-side tools | ✗ | ✓ |
| Client-side tools | ✗ | ✓ |
| Tool approval | ✗ | ✓ |
| Message pruning | ✗ | ✓ |
| MCP integration | ✗ | ✓ |
| Complexity | Low | Medium |
| Best for | Simple bots | Production apps |
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