Cloudflare Docs
Workers AI
Visit Workers AI on GitHub
Set theme to dark (⇧+D)

Sentiment Analysis

DistilBERT-SST-2 is a distilled BERT model that was finetuned on SST-2 for sentiment classification.

​​ Examples


import { Ai } from '@cloudflare/ai'
export interface Env {
AI: any;
}
export default {
async fetch(request: Request, env: Env) {
const ai = new Ai(env.AI);
const = await ai.run('@cf/huggingface/distilbert-sst-2-int8', {
text: "This pizza is great!"
}
);
return new Response(JSON.stringify(answer));
},
};

async function run(model, input) {
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/${model}`,
{
headers: { Authorization: "Bearer {API_TOKEN}" },
method: "POST",
body: JSON.stringify(input),
}
);
const result = await response.json();
return result;
}
run('@cf/huggingface/distilbert-sst-2-int8', { text: 'This pizza is great!' }).then((response) => {
console.log(JSON.stringify(response));
});

import requests
API_BASE_URL = "https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/"
headers = {"Authorization": "Bearer {API_TOKEN}"}
def run(model, input)
response = requests.post(f"{API_BASE_URL}{model}", headers=headers, json=input)
return response.json()
output = run("@cf/huggingface/distilbert-sst-2-int88", { text: "This pizza is great!" })

$ curl https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/@cf/meta/llama-2-7b-chat-int8 \
-X POST \
-H "Authorization: Bearer {API_TOKEN}" \
-d '{ "text": "This pizza is great!" }'

Example Workers AI response


{
"result": {
"items": [
{
"label": "POSITIVE",
"score": 0.9998738765716553
},
{
"label": "NEGATIVE",
"score": 0.00012611268903128803
}
],
}
"success": true,
"errors":[],
"messages":[]
}

​​ API schema

The following schema is based on JSON Schema


{
"task": "text-classification",
"tsClass": "AiTextClassification",
"jsonSchema": {
"input": {
"type": "object",
"properties": {
"text": {
"type": "string"
}
},
"required": ["text"]
},
"output": {
"type": "array",
"items": {
"type": "object",
"properties": {
"score": {
"type": "number"
},
"label": {
"type": "string"
}
}
}
}
}
}