CloudflareHono / SonikJavaScript未分類

HonoでCloudflare Pagesを作りつつ、wrangler.tomlを使ってVectorizeをよびだしてみた

2024年春のDeveloepr WeekでCloudflare Pagesがwrangler.tomlをサポート開始。Cloudflare Pagesプロジェクト作成からVectorizeの追加、Workers AIの有効化まで手順を解説。Vectorizeのデプロイ成功後、API追加し動作を確認。wrangler.tomlを更新しLangChain.js使用を試みるも、エラー発生。Node.js互換フラグの設定やcryptoモジュールの取り扱いについて解説。Cloudflare Pagesを使用したVectorizeの有効活用が可能となる手順を詳細に記載している。

広告ここから
広告ここまで

2024年春のDeveloepr WeekでCloudflare Pagesがwrangler.tomlをサポートしたとアナウンスがありました。せっかくなので、HonoでCloudflare Pagesプロジェクトを作ってみつつ、ついでに1つ気になっていた部分に挑戦してみました。

create-honoでプロジェクトをセットアップする

Honoでアプリを作る際にお馴染みのcreate-honoコマンドを利用します。

% npm create hono@latest pages-demo

今回はバージョン0.6.3を前提として紹介します。

  create-hono@0.6.3
Ok to proceed? (y) y

テンプレートはcloudflare-pagesを選びましょう。

? Which template do you want to use?
  aws-lambda
  bun
❯ cloudflare-pages
  cloudflare-workers
  deno
  fastly
  lambda-edge
(Use arrow keys to reveal more choices)

あとはライブラリのインストールを、お好きなツールで実行しましょう。

✔ Cloning the template
? Do you want to install project dependencies? (Y/n) y
? Which package manager do you want to use? (Use arrow keys)
❯ npm
  bun
  pnpm
  yarn

作成が完了しました。

🎉 Copied project files
Get started with: cd pages-demo

Wrangler.tomlはすでに生成されている

アナウンスされてまだ1週間経っていませんが、すでにwrangler.tomlが用意されていました。

name = "pages-demo"
pages_build_output_dir = "./dist"

# [vars]
# MY_VAR = "my-variable"

# [[kv_namespaces]]
# binding = "MY_KV_NAMESPACE"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# [[r2_buckets]]
# binding = "MY_BUCKET"
# bucket_name = "my-bucket"

# [[d1_databases]]
# binding = "DB"
# database_name = "my-database"
# database_id = ""

# [ai]
# binding = "AI"

あとは必要に応じてコメントアウトしたり、行ごと削除すればよさそうですね。

せっかくなので、あえてVectorizeを追加してみる

せっかくなので、用意されている設定ファイルに含まれていない、Cloudflare Vectorizeを追加してみましょう。インデックスの作成はWranglerで行います。

npx wrangler vectorize create rag-demo --dimensions=768 --metric=cosine

✅ Successfully created a new Vectorize index: 'rag-demo'
📋 To start querying from a Worker, add the following binding
 configuration into 'wrangler.toml':

[[vectorize]]
binding = "VECTORIZE_INDEX" # available within your Worker on env.VECTORIZE_INDEX
index_name = "rag-demo"

wrangler.tomlを更新するように言われますので、試してみましょう。一緒にWorkers AIも有効化しておきます。

name = "pages-demo"
pages_build_output_dir = "./dist"

[ai]
binding = "AI"

[[vectorize]]
binding = "VECTORIZE_INDEX" # available within your Worker on
 env.VECTORIZE_INDEX
index_name = "rag-demo"

Wranglerを使ってデプロイまで試みてみましょう。

 % npm run deploy

ビルドに成功すると、Pagesプロジェクトを新規作成するか聞かれます。

> build
> vite build

vite v5.2.8 building SSR bundle for production...
✓ 43 modules transformed.
dist/_worker.js  28.15 kB
✓ built in 332ms
The project you specified does not exist: "pages-demo".
Would you like to create it?"
❯ Create a new project

ブランチを選択後、デプロイに成功しました。

✔ Enter the production branch name: … production
✨ Successfully created the 'pages-demo' project.
🌍  Uploading... (1/1)

✨ Success! Uploaded 1 files (1.29 sec)

✨ Compiled Worker successfully
✨ Uploading Worker bundle
✨ Deployment complete! Take a peek over at https://xxxx.pages-demo.pages.dev

Vectorizeが動作するかを試してみる

デプロイが成功したので、本当にPagesからVectorizeが利用できるか試してみましょう。src/index.tsxに次のAPIを追加しました。

const app = new Hono<{
  Bindings: {
    VECTORIZE_INDEX: VectorizeIndex;
  }
}>()

// 中略

app.get('/search', async c => {
  try {
    const postVector = await c.env.VECTORIZE_INDEX.getByIds(["123"])
    console.log(postVector)
    return c.text('hello')
  } catch (e) {
    return c.json(e)
  }
})

データをなにも投入していないので、console.logは空になるはずです。しかしそもそもVectorizeが利用できない場合は、c.env.VECTORIZE_INDEX.getByIdがエラーになると予測しています。

この状態でプロジェクトをデプロイしてみましょう。

% npm run deploy

> deploy
> $npm_execpath run build && wrangler pages deploy dist


> build
> vite build

vite v5.2.8 building SSR bundle for production...
✓ 43 modules transformed.
dist/_worker.js  28.30 kB
✓ built in 381ms
🌍  Uploading... (1/1)

✨ Success! Uploaded 0 files (1 already uploaded) (0.37 sec)

✨ Compiled Worker successfully
✨ Uploading Worker bundle

その後ログを確認すると、エラーは発生していませんでした。ログにはただ「c.env.VECTORIZE_INDEX.getByIdの結果がなにもないこと」だけを示しています。

Cloudflare PagesでもVectorizeが使える・・・っぽい

ダッシュボードのバインディング画面には出てこないのですが、このようにwrangler.tomlを使うことでVectorizeが利用できるみたいです。

追記:

LangChain.jsを使いたいと思って、wrangler.tomlを次のように更新しました。

name = "pages-demo"
pages_build_output_dir = "./dist"
compatibility_date = "2023-12-01"

node_compat = true

するとnode_compatは使えないよというエラーが出ました。


✘ [ERROR] Running configuration file validation for Pages:

    - Configuration file for Pages projects does not support "node_compat"

compatibility_flags = [ "nodejs_compat" ]を使った場合、cryptoのエラーが発生します。


✘ [ERROR] Could not resolve "crypto"

    assets/few_shot-DFLCx_Dl.js:1:61:
      1 │ ...u}from"../_worker.js";import"crypto";class l extends p{construct...
        ╵                                ~~~~~~~~

  The package "crypto" wasn't found on the file system but is built into node.
  Add the "nodejs_compat" compatibility flag to your Pages project and make sure to prefix the module name with "node:" to enable Node.js compatibility.


✘ [ERROR] Build failed with 2 errors:

  _worker.js:1:525: ERROR: Could not resolve "crypto"
  assets/few_shot-DFLCx_Dl.js:1:61: ERROR: Could not resolve "crypto"

ライブラリの内部で使われているのでnode:cryptoにする解決策は使えなさそうなのが悩ましいですね・・・

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts