跳转到内容

通过搜索来寻找合适的代理(agent)

在 ADK 中得到支持。Python v0.1.0Java v0.1.0Kotlin v0.2.0

代理搜索(Agent Search) 这是一个非常强大的工具,属于 Agent Development Kit (ADK) 的组成部分;它允许 AI 代理从您的企业文档和数据仓库中获取信息。通过将您的 AI 代理与已索引的企业内容连接起来,您可以为用户提供基于您组织知识库的答案。

这一功能对于那些需要从内部文档、政策文件、研究论文或任何已被索引的专有内容中获取信息的企业特定查询来说尤其具有价值。 代理搜索(Agent Search) **datastore:** 当您的代理程序确定需要从知识库中获取信息时,它会自动搜索已索引的文档,并将搜索结果包含在响应中,同时会正确标注信息来源。

在创建一个“基于现实世界的智能代理”(grounded agent)之前,你必须已经拥有一个现有的“代理搜索数据存储”(Agent Search Data Store)。如果你还没有这样的数据存储,请按照相关说明进行操作。 开始使用自定义搜索功能吧! 要创建一个(某个东西),您需要使用您的……(此处应填写具体的工具、资源或信息)。 Data store ID (e.g., projects/YOUR_PROJECT_ID/locations/global/collections/default_collection/dataStores/YOUR_DATASTORE_ID)来配置代理程序。

身份验证设置

“Agent Search”功能要求您的 ADK 代理与 Google Cloud 项目进行身份验证(即需要连接并使用 Google Cloud 项目的认证机制)。在使用此工具时,不能使用来自 Google AI Studio 的 Gemini API 密钥。有关如何将您的 ADK 代理连接到 Google Cloud 项目的更多信息,请参阅相关文档。 连接到 Google Cloud guide.

  • 设置…… `gcloud CLI`
  • 通过终端运行以下命令,登录到 Google Cloud: gcloud auth login.
  • 对于 Python,请打开…… .env 请上传文件,并指定您的项目 ID 和项目所在的位置。
  • 对于 Java 和 Kotlin,请确保您的应用程序环境已配置 Google Cloud 的默认凭据。GOOGLE_APPLICATION_CREDENTIALS请在该环境中设置以下变量,而不是在另一个环境中设置它们。 .env file.
.env
GOOGLE_GENAI_USE_ENTERPRISE=TRUE
GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
GOOGLE_CLOUD_LOCATION=LOCATION

有关如何从 ADK 代理连接到 Google Cloud 的更多信息,请参阅…… 连接到 Google Cloud 和 Agent Platform。.

创建一个“接地气”(即实际可用、符合用户需求的)智能代理(agent)

要启用“通过搜索进行数据定位”(Grounding with Search)的功能,你需要在代理定义(agent definition)中加入相应的搜索工具,并提供必要的配置信息。 data_store_id.

from google.adk.agents import Agent
from google.adk.tools import VertexAiSearchTool

# Configuration
DATASTORE_ID = "projects/YOUR_PROJECT_ID/locations/global/collections/default_collection/dataStores/YOUR_DATASTORE_ID"

root_agent = Agent(
    name="vertex_search_agent",
    model="gemini-flash-latest",
    instruction="Answer questions using Agent Search to find information from internal documents. Always cite sources when available.",
    description="Enterprise document search assistant with Agent Search capabilities",
    tools=[VertexAiSearchTool(data_store_id=DATASTORE_ID)]
)
import com.google.adk.agents.LlmAgent;
import com.google.adk.tools.VertexAiSearchTool;

// Configuration
String DATASTORE_ID = "projects/YOUR_PROJECT_ID/locations/global/collections/default_collection/dataStores/YOUR_DATASTORE_ID";

LlmAgent rootAgent = LlmAgent.builder()
    .name("vertex_search_agent")
    .model("gemini-flash-latest")
    .instruction("Answer questions using Agent Search to find information from internal documents. Always cite sources when available.")
    .description("Enterprise document search assistant with Agent Search capabilities")
    .tools(VertexAiSearchTool.builder().dataStoreId(DATASTORE_ID).build())
    .build();
import com.google.adk.kt.agents.Instruction
import com.google.adk.kt.agents.LlmAgent
import com.google.adk.kt.models.Gemini
import com.google.adk.kt.tools.VertexAiSearchTool

// Configuration
val DATASTORE_ID =
    "projects/YOUR_PROJECT_ID/locations/global/collections/default_collection/dataStores/YOUR_DATASTORE_ID"

val rootAgent =
    LlmAgent(
        name = "vertex_search_agent",
        model = Gemini(name = "gemini-flash-latest"),
        instruction =
            Instruction(
                "Answer questions using Agent Search to find information from internal " +
                    "documents. Always cite sources when available.",
            ),
        description = "Enterprise document search assistant with Agent Search capabilities",
        tools = listOf(VertexAiSearchTool(dataStoreId = DATASTORE_ID)),
    )

“通过搜索进行基础训练”(Grounding with Search)的具体运作方式是怎样的?

“通过搜索进行信息整合”(Grounding with Search)是指将智能助手(agent)与组织内部已索引的文档和数据连接起来的过程,从而使该助手能够基于企业的私有信息生成准确的回复。当用户的查询需要从内部知识库中获取信息时,智能助手背后的大型语言模型(LLM)会智能地决定调用相应的功能或数据源来提供所需的答案。 VertexAiSearchTool 从您的索引文档中查找相关事实。

数据流图(Data Flow Diagram)

该图展示了用户查询如何逐步转化为具体、有意义的响应的整个过程。

通过搜索数据流来实现数据整合(即“Grounding with Search Data Flow”)

详细说明

该“接地代理”(grounding agent)利用图中描述的数据流来检索、处理企业信息,并将这些信息整合到最终呈现给用户的答案中。

  1. 用户查询(User Query)最终用户会向您的客服人员提出关于内部文档或企业数据的问题,从而与您的客服系统进行交互。
  2. ADK Orchestration代理开发工具包(Agent Development Kit)负责协调代理的行为,并将用户发送的消息传递给代理的核心处理模块。
  3. 大语言模型(LLM)的分析与工具调用代理的 large language model(LLM,例如 Gemini 模型)会分析用户提供的提示。如果该模型判断需要从用户索引的文档中获取相关信息,它就会通过调用相应的函数来触发“信息提取”(grounding)机制。 VertexAiSearchTool这非常适合用来回答有关公司政策、技术文档或专有研究的查询。
  4. Vertex AI Search Service 的交互方式: The VertexAiSearchTool 该服务会与您配置的代理搜索数据存储系统(Agent Search Datastore)进行交互,该系统存储了已索引的企业文档。该服务会根据您的私有内容生成并执行搜索查询。
  5. 文档检索与排序“Agent Search”会根据语义相似度以及相关性评分,从您的数据存储系统中检索并排序出最相关的文档片段。
  6. 上下文注入(Context Injection)搜索服务会在生成最终响应之前,将检索到的文档片段整合到模型的上下文中。这一步骤至关重要,因为它使模型能够对您组织中的实际数据进行分析和理解(即“进行推理”)。
  7. “Grounded Response Generation”(基于现实/具体情境的回应生成机制)现在,这个大型语言模型(LLM)已经获得了相关企业内容的信息,因此它能够生成一个包含从您的文档中提取到的信息的回复。
  8. 带有数据源的响应展示方式ADK 接收到了最终的回复,其中包含了必要的源文档引用信息。 groundingMetadata系统会从这些来源中获取信息,并注明信息来源后将其呈现给用户。这样一来,最终用户就可以将获取到的信息与你们企业的官方数据来源进行核对(即验证信息的真实性)。

通过搜索结果来理解“Grounding”(接地)的概念

当代理使用“Agent Search”来生成响应时,它会返回详细的信息,其中包括最终的文本答案以及用于生成该答案的文档的元数据。这些元数据对于验证响应内容以及明确信息来源(即您的企业提供的数据)至关重要。

一个“基于现实情况”的回应示例:

以下是一个示例:该示例展示了模型在对企业文档进行查询后返回的内容对象。

最终答案文本:

"Developing models for a medical scribe presents several significant challenges, primarily due to the complex nature of medical documentation, the sensitive data involved, and the demanding requirements of clinical workflows. Key challenges include: **Accuracy and Reliability:** Medical documentation requires extremely high levels of accuracy, as errors can lead to misdiagnoses, incorrect treatments, and legal repercussions. Ensuring that AI models can reliably capture nuanced medical language, distinguish between subjective and objective information, and accurately transcribe physician-patient interactions is a major hurdle. **Natural Language Understanding (NLU) and Speech Recognition:** Medical conversations are often rapid, involve highly specialized jargon, acronyms, and abbreviations, and can be spoken by individuals with diverse accents or speech patterns... [response continues with detailed analysis of privacy, integration, and technical challenges]"

元数据接地(Metadata Grounding)示例代码片段:

{
  "groundingMetadata": {
    "groundingChunks": [
      {
        "retrievedContext": {
          "title": "AI in Medical Scribing: Technical Challenges",
          "uri": "https://storage.googleapis.com/your-bucket/doc-medical-scribe-ai-tech-challenges.pdf",
          "documentName": "projects/your-project/locations/global/collections/default_collection/dataStores/your-datastore-id/branches/0/documents/doc-medical-scribe-ai-tech-challenges",
          "text": "Medical documentation requires extremely high levels of accuracy, as errors can lead to misdiagnoses..."
        }
      },
      {
        "retrievedContext": {
          "title": "Regulatory and Ethical Hurdles for AI in Healthcare",
          "uri": "https://storage.googleapis.com/your-bucket/doc-ai-healthcare-ethics.pdf",
          "documentName": "projects/your-project/locations/global/collections/default_collection/dataStores/your-datastore-id/branches/0/documents/doc-ai-healthcare-ethics",
          "text": "HIPAA compliance imposes strict requirements on how patient data may be stored and processed..."
        }
      }
    ],
    "groundingSupports": [
      {
        "groundingChunkIndices": [0, 1],
        "segment": {
          "endIndex": 637,
          "startIndex": 433,
          "text": "Ensuring that AI models can reliably capture nuanced medical language..."
        }
      }
    ],
    "retrievalQueries": [
      "challenges in natural language processing medical domain",
      "AI medical scribe challenges",
      "difficulties in developing AI for medical scribes"
    ]
  }
}

如何解读响应结果

元数据为模型生成的文本与企业提供的相关文档之间建立了联系。以下是具体的操作步骤:

  • groundingChunks这是一个包含该模型所参考的企业文档的列表。从您的数据存储系统中检索到的每个文档片段都包含相关信息。 retrievedContext 用于存储文档的对象 title,它的 uri,the documentName (文档中完整的代理搜索资源名称),以及 text 那就是被检索到的内容。
  • **groundingSupports**:该列表将最终答案中的具体句子与相应的信息源(或上下文)重新连接起来。 groundingChunks.
  • segment:该对象用于标识最终文本答案中的特定部分,其具体位置由该对象自身定义。 startIndex, endIndex,以及 text itself.
  • groundingChunkIndices这个数组包含了与列表中列出的来源相对应的索引编号。 groundingChunks例如,关于“HIPAA合规性”的内容是依据相关资料进行说明的。 groundingChunks 位于索引位置 1(即 “监管与伦理障碍” 这份文档)。
  • retrievalQueries该数组显示了针对您的数据存储库执行的具体搜索查询,这些查询用于查找相关信息。

与 Google Search 的实现方式不同,Grounding with Search 并不需要特定的显示组件。不过,通过展示引用文献和文档来源,可以增强用户的信任感,并让用户能够根据您组织的权威资料来验证信息的一致性。

可选的引用显示功能

由于元数据已经被提供出来,您可以根据自己的应用程序需求来选择如何实现引用显示功能(即如何将元数据用于展示引用信息)。

简单文本显示(最小化实现):

for event in events:
    if event.is_final_response() and event.content and event.content.parts:
        print(event.content.parts[0].text)

        # Optional: Show source count
        if event.grounding_metadata and event.grounding_metadata.grounding_chunks:
            print(f"\nBased on {len(event.grounding_metadata.grounding_chunks)} documents")
for (Event event : events) {
    if (event.finalResponse()) {
        System.out.println(event.content().parts().get(0).text());

        // Optional: Show source count
        if (event.groundingMetadata().isPresent()) {
            System.out.println("\nBased on " + event.groundingMetadata().get().groundingChunks().size() + " documents");
        }
    }
}
events.collect { event ->
    if (event.isFinalResponse) {
        println(event.content?.parts?.firstOrNull()?.text)

        // Optional: Show source count
        val chunks = event.groundingMetadata?.groundingChunks
        if (!chunks.isNullOrEmpty()) {
            println("\nBased on ${chunks.size} documents")
        }
    }
}

增强型引用显示功能(可选): 你可以实现交互式的引用功能,这些引用能够显示哪些文档支持某一条陈述。相关的元数据(grounding metadata)提供了将文本片段与源文档关联起来所需的所有必要信息。

实施注意事项

在实现“通过搜索进行接地处理”(Grounding with Search)功能时,系统会显示以下内容:

  1. 文档访问(Document Access):验证用户对所引用文档的访问权限。
  2. 简单的集成(Simple Integration):基本文本输出不需要任何额外的显示逻辑。
  3. 可选的增强功能(Optional Enhancements):只有在你的使用场景确实需要引用来源信息时,才添加引用内容。
  4. 文档链接:在需要时,将文档的 URI 转换为可访问的内部链接。
  5. 搜索查询: The retrievalQueries 该数组显示了针对您的数据存储库进行了哪些搜索操作。