Skip to content

Instantly share code, notes, and snippets.

@eblaauw
Created November 1, 2025 11:40
Show Gist options
  • Select an option

  • Save eblaauw/c6d4da38f2bf91f6bcecbc3064d89044 to your computer and use it in GitHub Desktop.

Select an option

Save eblaauw/c6d4da38f2bf91f6bcecbc3064d89044 to your computer and use it in GitHub Desktop.
Cat Breed finder
export interface Env {
AI: Ai;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const res = await fetch('https://cataas.com/cat');
const blob = await res.arrayBuffer();
// Convert array buffer to base64 data URL (in chunks to avoid stack overflow)
const uint8Array = new Uint8Array(blob);
let binaryString = '';
const chunkSize = 8192;
for (let i = 0; i < uint8Array.length; i += chunkSize) {
const chunk = uint8Array.slice(i, i + chunkSize);
binaryString += String.fromCharCode(...chunk);
}
const base64 = btoa(binaryString);
const dataUrl = `data:image/jpeg;base64,${base64}`;
const messages = [
{
role: 'system',
content: 'You are a cat breed expert assistant. You must respond with valid JSON only, matching the provided schema exactly.',
},
{
role: 'user',
content: [
{
type: 'text',
text: 'Analyze this image and identify the cat breed. Respond with a JSON object containing: breed (string), confidence (one of: high, medium, low).',
},
{ type: 'image_url', image_url: { url: dataUrl } },
],
},
];
const response = await env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {
messages,
max_tokens: 512,
response_format: {
type: 'json_schema',
json_schema: {
name: 'cat_breed_analysis',
strict: true,
schema: {
type: 'object',
properties: {
breed: {
type: 'string',
description: 'The cat breed identified in the image',
},
confidence: {
type: 'string',
enum: ['high', 'medium', 'low'],
description: 'Confidence level of the breed identification',
},
},
required: ['breed', 'confidence'],
additionalProperties: false,
},
},
},
});
return Response.json(response);
},
} satisfies ExportedHandler<Env>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment