跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

AI Search 概览

最后更新 查看 MarkdownAgent 设置

Agent 可使用 AI Search 从索引内容中检索相关信息,并用于增强对 AI 模型的调用。AI Search 为你管理检索管道,包括索引、搜索以及可选的内容 chat completion。

在以下场景使用 AI Search:

  • 搜索产品文档、支持内容、用户文件或内部知识库。
  • 在调用模型前检索相关 chunk。
  • 使用托管索引而非自行构建检索基础设施。
  • 从 R2 bucket、网站或上传文件查询内容。

基本模式

将 AI Search 绑定到 Worker,然后在 Agent 方法中查询实例。

import { Agent, callable } from "agents";

export class SearchAgent extends Agent {
	@callable()
	async searchKnowledge(query) {
		const instance = this.env.AI_SEARCH.get("my-instance");

		const results = await instance.search({
			messages: [{ role: "user", content: query }],
		});

		return results;
	}
}
import { Agent, callable } from "agents";

type Env = {
    AI_SEARCH: AiSearchNamespace;
};

export class SearchAgent extends Agent<Env> {
    @callable()
    async searchKnowledge(query: string) {
        const instance = this.env.AI_SEARCH.get("my-instance");

        const results = await instance.search({
            messages: [{ role: "user", content: query }],
        });

        return results;
    }
}

对于答案生成,使用 chatCompletions() 在一次调用中检索相关内容并生成响应。

const instance = this.env.AI_SEARCH.get("my-instance");

const response = await instance.chatCompletions({
	messages: [{ role: "user", content: "How do I deploy an Agent?" }],
	model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
	ai_search_options: {
		retrieval: {
			max_num_results: 5,
		},
	},
});
const instance = this.env.AI_SEARCH.get("my-instance");

const response = await instance.chatCompletions({
    messages: [{ role: "user", content: "How do I deploy an Agent?" }],
    model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
    ai_search_options: {
        retrieval: {
            max_num_results: 5,
        },
    },
});

配置

当 Agent 需要按名称访问 AI Search 实例时,使用 ai_search_namespaces binding。

{
    "ai_search_namespaces": [
        {
            "binding": "AI_SEARCH",
            "namespace": "default",
            "remote": true
        }
    ]
}
[[ai_search_namespaces]]
binding = "AI_SEARCH"
namespace = "default"
remote = true

使用 remote: true 在 wrangler dev 本地开发期间查询已部署的 AI Search 实例。

相关资源

AI Search

在网站、R2 bucket 和上传文件上创建托管检索管道。

这篇文档对您有帮助吗?