跳转到内容

用于 ADK 的非结构化数据转换工具(Unstructured Transform MCP Tool)

在 ADK 中得到支持。Python

The 非结构化数据转换 MCP 服务器 将您的 ADK 代理连接到…… 非结构化的这是一个文档处理平台,能够将原始文件转换为结构化的数据,从而便于人工智能(AI)进行处理。通过这种集成,您的代理(agent)可以解析 PDF 文件、Office 文档、电子邮件、图片以及扫描文件(支持超过 40 种文件格式)。 支持的文件类型 将原始数据(总计……)通过自然语言处理技术转换为经过分区处理、内容丰富化、分块处理以及嵌入格式的最终输出结果。Transform 是一个托管式的远程 MCP(Media Content Processing)服务器,因此用户无需在本地安装或运行任何软件。

使用场景

  • RAG 数据的摄取(Ingestion)将各种类型的文档集合解析为结构清晰、分块处理后的数据格式,这些数据格式可以直接用于向量存储系统以及检索流程。

  • 文档问答代理(Document Q&A Agents)让代理根据需求获取并解析合同、报告或相关文件,然后根据解析后的内容回答问题。

  • 格式标准化将各种类型的输入数据(扫描后的 PDF 文件、电子表格、演示文稿以及电子邮件内容)转换为一种统一、结构化的格式。

  • 在代理程序运行时进行光学字符识别(OCR):从图像和扫描的文档中提取文本和结构信息,作为更大规模自动化工作流程中的一个环节。

  • 结构化数据提取从表单、发票和合同中提取指定的字段,并将这些字段以 JSON 格式输出;这些 JSON 数据需要符合某种规范(该规范可以由用户自行提供,也可以由服务器从文档中自动生成)。

先决条件

安装

使用以下方法安装 ADK: mcp `extra` 是必需的;如果没有它,ADK 的 MCP 类就无法被导入。

pip install "google-adk[mcp]"

与代理程序(agent)一起使用。

将您的 API 密钥设置为环境变量:

export UNSTRUCTURED_API_KEY="<your-unstructured-api-key>"
export GOOGLE_API_KEY="<your-gemini-api-key>"
export GOOGLE_GENAI_USE_VERTEXAI=FALSE

服务器在每次请求(包括最初的连接建立过程)中,都会使用您的非结构化 API 密钥(作为承载令牌)来进行身份验证。 wait_seconds 这个辅助功能允许代理在状态检查之间暂停执行任务,因为作业的解析过程是异步进行的(即:各个作业的解析过程不会同时完成)。

import asyncio
import os

from google.adk.agents import Agent
from google.adk.tools.mcp_tool import McpToolset, StreamableHTTPConnectionParams


async def wait_seconds(seconds: int) -> dict:
    """Pause before the next status check. Use 30 seconds unless told otherwise.

    Args:
        seconds: How long to wait.

    Returns:
        dict confirming the wait.
    """
    seconds = max(1, min(int(seconds), 120))
    await asyncio.sleep(seconds)
    return {"waited_seconds": seconds}


root_agent = Agent(
    model="gemini-flash-latest",
    name="transform_agent",
    instruction=(
        "You parse documents with the Unstructured Transform MCP server. "
        "Pass public https:// file URLs straight to start_transform_job. It "
        "returns a job_id; poll with check_job_status, calling "
        "wait_seconds(30) between checks (jobs take 30 seconds to a few "
        "minutes). When the job completes, call get_job_results and "
        "report the parsed content back to the user. start_transform_job "
        "accepts an optional stages config; it auto-selects a parse "
        "strategy by default, but if the output looks low quality "
        "(garbled text or lost tables), re-run the file with a hi_res "
        "partition strategy for a cleaner result. If the user wants "
        "specific fields rather than the whole document, extract "
        "instead of just parsing. The extraction tools read the element "
        "JSON a parse produces, so parse the file first and keep the "
        "output_ref that get_job_results returns for it. Call "
        "suggest_extraction_schema_for_file with that output_ref when "
        "you need a schema, then start_extraction_job with "
        "element_json_refs set to the output_refs and schema_to_extract "
        "set to a JSON Schema passed as a JSON string. Poll and read an "
        "extraction job with check_job_status and get_job_results like "
        "any other job; its results come back inline, wrapped with the "
        "source filename, so report that filename with each object. If "
        "asked to parse a local file, explain that this requires the "
        "upload helper from the Unstructured ADK guide."
    ),
    tools=[
        wait_seconds,
        McpToolset(
            connection_params=StreamableHTTPConnectionParams(
                url="https://mcp.transform.unstructured.io",  # root URL; do not append /mcp
                headers={
                    "Authorization": f"Bearer {os.environ['UNSTRUCTURED_API_KEY']}",
                },
                timeout=30.0,  # ADK's 5s default is too short for a remote handshake
                sse_read_timeout=300.0,
            ),
            tool_filter=[
                "request_file_upload_url",
                "start_transform_job",
                "suggest_extraction_schema_for_file",
                "start_extraction_job",
                "check_job_status",
                "get_job_results",
            ],
        )
    ],
)

注意:

转换文档是一个异步过程: start_transform_job 启动一个作业后,代理会进行轮询(即定期检查该作业的状态)。 check_job_status,以及 get_job_results 返回输出文件的预签名下载链接。请指示您的代理在每次状态检查之间暂停一段时间(如上所述),以防止轮询循环频繁请求数据而超出模型的速率限制。

结构化数据提取是一个异步任务,会在解析完成后针对相应的 JSON 数据元素进行执行。这些 JSON 数据元素是通过特定的标识符来识别的。 output_ref 那个;那种 get_job_results 该函数会为每个文件返回相应的结果。为了解析并提取所需数据,程序需要执行两次轮询操作;因此请注意这些操作会消耗额外的时间,并且还需要完成一些模型相关的处理步骤。

为了进行解析(parse)…… local 除了处理文件之外,代理程序还需要一个普通的函数工具,用于处理 HTTP 请求。 PUT这些文件字节被发送到了由预签名 URL 返回的地址。 request_file_upload_url (此次上传操作不属于 MCP 调用类型,因此绝对不能发送相关数据。) Authorization (header)。一个完整的代理程序包含了上传(upload)和等待(wait)功能的相关辅助模块。 《非结构化数据转换 ADK 使用指南》.

可用的工具

工具 描述
request_file_upload_url 返回一个预签名的上传 URL 以及本地文件的引用信息。
start_transform_job 开始解析上传的文件或公共 HTTP(S) 网址;返回一个结果。 job_id.
suggest_extraction_schema_for_file 当您还没有 JSON 模式时,可以从已解析文档的元素数据中生成一个 JSON 模式。
start_extraction_job 根据 JSON 模式,从已解析的元素 JSON 数据中启动结构化数据提取任务;返回提取结果。 job_id.
check_job_status 报告某项作业(job)是否已完成(或处于某个特定状态)。 SCHEDULED, IN_PROGRESS,或 COMPLETED既可用于解析任务,也可用于数据提取任务。
get_job_results 返回已完成任务的输出结果:对于解析任务,会提供预先签名的下载 URL;对于提取任务,则会直接返回提取到的数据。

资源