跳转到正文
中文
获取 API 密钥

工作流 / Python

为 AI 智能体添加 Google 和 YouTube 搜索工具

将搜索和转录文本请求封装为 Python 工具,保留数据源引用,让您的智能体自主决定何时获取数据。

FlashData · 发布于

连接到网页搜索和视频数据工具的智能体

定义工具边界

为智能体提供输入输出清晰的小型工具:搜索网页、发现视频,以及读取视频的可用转录文本。由智能体决定何时调用这些工具,以及如何使用所获资料。

下方代码提供了数据获取函数。将这些函数注册到现有的智能体框架中;无论选择哪种模型或编排库,它们都可独立使用。

bash
# Replace YOUR_API_KEY near the top of the code below.

实现检索工具

以下 Python 3 代码使用标准库。将其保存为 tools.py。直接运行会发起一次 Google 搜索请求;导入后,你的应用可以将这三个函数注册为工具。

python
import json
import gzip
import os
import urllib.error
import urllib.request

API_URL = "https://data.flashdata.dev"
API_KEY = "YOUR_API_KEY"


def api_request(path, payload=None, response_headers=None, base_url=API_URL):
    target = path if path.startswith(("https://", "http://")) else base_url + path
    request = urllib.request.Request(
        target,
        data=json.dumps(payload).encode() if payload is not None else None,
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        method="POST" if payload is not None else "GET",
    )
    with urllib.request.urlopen(request, timeout=60) as response:
        if response_headers is not None:
            response_headers.update(response.headers)
        return json.load(response)


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, file_pointer, code, message, headers, new_url):
        return None


def result_request(url):
    request = urllib.request.Request(url, headers={"X-API-Key": API_KEY}, method="GET")
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=60):
            raise RuntimeError("Results endpoint did not redirect to storage")
    except urllib.error.HTTPError as response:
        if response.code != 302 or not response.headers.get("Location"):
            raise
        storage_url = response.headers["Location"]
        response.close()
    storage_request = urllib.request.Request(storage_url, headers={"Accept-Encoding": "gzip"})
    with urllib.request.urlopen(storage_request, timeout=60) as response:
        body = response.read()
        if response.headers.get("Content-Encoding") == "gzip":
            body = gzip.decompress(body)
        return json.loads(body)["results"]


def search_web(query):
    """Search the web and return titles, URLs and result snippets."""
    response = api_request("/v1/queries/realtime", {
        "source": "google_search", "query": query,
    })
    return response["results"][0]


def find_videos(query):
    """Discover YouTube videos and their video IDs."""
    response = api_request("/v1/queries/realtime", {
        "source": "youtube_search", "query": query,
        "params": {"max_results": 5},
    })
    return response["results"][0]["results"]


def read_video_transcript(video_id, language="en"):
    """Read available captions with timestamps; captions may be unavailable."""
    response = api_request("/v1/queries/realtime", {
        "source": "youtube_transcript", "video_id": video_id,
        "params": {"language": language, "auto": True},
    })
    return response["results"][0]


# Register these functions as tools in your own agent framework.
# The agent chooses when to call them and how to use the evidence.
if __name__ == "__main__":
    print(json.dumps(search_web("distributed systems"), indent=2))
bash
python3 tools.py

将工具接入你的智能体

在框架的工具 schema 中描述每个工具的参数和结果。请将 query, video_id 和 language 作为显式输入,让模型能够请求所需数据。

  • search_web(query) 返回 Google 结果,包含数据源 URL 和摘要。

  • find_videos(query) 返回视频及后续请求所需的 ID。

  • read_video_transcript(video_id, language) 返回可用字幕分段及时间戳。

请求失败或字幕轨道不可用时,返回有助于排查的工具错误。遵守应用的积分和请求预算,让智能体决定是否尝试其他查询或使用其他数据源。

保留数据源与时间戳

搜索摘要只是页面预览。请保留其 URL,不要将摘要视为完整文章。对于字幕文本,请保留视频 ID、语言和分段时间,以便智能体引用原文。

构建视频知识库时,请为每个文本片段保存视频标题和带时间戳的数据源链接。这样,检索系统就能同时返回内容及用于支持回答的参考资料。