用 Tavily 做真实网页搜索
tavily-web-search 是一个 Hybrid Gene,通过 Tavily API 搜索网页。它的输入和输出与 genesis-web-search 完全相同。区别在于 genesis-web-search 是演示用的,返回编造的 example.com 结果;这个 Gene 返回的是真实结果。
需要准备什么
Section titled “需要准备什么”- 一个 Tavily API Key。 到 tavily.com 注册。免费档每月 1,000 次搜索,不用绑卡。
- 一个 Rotifer 项目。 下面的命令要在项目里运行,用
rotifer init可以新建一个。
rotifer install tavily-web-search这会从 Rotifer Cloud 把编译好的 Gene 下载到 genes/tavily-web-search/,保存前会核对模块的 SHA-256。不需要自己编译。
设置 Key
Section titled “设置 Key”用下面的命令输入 Key,输入时屏幕上不显示,也不会进 shell 历史:
read -rs TAVILY_API_KEY && export TAVILY_API_KEY粘贴 Key 后按回车。在这个终端窗口关闭前一直有效。
rotifer run tavily-web-search --input '{"query":"WebAssembly component model","maxResults":3}'{ "results": [ { "title": "…", "url": "https://…", "snippet": "…" } ], "totalResults": 3, "searchTime": 840}maxResults 取 1–20(默认 5)。searchTime 是 Tavily 报告的响应时间,单位毫秒。
Key 去了哪里
Section titled “Key 去了哪里”Gene 的 phenotype.json 按名字声明它要用的 Key:
"externalDependencies": [ { "apiType": "rest", "semanticTag": "tavily-search", "domains": ["api.tavily.com"], "credentials": ["TAVILY_API_KEY"], "degradationBehavior": "FAIL" }]- CLI 从你的环境里读取
TAVILY_API_KEY,因为 Gene 声明了这个名字。别的变量一概不读,也没有存 Key 的文件。 - Gene 看不到 Key。它发出的请求里写的是
Authorization: Bearer ${env:TAVILY_API_KEY}这串文字,请求离开沙箱时由 CLI 填入真实的 Key。 - 请求只能发往
api.tavily.com。发往其他主机的请求在发出之前就会被拒绝。 - Key 不会被打印,也不会写进输出、日志或审计日志。
| 你看到的 | 意思 |
|---|---|
missing credential: the environment variable TAVILY_API_KEY is not set | 当前终端没有设置 Key,按上面的方法设置。Gene 没有运行。 |
每次运行都是 gene returned error code: -2,设不设 Key 都一样 | 你的 CLI 低于 0.31.0,按页首的提示升级。 |
gene returned error code: -201 | Tavily 拒绝了这个 Key,到 Tavily 控制台核对一下。 |
gene returned error code: -202 | 触发了 Tavily 的频率限制,或你的套餐本月额度已用完。 |
gene returned error code: -203 | Tavily 返回了其他错误。 |
gene returned error code: -204 | Tavily 有回应,但内容 Gene 读不懂。 |
gene returned error code: -4 或 -5 | 请求超时,或网络故障。 |
INVALID_INPUT: … | query 缺失或为空,或 maxResults 不在 1–20 之间,例如 INVALID_INPUT: maxResults must be an integer from 1 to 20。没有发起搜索。 |
从源码构建(可选)
Section titled “从源码构建(可选)”这个 Gene 的 Rust 源码在 rotifer-playground 仓库。想自己编译而不是安装的话,把 genes/tavily-web-search 复制到你项目的 genes/ 目录下,然后在项目根目录运行:
rustup target add wasm32-unknown-unknowncargo build --release --target wasm32-unknown-unknown --manifest-path genes/tavily-web-search/Cargo.tomlrotifer compile tavily-web-search --wasm genes/tavily-web-search/target/wasm32-unknown-unknown/release/tavily_web_search.wasmcompile 会保持这个 Gene 为 Hybrid,并生成 genes/tavily-web-search/gene.ir.wasm,之后按上面的方法设置 Key、搜索即可。这条路同样需要 0.31.0 或更高:在 0.30.x 上,compile 会提示 Hybrid gene — runs under Node.js with the network gateway; no WASM artifact is produced,不会生成 gene.ir.wasm。
任何 Hybrid Gene 里 API Key 是怎么处理的,见 Hybrid Gene 开发指南。