ツール境界を定義する
エージェントの小さなツールに明確な入力と出力を与えます。Web、discover動画を検索し、ビデオの利用可能なトランスクリプトを読みます。 エージェントは、それらを呼び出し、証拠の使用方法を選択する。
以下のコードは、検索関数を供給します。 既存のエージェントフレームワークに登録して、選択したモデルやオーケストレーションライブラリとは独立して機能します。
# Replace YOUR_API_KEY near the top of the code below.検索ツールの実装
以下のPython 3コードは標準ライブラリを使用します。 保存する tools.py. 直接実行すると、Google検索リクエストが1つになり、アプリケーションをインポートすると、ツールとして3つの機能が登録できます。
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))
python3 tools.pyツールをエージェントに接続
各ツールの引数を記述し、フレームワークのツールスキーマで結果を表示します。 保存する query, video_id とりあえず language 明示的な入力として、モデルが必要とするデータを要求できるようにします。
search_web(query)Google の結果をソースコード URLs とスニペットで返します。find_videos(query)フォローアップリクエストに必要な動画とIDsを返します。read_video_transcript(video_id, language)利用可能なキャプションセグメントをタイムスタンプで返します。
リクエストが失敗したり、キャプショントラックが利用できなくなったときに便利なツールエラーを返します。 アプリケーションのクレジットリクエストと予算を適用し、エージェントは異なるクエリを試すか、別のソースを使用するかどうかを決定します。
ソースとタイムスタンプを保持する
検索スニペットはページのプレビューです。 URLを保存し、スニペットをフル記事として扱うことを避けて下さい。 トランスクリプトでは、ID、言語、セグメントの時間をそのまま保存し、元の通過を切ることができます。
ビデオナレッジベースでは、各テキストチャンクでビデオタイトルとタイムスタンプソースリンクを保存します。 あなたの検索システムは、回答をサポートするために使用されるコンテンツと参考の両方を返すことができます。