Learn how to leverage Cloudflare's developer ecosystem to create powerful AI
applications using Workers and Workers AI.
This tutorial guides you through building three different AI-powered applications using Cloudflare Workers and Workers AI. You'll learn how to:
Note: Cloudflare's development ecosystem offers a powerful set of tools for building applications at the edge. Workers allows you to run serverless functions globally, while Workers AI brings machine learning capabilities directly to your applications without the need for external APIs or services.
This tutorial was created to help developers get started with Cloudflare's AI tools quickly. The examples provided here demonstrate how easy it is to build sophisticated AI applications without managing complex infrastructure or dependencies. Whether you're building a personal project or enterprise application, the techniques shown here will help you leverage Cloudflare's global network for fast, reliable AI-powered applications.
This tutorial is entirely dashboard focused to welcome coders at all levels.
Before you begin, you'll need:
Choose one of the following applications to build:
This simple application allows users to input text and receive an AI-generated summary. You have probably seen this sort of app in the wild.
export default {
async fetch(request, env) {
// Check if AI binding exists
if (!env.AI) {
return new Response("Error: AI binding is not configured. Please add an AI binding named 'AI' in the Cloudflare dashboard.", {
status: 500,
headers: { "Content-Type": "text/plain" }
});
}
if (request.method === "POST") {
try {
// Get the text from the request
const requestText = await request.text();
let text;
try {
// Try to parse as JSON
const jsonData = JSON.parse(requestText);
text = jsonData.text;
} catch (e) {
// If not valid JSON, use the text directly
text = requestText;
}
if (!text || text.trim().length === 0) {
return new Response(JSON.stringify({ error: "No text provided" }), {
status: 400,
headers: { "Content-Type": "application/json" }
});
}
try {
// Generate a concise summary with token efficiency in mind
const summary = await env.AI.run("@cf/mistral/mistral-7b-instruct-v0.1", {
messages: [
{
role: "user",
content: `Summarise the following text very concisely. Your summary should be no longer than 3-4 sentences and focus only on the most important points:
${text}`
}
],
max_tokens: 256 // Keep the default to preserve tokens
});
return new Response(JSON.stringify({
summary: summary.response
}), {
headers: { "Content-Type": "application/json" }
});
} catch (aiError) {
// Detailed AI error
return new Response(JSON.stringify({
error: "AI Error",
details: aiError.message || "Unknown AI error",
stack: aiError.stack
}), {
status: 500,
headers: { "Content-Type": "application/json" }
});
}
} catch (error) {
// Generic error
return new Response(JSON.stringify({
error: "Server Error",
message: error.message || "Unknown error",
stack: error.stack
}), {
status: 500,
headers: { "Content-Type": "application/json" }
});
}
}
// Return a simple HTML form for GET requests
return new Response(`
<!DOCTYPE html>
<html>
<head>
<title>Text Summariser</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f9f9fa;
color: #333;
line-height: 1.6;
}
h1, h2 {
color: #f48120;
margin-bottom: 15px;
}
textarea {
width: 100%;
height: 200px;
margin-bottom: 15px;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-family: inherit;
font-size: 16px;
}
button {
background-color: #f48120;
color: white;
border: none;
padding: 10px 18px;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #e67510;
}
button:disabled {
background-color: #f4b583;
cursor: not-allowed;
}
#summary {
margin-top: 20px;
padding: 15px;
border: 1px solid #e4e4e7;
min-height: 100px;
background-color: white;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.loading { color: #666; font-style: italic; }
.error { color: #e53e3e; background-color: #fee; padding: 10px; border-radius: 6px; }
.card {
background-color: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
p {
margin-bottom: 15px;
}
</style>
</head>
<body>
<div class="card">
<h1>Text Summariser</h1>
<p>Enter text below and click "Summarise" to get an AI-generated summary.</p>
<textarea id="text" placeholder="Enter text to summarise..."></textarea>
<button id="summariseBtn" onclick="summarise()">Summarise</button>
</div>
<div class="card">
<h2>Summary</h2>
<div id="summary"></div>
</div>
<script>
async function summarise() {
const text = document.getElementById('text').value;
if (!text) return alert('Please enter some text');
const summaryEl = document.getElementById('summary');
const button = document.getElementById('summariseBtn');
summaryEl.innerHTML = '<p class="loading">Generating summary...</p>';
button.disabled = true;
try {
const response = await fetch(window.location.href, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text })
});
const data = await response.json();
if (data.error) {
summaryEl.innerHTML = '<p class="error">Error: ' + (data.details || data.message || data.error) + '</p>';
console.error('Full error:', data);
} else {
summaryEl.innerHTML = data.summary;
}
} catch (error) {
summaryEl.innerHTML = '<p class="error">Error: ' + error.message + '</p>';
console.error(error);
} finally {
button.disabled = false;
}
}
</script>
</body>
</html>
`, {
headers: { "Content-Type": "text/html" }
});
}
};
This application allows users to upload an image and get AI-generated captions in multiple languages.
This application allows users to upload text documents, process them with AI, and ask questions about the content. Think Google's NotebookLM.
Before we create the Worker, we need to set up a Vectorize index using the Cloudflare API as there's no dashboard option for this.
Now that you've built one (or all) of these AI-powered applications with Cloudflare Workers, here are some ways to enhance them:
Cloudflare's ecosystem provides all the tools you need to build, deploy, and scale AI-powered applications at the edge. Explore the Cloudflare Developers documentation to learn more.
Remember: While Workers AI is powerful and convenient, it's important to implement proper safeguards and content moderation in production applications to prevent misuse.