|
| 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 worker = ` |
| 15 | +export interface Env { |
| 16 | + AI: Ai; |
| 17 | +} |
| 18 | +
|
| 19 | +export default { |
| 20 | + async fetch(request, env): Promise<Response> { |
| 21 | + const query = 'Which one is cooler?' |
| 22 | + const contexts = [ |
| 23 | + { |
| 24 | + text: 'a cyberpunk lizzard' |
| 25 | + }, |
| 26 | + { |
| 27 | + text: 'a cyberpunk cat' |
| 28 | + } |
| 29 | + ]; |
| 30 | +
|
| 31 | + const response = await env.AI.run('${name}', { query, contexts }); |
| 32 | +
|
| 33 | + return Response.json(response); |
| 34 | + }, |
| 35 | +} satisfies ExportedHandler<Env>; |
| 36 | +
|
| 37 | +`; |
| 38 | +
|
| 39 | +const python = ` |
| 40 | +import os |
| 41 | +import requests |
| 42 | +
|
| 43 | +ACCOUNT_ID = "your-account-id" |
| 44 | +AUTH_TOKEN = os.environ.get("CLOUDFLARE_AUTH_TOKEN") |
| 45 | +
|
| 46 | +response = requests.post( |
| 47 | + f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/${name}", |
| 48 | + headers={"Authorization": f"Bearer {AUTH_TOKEN}"}, |
| 49 | + json={ |
| 50 | + "query": "Which one is better?" |
| 51 | + "context": [ |
| 52 | + {"text": "a cyberpunk lizzard"}, |
| 53 | + {"text": "a cyberpunk car"}, |
| 54 | + ] |
| 55 | + } |
| 56 | +) |
| 57 | +result = response.json() |
| 58 | +print(result) |
| 59 | +`; |
| 60 | +
|
| 61 | +const curl = ` |
| 62 | +curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/${name} \\ |
| 63 | + -X POST \\ |
| 64 | + -H "Authorization: Bearer $CLOUDFLARE_AUTH_TOKEN" \\ |
| 65 | + -d '{ "query": "Which one is better?", "contexts": [{ "text": "a cyberpunk lizzard" }, {"text": "a cyberpunk cat"}]}' |
| 66 | +`; |
| 67 | +--- |
| 68 | + |
| 69 | +<Details header="Worker"> |
| 70 | + <Code code={worker} lang="ts" /> |
| 71 | +</Details> |
| 72 | + |
| 73 | +<Details header="Python"> |
| 74 | + <Code code={python} lang="py" /> |
| 75 | +</Details> |
| 76 | + |
| 77 | +<Details header="curl"> |
| 78 | + <Code code={curl} lang="sh" /> |
| 79 | +</Details> |
0 commit comments