Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Workers AI in local mode #4522

Merged
merged 5 commits into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mean-jars-count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": minor
---

Add support for Workers AI in local mode
1 change: 1 addition & 0 deletions fixtures/ai-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
21 changes: 21 additions & 0 deletions fixtures/ai-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "ai-app",
"version": "1.0.1",
"private": true,
"description": "",
"license": "ISC",
"author": "",
"main": "src/index.js",
"scripts": {
"check:type": "tsc",
"test": "vitest run",
"test:watch": "vitest",
"type:tests": "tsc -p ./tests/tsconfig.json"
},
"devDependencies": {
"undici": "^5.23.0",
"wrangler": "workspace:*",
"@cloudflare/workers-tsconfig": "workspace:^",
"@cloudflare/ai": "^1.0.35"
}
}
12 changes: 12 additions & 0 deletions fixtures/ai-app/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
console.log("startup log");

export default {
async fetch(request, env) {
console.log("request log");

return Response.json({
binding: env.AI,
fetcher: env.AI.fetch.toString(),
});
},
};
31 changes: 31 additions & 0 deletions fixtures/ai-app/tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { resolve } from "path";
import { fetch } from "undici";
import { describe, it, beforeAll, afterAll } from "vitest";
import { runWranglerDev } from "../../shared/src/run-wrangler-long-lived";

describe("'wrangler dev' correctly renders pages", () => {
let ip: string,
port: number,
stop: (() => Promise<unknown>) | undefined,
getOutput: () => string;

beforeAll(async () => {
({ ip, port, stop, getOutput } = await runWranglerDev(
resolve(__dirname, ".."),
["--local", "--port=0", "--inspector-port=0"]
));
});

afterAll(async () => {
await stop?.();
});

it("ai binding is defined ", async ({ expect }) => {
const response = await fetch(`http://${ip}:${port}/`);
const content = await response.json();
expect(content).toEqual({
binding: {},
fetcher: "function fetch() { [native code] }",
});
});
});
7 changes: 7 additions & 0 deletions fixtures/ai-app/tests/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "@cloudflare/workers-tsconfig/tsconfig.json",
"compilerOptions": {
"types": ["node"]
},
"include": ["**/*.ts", "../../../node-types.d.ts"]
}
13 changes: 13 additions & 0 deletions fixtures/ai-app/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2020",
"esModuleInterop": true,
"module": "CommonJS",
"lib": ["ES2020"],
"types": ["node"],
"skipLibCheck": true,
"moduleResolution": "node",
"noEmit": true
},
"include": ["tests", "../../node-types.d.ts"]
}
10 changes: 10 additions & 0 deletions fixtures/ai-app/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineConfig } from "vitest/config";

export default defineConfig({
test: {
testTimeout: 10_000,
hookTimeout: 10_000,
teardownTimeout: 10_000,
useAtomics: true,
},
});
7 changes: 7 additions & 0 deletions fixtures/ai-app/wrangler.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
name = "ai-app"
compatibility_date = "2023-11-21"

main = "src/index.js"

[ai]
binding = "AI"
1 change: 1 addition & 0 deletions packages/wrangler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
"xxhash-wasm": "^1.0.1"
},
"devDependencies": {
"@cloudflare/ai": "^1.0.35",
"@cloudflare/cli": "workspace:*",
"@cloudflare/eslint-config-worker": "*",
"@cloudflare/pages-shared": "workspace:^",
Expand Down
20 changes: 20 additions & 0 deletions packages/wrangler/src/ai/fetcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Response } from "miniflare";
import { performApiFetch } from "../cfetch/internal";
import { getAccountId } from "../user";
import type { Request } from "miniflare";

export async function AIFetcher(request: Request) {
const accountId = await getAccountId();

Check warning on line 7 in packages/wrangler/src/ai/fetcher.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/ai/fetcher.ts#L6-L7

Added lines #L6 - L7 were not covered by tests

request.headers.delete("Host");
request.headers.delete("Content-Length");

Check warning on line 10 in packages/wrangler/src/ai/fetcher.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/ai/fetcher.ts#L9-L10

Added lines #L9 - L10 were not covered by tests

const res = await performApiFetch(`/accounts/${accountId}/ai/run/proxy`, {

Check warning on line 12 in packages/wrangler/src/ai/fetcher.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/ai/fetcher.ts#L12

Added line #L12 was not covered by tests
method: "POST",
headers: Object.fromEntries(request.headers.entries()),
body: request.body,
duplex: "half",
});

return new Response(res.body, { status: res.status });

Check warning on line 19 in packages/wrangler/src/ai/fetcher.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/ai/fetcher.ts#L19

Added line #L19 was not covered by tests
}
13 changes: 6 additions & 7 deletions packages/wrangler/src/dev/miniflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { realpathSync } from "node:fs";
import path from "node:path";
import { Log, LogLevel, TypedEventTarget, Mutex, Miniflare } from "miniflare";
import { AIFetcher } from "../ai/fetcher";
import { ModuleTypeToRuleType } from "../deployment-bundle/module-collection";
import { withSourceURLs } from "../deployment-bundle/source-url";
import { getHttpsOptions } from "../https-options";
Expand Down Expand Up @@ -312,6 +313,10 @@
.join("\n"),
};

if (bindings.ai?.binding) {
config.serviceBindings[bindings.ai.binding] = AIFetcher;

Check warning on line 317 in packages/wrangler/src/dev/miniflare.ts

View check run for this annotation

Codecov / codecov/patch

packages/wrangler/src/dev/miniflare.ts#L317

Added line #L317 was not covered by tests
}

const bindingOptions = {
bindings: bindings.vars,
textBlobBindings,
Expand Down Expand Up @@ -502,13 +507,7 @@
logger.warn("Miniflare 3 does not support CRON triggers yet, ignoring...");
}

if (config.bindings.ai) {
logger.warn(
"Workers AI is not currently supported in local mode. Please use --remote to work with it."
);
}

if (!config.bindings.ai && config.bindings.vectorize?.length) {
if (config.bindings.vectorize?.length) {
// TODO: add local support for Vectorize bindings (https://github.com/cloudflare/workers-sdk/issues/4360)
logger.warn(
"Vectorize bindings are not currently supported in local mode. Please use --remote if you are working with them."
Expand Down
22 changes: 22 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.