iTranslated by AI
Trying Out Cloudflare Workers AI + Vectorize
Overview
In this article, I would like to try out the basic usage of Cloudflare Workers AI and Vectorize through a hands-on approach. I will try text generation and multilingual translation using LLM models with Workers AI, building and searching a vector database with Vectorize, and finally, a sample combining both Workers AI and Vectorize.
List of models available in Workers AI
Cloudflare Workers AI catalogs more than 50 OSS models so that they can be called immediately via "serverless GPUs," allowing a wide range of tasks from text generation to image generation and speech recognition to be handled with the same API.
Development Environment
$ node -v
v22.7.0
$ yarn -v
1.22.22
Testing a Simple Workers AI Configuration
First, I want to see what Workers AI is like.
I'll start by setting up the environment right away.
$ mkdir cloudflare-workers-ai-example
$ cd cloudflare-workers-ai-example
$ npm create cloudflare@latest
# I created the project with the following selections
╭ Create an application with Cloudflare Step 1 of 3
│
├ In which directory do you want to create your application?
│ dir ./app
│
├ What would you like to start with?
│ category Hello World example
│
├ Which template would you like to use?
│ type Worker only
│
├ Which language do you want to use?
│ lang TypeScript
│
├ Copying template files
│ files copied to project directory
│
├ Updating name in `package.json`
│ updated `package.json`
│
├ Installing dependencies
│ installed via `npm install`
│
╰ Application created
╭ Configuring your application for Cloudflare Step 2 of 3
│
├ Installing wrangler A command line tool for building Cloudflare Workers
│ installed via `npm install wrangler --save-dev`
│
├ Retrieving current workerd compatibility date
│ compatibility date 2025-06-06
│
├ Generating types for your application
│ generated to `./worker-configuration.d.ts` via `npm run cf-typegen`
│
├ You're in an existing git repository. Do you want to use git for version control?
│ no git
│
╰ Application configured
╭ Deploy with Cloudflare Step 3 of 3
│
├ Do you want to deploy your application?
│ no deploy via `npm run deploy`
│
╰ Done
Once the project is created, add the following to wrangler.jsonc.
{
// ....
"observability": {
"enabled": true
},
// 👇 Add
"ai": {
"binding": "AI"
}
}
Next, install the necessary package.
npm install @cloudflare/ai
Either add the following to Env in worker-configuration.d.ts,
interface Env extends Cloudflare.Env {
AI: Ai; // Add
}
or update worker-configuration.d.ts using the following command.
npx wrangler types
Change src/index.ts to the following.
import { Ai } from '@cloudflare/ai';
export default {
async fetch(request, env) {
const ai = new Ai(env.AI);
const input = { prompt: "What's the origin of the phrase 'Hello, World'" };
const output = await ai.run('@cf/meta/llama-2-7b-chat-int8', input);
return new Response(JSON.stringify(output));
},
} satisfies ExportedHandler<Env>;
Now we just need to run it. However, since Workers AI cannot be run locally, I will use the --remote flag to run it on the Cloudflare environment from my local machine.
Log in beforehand.
$ npx wrangler login
# Confirm if you logged in correctly 👇
$ npx wrangler whoami
Once logged in, try running it with the command below.
npx wrangler dev --remote
After it starts, accessing http://localhost:8787/ in your browser will return a response like this.
{
"response":"What a great question!\n\nThe phrase \"Hello, World\" has a fascinating history! It originated in the early days of computer programming, specifically in the 1970s. The phrase was first used as a test message in the development of programming languages and operating systems.\n\nThe most commonly cited source of the phrase is Brian Kernighan, a computer scientist who worked at Bell Labs, a research and development organization. In 1973, Kernighan and his colleague, Dennis Ritchie, created the C programming language. They used \"Hello, World\" as a test program to ensure that their language was working correctly. The program printed the phrase \"Hello, World\" to the screen, and it has since become a standard phrase in programming culture.\n\nThe phrase was likely chosen because it was a simple, yet effective, way to test the basic functionality of a program. It's also a friendly and approachable greeting, which has contributed to its widespread adoption.\n\nOver time, the phrase has become a cultural phenomenon, symbolizing the beginning of a new program, a new project, or even a new era in technology. It's often used as a placeholder or a test message in various programming contexts, such as:\n\n1. Programming languages: Many programming languages, including C,",
"usage":{
"prompt_tokens":56,
"completion_tokens":256,
"total_tokens":312
}
}
Trying Another Model
The model we just tried was llama-2-7b-chat-int8, which is characterized by:
A lightweight version of the conversation-optimized LLM Llama 2-Chat released by Meta, with 7B (≈7 billion) parameters, quantized to int8 for inference. It has an 8k token context window to support relatively long inputs, adopts a Transformer-based architecture, and is strong in natural dialogue and text generation.
Next, I'll try the m2m100-1.2b model. Its features are as follows:
A 1.2 billion parameter Transformer encoder-decoder LLM released by Meta (formerly Facebook). Its biggest feature is its "Many-to-Many" design, which can handle translations for 100 languages × 99 directions = 9,900 combinations directly without going through English, maintaining high accuracy even between low-resource languages.
So, let's try translating from English to Japanese. Replace the previous src/index.ts with the following.
import { Ai } from '@cloudflare/ai';
export default {
async fetch(request, env) {
const ai = new Ai(env.AI);
const output = await ai.run('@cf/meta/m2m100-1.2b', {
text: "Workers AI allows you to run AI models in a serverless way, without having to worry about scaling, maintaining, or paying for unused infrastructure. You can invoke models running on GPUs on Cloudflare's network from your own code — from Workers, Pages, or anywhere via the Cloudflare API.",
source_lang: 'english',
target_lang: 'japanese',
});
return new Response(JSON.stringify(output));
},
} satisfies ExportedHandler<Env>;
After running it and accessing http://localhost:8787/, the following response was returned.
{
"translated_text":"Workers AI を使用すると、Serverless で AI モデルを実行できますが、未使用のインフラストラクチャのスケーリング、メンテナンス、または支払いについて心配する必要はありません。Cloudflare のネットワーク上の GPU で動作するモデルは、Workers、Pages から、または Cloudflare API を通じてどこからでも、独自のコードから呼び出すことができます。",
"usage":{
"prompt_tokens":76,
"completion_tokens":104,
"total_tokens":180
}
}
It seems to have translated it quite well.
Testing a Simple Cloudflare Vectorize Configuration
I’ll proceed by referring to the following article:
I'll continue using the cloudflare-workers-ai-example project from earlier.
First, create a Vectorize index on Cloudflare.
$ npx wrangler vectorize create tutorial-index --dimensions=32 --metric=euclidean
Creating index: 'tutorial-index'
✅ Successfully created a new Vectorize index: 'tutorial-index'
📋 To start querying from a Worker, add the following binding configuration to your wrangler.json file:
{
"vectorize": [
{
"binding": "VECTORIZE",
"index_name": "tutorial-index"
}
]
}
The number of vector dimensions (32) and the metric are set as per the reference article. These two parameters can only be determined at creation time and cannot be changed, so they should be considered based on your requirements.
Note: The metric is used to determine similarity. It seems you can specify euclidean (Euclidean distance), cosine (Cosine distance), or dot product. See below for an explanation of each.
LLM explanation of Euclidean distance, Cosine distance, and Dot product
To summarize the key points:
Euclidean distance is "measuring distance straight with a ruler," Cosine distance is "the difference in the angle the vectors create," and Dot product is a numerical representation of "how much they share the same direction." None of these produce strange values like "-5 meters"; values greater than 0 or closer to 0 indicate similarity/closeness, but what is being measured (length vs. direction) differs.
What are distance and direction?
- When placing points or arrows (vectors) in a 2D plane or 3D space, "how far apart they are" and "which direction they are facing" are separate pieces of information. (datacamp.com)
- It helps to remember that distance-based metrics measure the "length" of the vector, cosine-based metrics measure the angle, and dot product measures the degree of overlap in direction. (betterexplained.com, geeksforgeeks.org)
Euclidean Distance: "Straight-line distance" measured with a ruler
| Concept | Mathematical Point |
|---|---|
| Imagine pulling a string tight between two points and measuring its length with a ruler. | Derived from the Pythagorean theorem: straight-line distance = √((x₂−x₁)²+(y₂−y₁)²…). |
- You can think of it as "the distance a bird flies in a straight line." (geeksforgeeks.org)
- Even as dimensions increase, the procedure of "summing the squares of the differences in each coordinate and taking the square root" remains the same. (cuemath.com, byjus.com)
- The advantage is that it’s intuitive: the larger the number, the further apart; the smaller the number, the closer. (youtube.com)
Cosine Distance (Cosine Similarity): Looking at the "angle" of vectors
| Concept | Mathematical Point |
|---|---|
| The smaller the angle between two arrows, the more "similar" they are. | cos θ = (𝐚・𝐛)/(‖𝐚‖‖𝐛‖). Similarity = cos θ; Distance = 1 − cos θ is commonly used. |
- It's easier to imagine it as normalizing all lengths to 1 and then just comparing the angles. (medium.com)
- If the angle is 0°, cos θ = 1 (exactly the same direction); if it's 90°, it's 0 (orthogonal = completely different direction). Values range from -1 to 1. A higher value like 0.8 means they are more similar. (geeksforgeeks.org, datastax.com)
- This is often used for document comparison to see if the "topic is the same even if the length of the text differs." (machinelearningplus.com)
- If you watch a video, animations showing "the bar going down as the angle opens up" are easy to understand. (youtube.com)
Dot Product (Inner Product): Measuring the degree of overlap in direction
| Concept | Mathematical Point |
|---|---|
| It's like dropping one arrow as a "shadow" onto the other and multiplying their lengths. | 𝐚・𝐛 = Σ aᵢbᵢ |
- It's easy to determine: a positive value means "roughly the same direction," 0 means orthogonal, and a negative value means the opposite direction. (khanacademy.org, mathsisfun.com)
- It is also called the "scalar product" because multiplying two vectors results in just a number, not a vector. (betterexplained.com)
- It also appears in physics, such as when calculating work (energy) using force and distance. (youtube.com)
How to choose between them?
| Scenario | Recommended Metric | Reason |
|---|---|---|
| Measuring the "actual distance" between two points on a map | Euclidean Distance | You simply want to know how far apart they are in a straight line |
| Comparing if the "content is similar" for text or images | Cosine Distance / Similarity | It's OK if the number of words or pixels (= length) differs, as long as the direction (feature ratio) is similar |
| Quantifying the overlap of directions, such as the relationship between the direction of force and direction of movement | Dot Product | You can determine both direction (positive/negative) and magnitude in one go |
- It's useful to remember: length itself matters → Euclidean, only direction matters → Cosine, direction + strength combined into one number → Dot Product. (geeksforgeeks.org, datastax.com, khanacademy.org)
Summary
| Metric | What does it measure? | Value Range | Meaning of "Close to 0" |
|---|---|---|---|
| Euclidean Distance | Straight-line distance between points | 0 to ∞ | Very close |
| Cosine Distance (1−cos θ) | Angular difference between vectors | 0 to 2 | Direction is almost the same |
| Dot Product | Directional overlap + Magnitude | -∞ to ∞ | Directions are orthogonal (= 0) |
I hope this helps you grasp the differences between the three approaches: "length," "angle," and "overlap of direction." Regardless of the data, decide "what you want to compare" first, and then choose the perfect metric for it.
Next, as shown in the terminal output, add the following to wrangler.jsonc.
{
"vectorize": [
{
"binding": "VECTORIZE",
"index_name": "tutorial-index"
}
]
}
Also update worker-configuration.d.ts accordingly.
declare namespace Cloudflare {
interface Env {
VECTORIZE: VectorizeIndex; // Add manually or run npx wrangler types
AI: Ai;
}
}
Next, let's actually register vectors into the index. Modify the previous src/index.ts as follows.
import { Ai } from '@cloudflare/ai';
const sampleVectors: Array<VectorizeVector> = [
{
id: '1',
values: [
0.12, 0.45, 0.67, 0.89, 0.23, 0.56, 0.34, 0.78, 0.12, 0.9, 0.24, 0.67, 0.89, 0.35, 0.48, 0.7, 0.22, 0.58, 0.74, 0.33, 0.88, 0.66,
0.45, 0.27, 0.81, 0.54, 0.39, 0.76, 0.41, 0.29, 0.83, 0.55,
],
metadata: { url: '/products/sku/13913913' },
},
{
id: '2',
values: [
0.14, 0.23, 0.36, 0.51, 0.62, 0.47, 0.59, 0.74, 0.33, 0.89, 0.41, 0.53, 0.68, 0.29, 0.77, 0.45, 0.24, 0.66, 0.71, 0.34, 0.86, 0.57,
0.62, 0.48, 0.78, 0.52, 0.37, 0.61, 0.69, 0.28, 0.8, 0.53,
],
metadata: { url: '/products/sku/10148191' },
},
{
id: '3',
values: [
0.21, 0.33, 0.55, 0.67, 0.8, 0.22, 0.47, 0.63, 0.31, 0.74, 0.35, 0.53, 0.68, 0.45, 0.55, 0.7, 0.28, 0.64, 0.71, 0.3, 0.77, 0.6, 0.43,
0.39, 0.85, 0.55, 0.31, 0.69, 0.52, 0.29, 0.72, 0.48,
],
metadata: { url: '/products/sku/97913813' },
},
{
id: '4',
values: [
0.17, 0.29, 0.42, 0.57, 0.64, 0.38, 0.51, 0.72, 0.22, 0.85, 0.39, 0.66, 0.74, 0.32, 0.53, 0.48, 0.21, 0.69, 0.77, 0.34, 0.8, 0.55,
0.41, 0.29, 0.7, 0.62, 0.35, 0.68, 0.53, 0.3, 0.79, 0.49,
],
metadata: { url: '/products/sku/418313' },
},
{
id: '5',
values: [
0.11, 0.46, 0.68, 0.82, 0.27, 0.57, 0.39, 0.75, 0.16, 0.92, 0.28, 0.61, 0.85, 0.4, 0.49, 0.67, 0.19, 0.58, 0.76, 0.37, 0.83, 0.64,
0.53, 0.3, 0.77, 0.54, 0.43, 0.71, 0.36, 0.26, 0.8, 0.53,
],
metadata: { url: '/products/sku/55519183' },
},
];
export default {
async fetch(request, env) {
const path = new URL(request.url).pathname;
// Previous Workers AI sample
if (path.startsWith('/ai')) {
const ai = new Ai(env.AI);
const output = await ai.run('@cf/meta/m2m100-1.2b', {
text: "Workers AI allows you to run AI models in a serverless way, without having to worry about scaling, maintaining, or paying for unused infrastructure. You can invoke models running on GPUs on Cloudflare's network from your own code — from Workers, Pages, or anywhere via the Cloudflare API.",
source_lang: 'english',
target_lang: 'japanese',
});
return new Response(JSON.stringify(output));
}
if (path.startsWith('/insert')) {
const inserted = await env.VECTORIZE.insert(sampleVectors);
return Response.json(inserted);
}
return new Response('nothing to do... yet', { status: 404 });
},
} satisfies ExportedHandler<Env>;
The implementation is set up to register sampleVectors when a request is made to /insert. Let's try registering it right away.
$ npx wrangler dev --remote
# In a separate terminal
$ curl http://localhost:8787/insert
{
"mutationId":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
Next, let's actually query and check. Add the following to src/index.ts.
export default {
async fetch(request, env) {
const path = new URL(request.url).pathname;
// ....
// 👇 Add
if (path.startsWith('/query')) {
const queryVector: Array<number> = [
0.13, 0.25, 0.44, 0.53, 0.62, 0.41, 0.59, 0.68, 0.29, 0.82, 0.37, 0.5, 0.74, 0.46, 0.57, 0.64, 0.28, 0.61, 0.73, 0.35, 0.78, 0.58,
0.42, 0.32, 0.77, 0.65, 0.49, 0.54, 0.31, 0.29, 0.71, 0.57,
];
const matches = await env.VECTORIZE.query(queryVector, {
topK: 3,
returnValues: true,
returnMetadata: 'all',
});
return Response.json({ matches });
}
return new Response('nothing to do... yet', { status: 404 });
},
} satisfies ExportedHandler<Env>;
Let's see if we can query correctly.
$ curl http://localhost:8787/query
{
"matches":{
"count":3,
"matches":[
{
"id":"4",
"score":0.46348256,
"values":[
0.17, 0.29, 0.42, 0.57, 0.64, 0.38, 0.51, 0.72, 0.22, 0.85, 0.39,
0.66, 0.74, 0.32, 0.53, 0.48, 0.21, 0.69, 0.77, 0.34, 0.8, 0.55, 0.41,
0.29, 0.7, 0.62, 0.35, 0.68, 0.53, 0.3, 0.79, 0.49
],
"metadata":{
"url":"/products/sku/418313"
}
},
{
"id":"3",
"score":0.52920616,
"values":[
0.21, 0.33, 0.55, 0.67, 0.8, 0.22, 0.47, 0.63, 0.31, 0.74, 0.35, 0.53,
0.68, 0.45, 0.55, 0.7, 0.28, 0.64, 0.71, 0.3, 0.77, 0.6, 0.43, 0.39,
0.85, 0.55, 0.31, 0.69, 0.52, 0.29, 0.72, 0.48
],
"metadata":{
"url":"/products/sku/97913813"
}
},
{
"id":"2",
"score":0.6337869,
"values":[
"values": [
0.14, 0.23, 0.36, 0.51, 0.62, 0.47, 0.59, 0.74, 0.33, 0.89, 0.41,
0.53, 0.68, 0.29, 0.77, 0.45, 0.24, 0.66, 0.71, 0.34, 0.86, 0.57,
0.62, 0.48, 0.78, 0.52, 0.37, 0.61, 0.69, 0.28, 0.8, 0.53
],
"metadata":{
"url":"/products/sku/10148191"
}
}
]
}
}
It seems to be querying correctly ✨
Testing Workers AI + Vectorize
Finally, I would like to try creating a pseudo-RAG using Workers AI + Vectorize. For the model that vectorizes the passed text, I will use the following:
BAAI general embedding model that converts any text into a 768-dimensional vector.
Note: BAAI General Embedding (BGE) is a group of general-purpose text embedding models released by the Beijing Academy of Artificial Intelligence (BAAI).
Since it is a 768-dimensional vector, I will recreate the Vectorize index.
# Delete the previous index if necessary
$ npx wrangler vectorize list
┌────────────────┬────────────┬───────────┬─────────────┬────────────────────────────┬────────────────────────────┐
│ name │ dimensions │ metric │ description │ created │ modified │
├────────────────┼────────────┼───────────┼─────────────┼────────────────────────────┼────────────────────────────┤
│ tutorial-index │ 32 │ euclidean │ │ .......................... │ .......................... │
└────────────────┴────────────┴───────────┴─────────────┴────────────────────────────┴────────────────────────────┘
$ npx wrangler vectorize delete tutorial-index
# Create a 768-dimension index with cosine metric
$ npx wrangler vectorize create embeddings-index --dimensions=768 --metric=cosine
I'll update wrangler.jsonc.
{
"vectorize": [
{
"binding": "VECTORIZE",
"index_name": "embeddings-index"
}
]
}
Change src/index.ts to the following.
interface EmbeddingResponse {
shape: number[];
data: number[][];
}
export default {
async fetch(request, env) {
const url = new URL(request.url);
const path = url.pathname;
const userQuery = url.searchParams.get('q') ?? '';
if (path.startsWith('/insert')) {
const stories = [
'Orange cloud drifts above the silent sea',
'A llama hums softly at snowy dawn',
'Mars robot nurtures tomatoes beneath pink sky',
];
const modelResp: EmbeddingResponse = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
text: stories,
});
const vectors: VectorizeVector[] = [];
let id = 1;
modelResp.data.forEach((vector) => {
vectors.push({ id: `${id}`, values: vector });
id++;
});
let inserted = await env.VECTORIZE.upsert(vectors);
return Response.json(inserted);
}
if (path.startsWith('/query')) {
const queryVector: EmbeddingResponse = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
text: [userQuery],
});
const matches = await env.VECTORIZE.query(queryVector.data[0], {
topK: 1, // Number of results to return for similarity search
});
return Response.json({ matches });
}
return new Response('nothing to do... yet', { status: 404 });
},
} satisfies ExportedHandler<Env>;
Normally, you would register data pulled from an SQL database etc. into the Vectorize index, but this time I'm registering the following text provided by an LLM in order starting from id=1.
| id | Text |
|---|---|
| 1 | Orange cloud drifts above the silent sea |
| 2 | A llama hums softly at snowy dawn |
| 3 | Mars robot nurtures tomatoes beneath pink sky |
Let's try it right away.
$ npx wrangler dev --remote
# In a separate terminal
$ curl http://localhost:8787/insert
{
"mutationId":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
# Query with the phrase "robot vegetables"
$ curl http://localhost:8787/query?q=robot+vegetables
{
"matches":{
"count":1,
"matches":[
{
"id":"3",
"score":0.8041519
}
]
}
}
A score closer to 1 means a better match, so 0.8.. indicates it was queried successfully.
Let's try with other words.
# Query with just "winter"
$ curl http://localhost:8787/query?q=winter
{
"matches":{
"count":1,
"matches":[
{
"id":"2",
"score":0.6488873
}
]
}
}
# Query with "winter animal"
$ curl http://localhost:8787/query?q=winter+animal
{
"matches":{
"count":1,
"matches":[
{
"id":"2",
"score":0.7506682
}
]
}
}
The scores are as expected.
It was great to get a sense of how things work by easily trying out Workers AI + Vectorize! Next time, I hope to try other models, test with Japanese, or dive even deeper.
Bad Know-how
The following error occurs when running Workers AI
✘ [ERROR] Could not resolve "base64-js"
The solution is simply to add base64-js.
npm i base64-js
Reference URLs
Discussion