打开 wrangler.toml 文件,修改 name 和 compatibility_date 为你的应用名称和兼容日期。
这里我们我们需要注意的配置就是 vars 里面的 TOKEN,在 Dify 添加 API 扩展的时候,我们需要填写这个 Token。出于安全考虑,我们建议你使用一个随机的字符串作为 Token,你不应该在源代码中直接写入 Token,而是使用环境变量的方式来传递 Token。所以请不要把 wrangler.toml 提交到你的代码仓库中。
name = "dify-extension-example"
compatibility_date = "2023-01-01"
[vars]
TOKEN = "bananaiscool"
这个 API 扩展会返回一个随机的 Breaking Bad 名言。你可以在 src/index.ts 中修改这个 API 扩展的逻辑。这个例子展示了与第三方 API 进行交互的方式。
// ⬇️ implement your logic here ⬇️
// point === "app.external_data_tool.query"
// https://api.breakingbadquotes.xyz/v1/quotes
const count = params?.inputs?.count ?? 1;
const url = `https://api.breakingbadquotes.xyz/v1/quotes/${count}`;
const result = await fetch(url).then(res => res.text())
// ⬆️ implement your logic here ⬆️
这个仓库简化了除了业务逻辑之外所有的配置,你可以直接使用 npm 命令来部署你的 API 扩展。
npm install
npm run deploy
部署成功之后,你会得到一个公网地址,你可以在 Dify 中添加这个地址作为 API Endpoint。请注意不要遗漏 endpoint 这个路径,此路径的具体定义在 src/index.ts 中可以查看。
另外,也可以直接使用 npm run dev 命令来部署到本地进行测试。
npm install
npm run dev
相关输出:
$ npm run dev
> dev
> wrangler dev src/index.ts
⛅️ wrangler 3.99.0
-------------------
Your worker has access to the following bindings:
- Vars:
- TOKEN: "ban****ool"
⎔ Starting local server...
[wrangler:inf] Ready on http://localhost:58445