|
| 1 | +--- |
| 2 | +import { z } from "astro:schema"; |
| 3 | +import { Code } from "@astrojs/starlight/components"; |
| 4 | +import Details from "~/components/Details.astro"; |
| 5 | +
|
| 6 | +type Props = z.infer<typeof props>; |
| 7 | +
|
| 8 | +const props = z.object({ |
| 9 | + name: z.string(), |
| 10 | +}); |
| 11 | +
|
| 12 | +const { name } = props.parse(Astro.props); |
| 13 | +
|
| 14 | +const workerReturningDataURI = ` |
| 15 | +export interface Env { |
| 16 | + AI: Ai; |
| 17 | +} |
| 18 | +
|
| 19 | +export default { |
| 20 | + async fetch(request, env): Promise<Response> { |
| 21 | + const response = await env.AI.run('@cf/black-forest-labs/flux-1-schnell', { |
| 22 | + prompt: 'a cyberpunk lizard', |
| 23 | + }); |
| 24 | + // response.image is base64 encoded which can be used directly as an <img src=""> data URI |
| 25 | + const dataURI = \`data:image/jpeg;charset=utf-8;base64,\${response.image}\`; |
| 26 | + return Response.json({ dataURI }); |
| 27 | + }, |
| 28 | +} satisfies ExportedHandler<Env>; |
| 29 | +
|
| 30 | +`; |
| 31 | +
|
| 32 | +const workerReturningImage = ` |
| 33 | +export interface Env { |
| 34 | + AI: Ai; |
| 35 | +} |
| 36 | +
|
| 37 | +export default { |
| 38 | + async fetch(request, env): Promise<Response> { |
| 39 | + const response = await env.AI.run('@cf/black-forest-labs/flux-1-schnell', { |
| 40 | + prompt: 'a cyberpunk lizard', |
| 41 | + }); |
| 42 | + // Convert from base64 string |
| 43 | + const binaryString = atob(response.image); |
| 44 | + // Create byte representation |
| 45 | + const img = Uint8Array.from(binaryString, (m) => m.codePointAt(0)); |
| 46 | + return new Response(img, { |
| 47 | + headers: { |
| 48 | + 'Content-Type': 'image/jpeg', |
| 49 | + }, |
| 50 | + }); |
| 51 | + }, |
| 52 | +} satisfies ExportedHandler<Env>; |
| 53 | +`; |
| 54 | +
|
| 55 | +const curl = ` |
| 56 | +curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ |
| 57 | + -X POST \\ |
| 58 | + -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \\ |
| 59 | + -d '{ "prompt": "cyberpunk cat" }' |
| 60 | +`; |
| 61 | +--- |
| 62 | + |
| 63 | +<Details header="Workers - Returning a data URI - TypeScript"> |
| 64 | + <Code code={workerReturningDataURI} lang="ts" /> |
| 65 | +</Details> |
| 66 | + |
| 67 | +<Details header="Workers - Returning an image - TypeScript"> |
| 68 | + <Code code={workerReturningImage} lang="ts" /> |
| 69 | +</Details> |
| 70 | + |
| 71 | +<Details header="curl"> |
| 72 | + <Code code={curl} lang="sh" /> |
| 73 | +</Details> |
0 commit comments