SandBaseを使ったDataForSEO APIキーワードリサーチエージェント

SandBase経由でDataForSEOのキーワードまたは競合リクエストを1件から開始し、プロバイダー報告の価格を確認して、日付付きのキーワードリサーチエージェント実験をレビューします。

SandBase上のDataForSEOキーワードリサーチエージェントのカバー画像。テスト結果ではなく編集用アートワークです

2026-10-03 に、DataForSEO はシード「ai agent」に対して、月間検索数がちょうど 49,500 のキーワードを 7 つ返しました。「ai agent」「agent ai」「agent in ai」「ai intelligent agent」、そしてさらに 3 つです。それらの 12 か月のボリューム系列は同一でした。これらの行を合計すると、存在しない 346,500 回の検索になります。

これは DataForSEO API キーワードリサーチエージェントが最初に対処しなければならないことであり、数値はコードに置くべきだという良い例です。以下の過去の実験では、約 170 行の Python でそれを構築しました。現在のセットアップのセクションは、1 つの境界付けられたリクエストから始まります。その実験はシードトピックと競合ドメインを受け取り、優先順位付けされたキーワードリストを生成し、オーガニック結果と競合のランキングをサンプリングし、その後openai/gpt-6.1-solを使って計画を書きました。その呼び出しは 1 つの API キーで SandBase を経由しました。以下の現在のヘルパーは 1 つのタスク結果のみを返します。その完全なパイプラインを再実行するものではありません。

要点

  • 3 つの DataForSEO エンドポイントがこの作業をカバーします: keyword_suggestions(アイデア、ボリューム、難易度、インテント)、ranked_keywords(競合がランクインしているもの)、serp/google/organic/live/advanced(ライブの上位結果)。3 つとも 2026-10-03 時点で SandBase 上で有効です。
  • 1 回の完全な実行で 5 回のデータ呼び出しと 1 回の LLM 呼び出しを行いました。LLM 呼び出しのコストは $0.0104 でした。データ呼び出しは 2026-10-03 のみ「API Free Week」という、すでに終了したプロモーションのため $0.00 で請求されました。2026-11-08 に検査した 2 つの Labs 契約はプロバイダー報告コストの価格設定を使用しており、無料枠を宣伝していません。
  • 近いバリアントは 1 つのボリューム数値を共有します。12 か月の系列でグループ化すると、50 件のサジェストがより少なく、正直な行にまとまりました。「ai agent」だけで 7 件を吸収しました。
  • ライブ SERP は素早く動きました: 約 6 分間隔の 2 回のチェックで、「ai agent」の上位 5 つのオーガニックドメインがまったく重なりませんでした。1 回の SERP 取得はサンプルとして扱ってください。
  • データは DataForSEO によるサードパーティの SEO 推定値であり、Google 自身のデータではありません。

現在の最初のリクエスト: 1 つのリサーチタスクを選ぶ

契約レビュー: 2026-11-08。 シードフレーズには Keyword Suggestions を、既知の競合ドメインまたはページには Ranked Keywords を使用してください。これらは別々のリクエストです。現在の SandBase フォームはkeywordまたはtarget、加えてlocation_code、language_code、limit(最大 100)を公開しています。スキーマは必須フィールドをマークせず、追加プロパティを許可しています。この最初のリクエストの例では、表示されている 4 つのフィールドすべてを意図的に指定しています。高度な上流オプションはこのリビジョンのテスト範囲外であり、サポートされないことが証明されたわけではありません。

リサーチの問いに合わせて市場と言語を選択してください。例では米国のコード2840、英語en、上限 5 を使用しています。これらは明示的なサンプルの選択であり、グローバルなデフォルトや別の市場に関する証拠ではありません。

  • すでにキーをお持ちですか?ローカルのSANDBASE_API_KEY環境変数またはシークレットマネージャーに保管し、プロンプトやコミットされたファイルには置かないでください。
  • すでにエージェントを SandBase に接続済みですか?その接続を再利用し、DataForSEO を検出するよう依頼してから、リクエストを準備する前に選択したエンドポイントを検査してください。
  • プロジェクトを始めますか?エージェントにセットアップ Skillと Markdown Quickstart、シードまたは競合、市場と言語を渡してください。1 つのリクエストを準備し、実行前に価格を説明するよう依頼してください。誤ってマルチキーワードのパイプライン全体を承認しないでください。

両方の Labs 契約は現在、基本価格 $0.0126、計算式 usage.provider_reported_cost を記載しています。基本価格はすべてのリクエストに対する固定の最終見積もりではありません。どちらの検査でも無料枠は宣伝されていません。実行前に現在の価格とリクエストの予算を確認してください。実際のアカウント請求は別の請求記録のままです。このリビジョンでは新たな有料呼び出しは行っていません。

requestsをpython -m pip install requestsでインストールしてください。コードをfirst_seo_request.pyとして保存し、キーをローカルで設定し、選択したリクエストを確認した後にのみpython first_seo_request.pyを実行してください。課金される可能性のある POST を 1 回行い、リトライ、ページネーション、SERP 呼び出し、LLM ステップはありません。

Python
import os
import requests


def query_once(mode, value, location_code=2840, language_code="en", limit=5):
    routes = {"suggestions": ("keyword_suggestions", "keyword"),
              "ranked": ("ranked_keywords", "target")}
    if mode not in routes or not isinstance(value, str) or not value.strip():
        raise ValueError("Choose suggestions + seed, or ranked + domain/page")
    if type(limit) is not int or not 1 <= limit <= 100:
        raise ValueError("Use an integer limit from 1 to 100")
    if type(location_code) is not int or location_code <= 0:
        raise ValueError("Use a supported positive DataForSEO location code")
    if not isinstance(language_code, str) or not language_code.strip():
        raise ValueError("Choose a supported language code")
    key = os.environ.get("SANDBASE_API_KEY", "").strip()
    if not key:
        raise RuntimeError("Set SANDBASE_API_KEY locally")
    endpoint, field = routes[mode]
    url = f"https://api.sandbase.ai/v1/api/dataforseo/v3/dataforseo_labs/google/{endpoint}/live"
    try:
        response = requests.post(url,
            headers={"Authorization": f"Bearer {key}"},
            json={field: value.strip(), "location_code": location_code,
                  "language_code": language_code.strip(), "limit": limit},
            timeout=(10, 90), allow_redirects=False)
        if not 200 <= response.status_code < 300:
            raise RuntimeError(f"SandBase HTTP {response.status_code}; inspect before retrying")
        body = response.json()
    except ValueError:
        raise RuntimeError("SandBase returned invalid JSON") from None
    except requests.RequestException:
        raise RuntimeError("Request failed; check run history before retrying") from None
    if not isinstance(body, dict) or body.get("status") != "completed":
        raise RuntimeError("SandBase run did not complete; inspect status and error")
    outputs = body.get("outputs")
    if not isinstance(outputs, list) or not outputs or not isinstance(outputs[0], dict):
        raise RuntimeError("Missing outputs[0]")
    payload = outputs[0].get("data")
    if not isinstance(payload, dict):
        raise RuntimeError("Missing object at outputs[0].data")
    if payload.get("status_code") != 20000:
        raise RuntimeError("DataForSEO response failed or lacks a success code")
    tasks = payload.get("tasks")
    if not isinstance(tasks, list) or len(tasks) != 1 or not isinstance(tasks[0], dict):
        raise RuntimeError("Expected one DataForSEO task")
    if tasks[0].get("status_code") != 20000:
        raise RuntimeError("DataForSEO task failed or lacks a success code")
    results = tasks[0].get("result")
    if not isinstance(results, list) or not results or not isinstance(results[0], dict):
        raise RuntimeError("No usable DataForSEO task result; do not infer zero demand")
    return results[0]


if __name__ == "__main__":
    # Choose ONE mode: use "ranked", "learn.microsoft.com" instead for a competitor.
    result = query_once("suggestions", "ai agent")
    print("Result keys:", sorted(result))

新しいヘルパーは現在の SandBase outputs[0].dataエンベロープのみに従います。DataForSEO Keyword Suggestions レスポンスと Ranked Keywords レスポンスは、プロバイダーレベルとタスクレベルの両方でstatus_code: 20000を文書化しています。HTTP 200 だけでは不十分です。status または result が欠けている場合、この厳格な例は停止します。空の result オブジェクトは検索ボリューム 0 に変換されません。ビジネスフィールドをマッピングする前に、承認された実際のレスポンスを検査してください。これらの分岐はオフラインでテストされたもので、新しいライブ結果に対してではありません。タイムアウト後は、リトライを決める前に実行履歴を検査してください。

過去のワークフロー: 2026-10-03 にテスト済み

残りのウォークスルー、実行 ID、出力、完全なパイプラインは元の実験を保持しています。高度なオプションと過去のエンベロープフォールバックを使用しており、新たに検証されたセットアップ経路ではありません。その古い無料プロモーションのスクリーンショットとサンプルランキングは、今日の価格や順位を立証するものではありません。初期統合には上記の現在の 1 リクエストの例を使用してください。過去のパイプラインを適応させる前に、追加のエンドポイントとパラメーターをすべて再検証してください。

過去のエージェントが生成したもの

過去の出力ソース価格の文脈
シードを含むキーワードアイデア、search_volume、keyword_difficulty、main_intent付きdataforseo_labs/google/keyword_suggestions/live実行前にプロバイダー報告コストの価格設定を再確認
競合がランクインしているキーワード、その順位と URL 付きdataforseo_labs/google/ranked_keywords/live実行前にプロバイダー報告コストの価格設定を再確認
上位 3 キーワードのトップオーガニックドメインserp/google/organic/live/advanced呼び出しごとに課金(カタログ参照)
バリアントのグループ化、機会スコア、マージ、CSVPython—
最大 8 項目の箇条書きの計画openai/gpt-6.1-sol過去の 2026-10-03 表示: 入力 $2/M、出力 $10/M トークン

出力はkeyword_plan.csvに加えて、印刷された表と計画です。

SandBase 上の DataForSEO カタログは 2026-10-03 時点で 74 のエンドポイントを記載しています。選択されたカード(このエージェントが呼び出さない OnPage エンドポイント)は API Free Week 中に Available と Free を示していました:

SandBase DataForSEO API カタログ。SERP Google Organic Live を含む 74 のエンドポイントを表示し、選択されたカードは API Free Week 中に Available と Free とマークされている キャプション: SandBase DataForSEO カタログは「API Free Week」バナー下に、SERP Google Organic Live を含む 74 のエンドポイントを記載しています(2026-10-03 撮影)。そのプロモーションは終了しています。このスクリーンショットは現在の無料枠の証拠ではありません。

カタログはGET /apis/v1/...のサーフェスを示しています。このチュートリアルでは、エンドポイントリファレンスの Model API ルートPOST https://api.sandbase.ai/v1/api/dataforseo/<path>を使用します。

データの境界、および DataForSEO 直接 vs SandBase

これは公開された読み取り専用の SEO データを使用します。キーワードボリューム、難易度スコア、SERP スナップショットは、上流プロバイダーである DataForSEO が生成したサードパーティの推定値です。これらは Google 自身のデータではなく、SandBase は Google と提携していません。エージェントには SandBase API キーが必要です。Google Search Console、Google Ads アカウント、サイト所有者のアナリティクス、またはサイトやアカウントを変更するものには一切触れません。

DataForSEO を直接呼び出すこともできます。違いは主に配線です:

DataForSEO 直接SandBase 経由の DataForSEO
認証DataForSEO API のログインとパスワードによる HTTP Basic(認証ドキュメント)Authorization: Bearer $SANDBASE_API_KEY
リクエストボディタスクオブジェクトの JSON 配列1 つのタスクオブジェクト。選択した SandBase 契約に対してフィールドを検証
レスポンスDataForSEO のtasks[].result[]現在のoutputs[0].dataエンベロープ下の DataForSEO ボディ
LLM ステップ別のプロバイダー、キー、請求同じキー、POST /v1/chat/completions
これを選ぶのはDataForSEO のみを、大量に、自社契約で必要とする場合SEO データとモデルを 1 つのキーと 1 つの契約の背後に置きたい場合

2 つの価格は比較していません。DataForSEO は独自の価格を公開しています。

ステップ 1: ボリュームと難易度付きのキーワードアイデア

2026-10-03 のモデルページは「0 input fields」を示していました。それは過去のものです。現在の 4 フィールドのフォームは上記で説明しています。古い実験では DataForSEO のドキュメントの高度なパラメーター、filters、order_by、include_seed_keywordを使用しました。これらのオプションはこのリビジョンでは再検証されていません。

DataForSEO Labs Google Keyword Suggestions の SandBase モデルページ。API Free Week 中の Free 基本価格、同期実行、api モデルタイプ、0 input fields を表示 キャプション: API Free Week 中の Free と 0 input fields を示す過去の 2026-10-03 ページ。現在のフィールドと価格は上記で説明しています。このスクリーンショットは現在のスキーマや価格の参照ではありません。

2026-10-03(UTC)にテスト済み

公開入力: 汎用シード「ai agent」、Google 米国(location_code 2840)、英語、競合ドメインとして Microsoft Learn(learn.microsoft.com)。

Shell
curl -s https://api.sandbase.ai/v1/api/dataforseo/v3/dataforseo_labs/google/keyword_suggestions/live \
  -H "Authorization: Bearer $SANDBASE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"keyword": "ai agent", "location_code": 2840, "language_code": "en",
       "include_seed_keyword": true, "limit": 50,
       "filters": [["keyword_info.search_volume", ">=", 100]],
       "order_by": ["keyword_info.search_volume,desc"]}'

トリミングされたレスポンス(実行 ID 6ed0cb41-ad1f-4bf3-a10e-bb1c046e2223、50 項目のうちの 1 つ):

JSON
{
  "id": "6ed0cb41-ad1f-4bf3-a10e-bb1c046e2223",
  "status": "completed",
  "model": "dataforseo/v3/dataforseo_labs/google/keyword_suggestions/live",
  "outputs": [{
    "status_code": 20000,
    "tasks": [{"status_code": 20000, "result": [{
      "total_count": 615, "items_count": 50,
      "items": [{
        "keyword": "ai agent",
        "keyword_info": {"search_volume": 49500, "competition_level": "MEDIUM", "cpc": 20.9,
          "monthly_searches": [{"year": 2026, "month": 8, "search_volume": 49500}, "…"]},
        "keyword_properties": {"core_keyword": "agentic ai", "keyword_difficulty": 70},
        "search_intent_info": {"main_intent": "commercial"}
      }]
    }]}]
  }]
}

過去の観察のみ: 2026-10-03 に、ここで記録された 22 回の呼び出しは DataForSEO ボディをoutputs[0]に直接置き、文書化されたoutputs[0].dataとは異なっていました。以下のアーカイブされたパイプラインは、それらの結果を説明するためにフォールバックを保持しています。新しい統合では現在のヘルパーのようにoutputs[0].dataを使用し、古いエンベロープを黙って受け入れるのではなく契約の不一致を報告すべきです。

上記のビジネスフィールド(search_volume、keyword_difficulty、monthly_searches、core_keyword、main_intent)は、これらの実行と DataForSEO のドキュメントで観察されています。それらは SandBase からの保証ではありません。コードはそれぞれを.get()で読み取ります。ペイロードは DataForSEO 自身のcostフィールドも運びます。SandBase アカウントに請求されるのは、GET /v1/tasks/<id>/costが報告するものです。

ステップ 2: 競合がすでにランクインしているもの

ranked_keywordsはtargetドメインを受け取ります。そのデータは DataForSEO のスナップショットで、彼らのドキュメントによれば毎週更新されるため、これらの順位は同日の Google チェックではありません(以下の SERP ステップがライブのものです)。シードを含むキーワードに絞り込み、ボリュームで並べ替えました:

JSON
{"target": "learn.microsoft.com", "location_code": 2840, "language_code": "en", "limit": 50,
 "filters": [["keyword_data.keyword", "like", "%ai agent%"]],
 "order_by": ["keyword_data.keyword_info.search_volume,desc"]}

実行 ID d38178c1-e21d-4610-9763-02c222363b14はtotal_count 254 を報告し、50 項目を返しました。1 つをトリミング:

JSON
{"keyword_data": {"keyword": "ai agent course",
   "keyword_info": {"search_volume": 1000},
   "keyword_properties": {"keyword_difficulty": 12}},
 "ranked_serp_element": {"serp_item": {"type": "organic", "rank_group": 2, "rank_absolute": 3,
   "domain": "learn.microsoft.com",
   "url": "https://learn.microsoft.com/en-us/shows/ai-agents-for-beginners/"}}}

keyword_dataはサジェスト項目と同じフィールド名を使用しているため、1 つのrow_from()関数が両方をフラット化します。rank_groupはオーガニック結果の中での順位です。rank_absoluteはすべての SERP 要素を数えます。

dataforseo ranked_keywords live の SandBase API リファレンス。POST ルートと、outputs data オブジェクトを含む完了したレスポンス例を表示 キャプション: ranked_keywords/liveリファレンスはPOST /v1/api/dataforseo/v3/dataforseo_labs/google/ranked_keywords/liveと、outputs[0].dataを含む完了した例を示しています。これはライブ呼び出しと異なっていた形です(2026-10-03 撮影)。

リファレンスの生成された curl サンプルは、ボディにmodelフィールドを入れています。パスがすでにモデルを指定しているため、コードは DataForSEO のフィールドのみを送信します。

このステップに落ち着く前に、明白な近道を試しました: 以前のテスト呼び出しからの 30 件のサジェストを、inフィルター付きでranked_keywordsに渡しました(実行 ID 75cad2ec-fd7d-4eda-ace5-8274c295eff0)。Microsoft Learn はそのうちちょうど 1 つ(「no code ai agent builder」、順位 58)にランクインしていました。実際にランクインしているキーワード、たとえば「build ai agents」や「ai agent course」は、サジェストとして一度も現れませんでした。競合のギャップは両方のリストをマージすることから生まれ、交差させることからではありません。

ステップ 3: 上位キーワードのライブ SERP

SERP エンドポイント(DataForSEO ドキュメント)はkeyword、location_code、language_code、depthを受け取ります。depth: 10で、3 回の呼び出しはそれぞれ 12 または 13 項目を返し、そのうち 6 から 8 がorganicでした。最初の項目は毎回ai_overviewだったため、コードはtype == "organic"でフィルタリングします。「ai voice agent」の実行 ID a6618702-02a4-47bd-8f85-e848f2309252:

JSON
[{"type": "ai_overview", "rank_group": 1, "rank_absolute": 1},
 {"type": "organic", "rank_group": 1, "rank_absolute": 2, "domain": "www.retellai.com"},
 {"type": "organic", "rank_group": 2, "rank_absolute": 3, "domain": "elevenlabs.io"},
 {"type": "organic", "rank_group": 3, "rank_absolute": 4, "domain": "www.reddit.com"}]

その後、6 分後にプログラム全体をもう一度実行しました。「ai agent」について、04:10 UTC のチェックでは上位 5 つのオーガニック結果に IBM、aiagent.app、AWS、Wikipedia、Meta がありました。04:16 のチェックでは Reddit、LinkedIn、retresco.de、airia.com、airbyte.com がありました。まったく重なりませんでした。「what is an ai agent」もまったく重なりませんでした。「ai voice agent」は Reddit のみを共有しました。2 つのサンプルからは、それが Google 自身の変動なのか、AI Overview のレイアウトなのか、DataForSEO の収集なのかは判断できません。そのため計画では、SERP ドメインをランキングのターゲットリストではなく、ページタイプのヒントとして扱います。

ステップ 4: コードでのスコアリング

3 つのルール、すべてbuild_table()内:

  1. 両方のリストをキーワードでマージし、一致する行に競合のrank_groupと URL をコピーする。
  2. ボリュームが 100 未満、難易度なし、またはnavigationalインテント(「n8n ai agent」のようなブランド検索)の行を削除する。
  3. 同一の 12 か月ボリューム系列で近いバリアントをグループ化する。代表は可能ならシードを含み、次に最短のもの。variantsは折り込まれた行数を記録する。

次にopportunity = volume × (100 − difficulty) / 100。これは DataForSEO の 0〜100 の難易度でボリュームを割り引くヒューリスティックです。トラフィック予測ではありません。表は上位 12 行に加え、競合がランクインしている最大 5 行を保持するため、ギャップリストが底から落ちることはありません。

なぜ DataForSEO のcore_keywordではなくボリューム系列なのか?この実行では、core_keywordは「ai agent」を「agentic ai」と同じグループにしましたが、「ai intelligent agent」は別のグループにしました。両方とも同じ 49,500 と同じ月次数値を報告していたにもかかわらずです。系列の一致はより粗いですが、実際の問題、つまり二重計上されたボリュームを狙っています。無関係な 2 つのキーワードが偶然に系列を共有する可能性はあります。12 か月でボリューム ≥ 100 では、私はそれが起こるのを見ませんでした。

ステップ 5: LLM が計画を書く

openai/gpt-6.1-solは表と SERP ドメインを JSON として受け取り、厳格な指示を受け取ります: 数値はデータからのみ引用し、新しい数値を計算しないこと。これを選んだのは、私たちの Claude Sonnet 5.5 vs GPT-6.1 Sol エージェントテストで、30 件の短いツールタスクのうち 30 件すべてに正しく回答し、タスクあたり約 $0.0066 だったからです。そのテストでのミスはツール出力に対する算術であり、まさにそれがここで平均、グループ化、スコアリングを Python に留めている理由です。呼び出しは OpenAI 互換の Chat Completions ルートを使用します。

アーカイブされた完全なコード — 現在のセットアップ例ではありません

このコードは 2026-10-03 の実験の証拠として変更されずに保持されています。現在テストされた統合としてコピーしないでください。その高度なパラメーター、エンベロープフォールバック、マルチ呼び出しコストは再検証が必要です。

Python
#!/usr/bin/env python3
"""SEO keyword-research agent: DataForSEO data through SandBase, numbers in code, plan by an LLM.

Usage: python3 seo_research_agent.py "ai agent" learn.microsoft.com
Needs SANDBASE_API_KEY in the environment. Writes keyword_plan.csv and prints a plan.
"""
import csv
import json
import os
import sys

import requests

FIELDS = ["keyword", "variants", "volume", "difficulty", "intent", "opportunity",
          "competitor_rank", "competitor_url", "serp_top3"]
API = "https://api.sandbase.ai"
HEADERS = {
    "Authorization": f"Bearer {os.environ['SANDBASE_API_KEY']}",
    "Content-Type": "application/json",
}
LOCALE = {"location_code": 2840, "language_code": "en"}  # United States, English
TOP_N = 12            # best rows by opportunity
COMPETITOR_EXTRA = 5  # extra rows where the competitor ranks, even below the cut
SERP_CHECKS = 3       # live SERP lookups for the top keywords


def dataforseo(path: str, params: dict) -> dict:
    """POST /v1/api/dataforseo/<path> and return the first DataForSEO task result."""
    resp = requests.post(f"{API}/v1/api/dataforseo/{path}", headers=HEADERS, json=params, timeout=120)
    resp.raise_for_status()
    body = resp.json()
    outputs = body.get("outputs") or []
    if body.get("status") != "completed" or not outputs:
        raise RuntimeError(f"SandBase call did not complete: {body.get('status')} {body.get('error')}")
    # Documented contract: outputs[0].data. Observed on 2026-10-03: DataForSEO's body sat directly in outputs[0].
    data = outputs[0].get("data")
    payload = data if isinstance(data, dict) and "tasks" in data else outputs[0]
    tasks = payload.get("tasks") or []
    if not tasks or tasks[0].get("status_code") != 20000:
        task = tasks[0] if tasks else payload
        raise RuntimeError(f"DataForSEO task failed: {task.get('status_code')} {task.get('status_message')}")
    results = tasks[0].get("result") or []
    return results[0] if results else {}


def keyword_ideas(seed: str, limit: int = 50) -> list[dict]:
    """Keywords that contain the seed, with volume >= 100, biggest first."""
    result = dataforseo("v3/dataforseo_labs/google/keyword_suggestions/live", {
        "keyword": seed, **LOCALE, "include_seed_keyword": True, "limit": limit,
        "filters": [["keyword_info.search_volume", ">=", 100]],
        "order_by": ["keyword_info.search_volume,desc"],
    })
    return result.get("items") or []


def competitor_keywords(domain: str, seed: str, limit: int = 50) -> list[dict]:
    """Keywords containing the seed that the competitor domain ranks for."""
    result = dataforseo("v3/dataforseo_labs/google/ranked_keywords/live", {
        "target": domain, **LOCALE, "limit": limit,
        "filters": [["keyword_data.keyword", "like", f"%{seed}%"]],
        "order_by": ["keyword_data.keyword_info.search_volume,desc"],
    })
    return result.get("items") or []


def top_organic(keyword: str, n: int = 5) -> list[dict]:
    """Live Google organic results (first page) for one keyword."""
    result = dataforseo("v3/serp/google/organic/live/advanced", {"keyword": keyword, **LOCALE, "depth": 10})
    organic = [i for i in result.get("items") or [] if i.get("type") == "organic"]
    return [{"rank": i.get("rank_group"), "domain": i.get("domain"), "url": i.get("url")} for i in organic[:n]]


def row_from(kw: dict) -> dict:
    """Flatten the keyword fields both Labs endpoints share."""
    info = kw.get("keyword_info") or {}
    props = kw.get("keyword_properties") or {}
    # Close variants ("ai agent", "agent ai") came back with identical 12-month volume series.
    series = tuple(m.get("search_volume") for m in info.get("monthly_searches") or [])
    return {
        "keyword": kw.get("keyword"),
        "cluster": series or kw.get("keyword"),
        "volume": info.get("search_volume") or 0,
        "difficulty": props.get("keyword_difficulty"),
        "intent": (kw.get("search_intent_info") or {}).get("main_intent"),
        "competitor_rank": None,
        "competitor_url": "",
    }


def build_table(seed: str, ideas: list[dict], ranked: list[dict]) -> list[dict]:
    """Merge both sources, collapse close variants, score, and keep the top rows."""
    rows = {}
    for kw in ideas:
        rows[kw.get("keyword")] = row_from(kw)
    for item in ranked:
        kw = item.get("keyword_data") or {}
        serp_item = (item.get("ranked_serp_element") or {}).get("serp_item") or {}
        row = rows.setdefault(kw.get("keyword"), row_from(kw))
        row["competitor_rank"] = serp_item.get("rank_group")
        row["competitor_url"] = serp_item.get("url") or ""

    # One row per variant group. Representative: contains the seed, then the shortest keyword.
    keep = [r for r in rows.values()
            if r["volume"] >= 100 and r["difficulty"] is not None and r["intent"] != "navigational"]
    keep.sort(key=lambda r: (seed not in r["keyword"], len(r["keyword"])))
    best = {}
    for row in keep:
        winner = best.setdefault(row["cluster"], {**row, "variants": 0})
        winner["variants"] += 1
        if row["competitor_rank"] and not winner["competitor_rank"]:
            winner["competitor_rank"], winner["competitor_url"] = row["competitor_rank"], row["competitor_url"]

    # Opportunity = volume discounted by difficulty (0-100). A heuristic, not a traffic forecast.
    for row in best.values():
        row["opportunity"] = round(row["volume"] * (100 - row["difficulty"]) / 100)
    ranked_rows = sorted(best.values(), key=lambda r: r["opportunity"], reverse=True)
    # Top rows overall, plus the competitor's best keywords even if they fall below the cut.
    table = ranked_rows[:TOP_N]
    table += [r for r in ranked_rows if r["competitor_rank"] and r not in table][:COMPETITOR_EXTRA]
    return table


def write_plan(seed: str, domain: str, table: list[dict], serps: dict) -> tuple[str, dict]:
    """Ask openai/gpt-6.1-sol for a short plan. It gets computed numbers and must not invent new ones."""
    prompt = (
        f"Seed topic: {seed}. Competitor: {domain}. Market: Google US, English.\n"
        f"Keyword table (opportunity = volume x (100 - difficulty) / 100, computed in code):\n"
        f"{json.dumps([{k: r.get(k) for k in FIELDS} for r in table], ensure_ascii=False)}\n"
        f"Current top organic results for the top keywords:\n{json.dumps(serps, ensure_ascii=False)}\n\n"
        "Write a content plan in at most 8 bullets: which 3-5 keywords to target first and why, "
        "where the competitor already ranks, and what page type each target needs based on the SERP. "
        "Quote numbers only from the data above; do not compute or estimate new ones."
    )
    resp = requests.post(f"{API}/v1/chat/completions", headers=HEADERS, timeout=120, json={
        "model": "openai/gpt-6.1-sol",
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 800,
    })
    resp.raise_for_status()
    body = resp.json()
    return body["choices"][0]["message"]["content"], body.get("usage") or {}


def main(seed: str, domain: str) -> None:
    ideas = keyword_ideas(seed)
    ranked = competitor_keywords(domain, seed)
    print(f"{len(ideas)} keyword suggestions, {len(ranked)} competitor keywords containing '{seed}'")
    table = build_table(seed, ideas, ranked)
    serps = {row["keyword"]: top_organic(row["keyword"]) for row in table[:SERP_CHECKS]}
    for row in table[:SERP_CHECKS]:
        row["serp_top3"] = " | ".join(r["domain"] for r in serps[row["keyword"]][:3])

    with open("keyword_plan.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore")
        writer.writeheader()
        writer.writerows(table)

    print(f"\n{'keyword':28} {'var':>3} {'volume':>7} {'KD':>3} {'opp':>6} {'comp':>4}  intent")
    for row in table:
        rank = row["competitor_rank"] or "-"
        print(f"{row['keyword'][:28]:28} {row['variants']:>3} {row['volume']:>7} {row['difficulty']:>3} "
              f"{row['opportunity']:>6} {rank:>4}  {row['intent']}")

    plan, usage = write_plan(seed, domain, table, serps)
    print("\nPlan (openai/gpt-6.1-sol):\n" + plan)
    print(f"\nLLM usage: {usage.get('prompt_tokens')} input / {usage.get('completion_tokens')} output tokens")


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit('usage: python3 seo_research_agent.py "<seed topic>" <competitor domain>')
    main(sys.argv[1], sys.argv[2])

Python 3.9+ とrequestsが必要です。python3 seo_research_agent.py "ai agent" learn.microsoft.comで実行してください。

実行が印刷したもの

これは上記のプログラムの出力で、2026-10-03 04:15 UTC に実行されました(6 回の呼び出しすべてcompleted):

Text
50 keyword suggestions, 50 competitor keywords containing 'ai agent'

keyword                      var  volume  KD    opp comp  intent
ai agent                       7   49500  70  14850    -  commercial
ai voice agent                 1   22200  38  13764    -  commercial
what is an ai agent            1   18100  49   9231    -  informational
open source ai agent           2    9900  20   7920    -  commercial
ai code agent                  3    8100  30   5670    -  commercial
ai powered coding agent        1    8100  32   5508    -  commercial
gemini spark ai agent          1    6600  18   5412    -  informational
autonomous ai agent            1    6600  22   5148    -  informational
ai agent moltbook              1    6600  43   3762    -  transactional
open-source ai coding agent    2    5400  31   3726    -  commercial
self-hosted ai agent           1    3600   0   3600    -  commercial
no-code ai agent builder       2    3600  10   3240   58  commercial
build ai agent                 4    2400  20   1920    4  commercial
how to build ai agents         1    1600  41    944    4  informational
ai agent course                2    1000  12    880    2  commercial
ai agent frameworks            1    1000  27    730    2  commercial
build an ai agent              2    1000  28    720    4  informational

LLM usage: 1957 input / 551 output tokens

計画は「open source ai agent」「ai voice agent」「what is an ai agent」「self-hosted ai agent」「no-code ai agent builder」を最初のターゲットとして挙げました。Microsoft Learn の AI Agents for Beginners ページがすでに「build ai agent」で 4 位、「ai agent course」で 2 位にランクインしていることを指摘し、それらの直接対決を延期することを提案しました。私が気に入った箇条書きの 1 つ: SERP チェックのないキーワードについては、ページタイプをでっち上げるのではなく「暫定」と呼びました。また、一致のない行については Microsoft の順位が「報告なし」であると述べ、これは正しい読み方です。ranked_keywordsは DataForSEO がインデックスしたものだけを返します。

表の 2 行は、公開前に読むべきという注意喚起です。「self-hosted ai agent」は難易度 0 を示し、「ai agent moltbook」と「gemini spark ai agent」は、たまたま informational または transactional とタグ付けされた製品名のように見えます。コードはそれらを捕まえません。人間が捕まえるべきです。

コスト

呼び出し実行あたりの回数2026-10-03 の請求(API Free Week、すでに終了)
keyword_suggestions/live1$0.000000
ranked_keywords/live1$0.000000
serp/google/organic/live/advanced3各 $0.000000
openai/gpt-6.1-sol1$0.010401

これらは上記の実行に対してGET /v1/tasks/<id>/costが返した数値です。$0.000000 のデータ行は 2026-10-03 の記録で、3 つの DataForSEO モデルページが「API Free Week」バナー下で基本価格 Free を示していたときのものです。そのプロモーションは終了しています。2 つの Labs 契約の 2026-11-08 の検査はusage.provider_reported_costを示しており、固定の最終的な呼び出しあたりの見積もりではなく、宣伝された無料枠もありません。この過去の 6 回呼び出しの実行における SERP と LLM のステップは、このリビジョンでは再価格設定も再実行もされていません。プロモーションの合計を現在のワークフロー予算に外挿しないでください。

LLM の数値はコスト記録が報告したものであり、私が導出した数値ではありません。2026-10-03 に検査したモデルページは、272K プロンプトトークン未満で入力 $2/M、出力 $10/M を記載しており、これは 1,957 × $2/M + 551 × $10/M = $0.0094 になります。請求された $0.010401 は約 $0.001 高かったです。同じコスト記録の使用量ブロックはcache_creation_tokens: 1954を示していますが、当時記録された計算式はこのプロンプトサイズでキャッシュ書き込みを価格設定していなかったため、その過去の差異は未解決のままで、SandBase チームに提起されました。このリビジョンではそのモデルの価格を再確認していません。計算式ではなくコスト記録から予算を立ててください。私の 3 回の完全な実行を通じて、請求された LLM 呼び出しは $0.0104 から $0.0116 でした。

制限事項

  • 1 つのシード、1 つの市場(米国英語)、1 つの競合、1 日。ボリュームと難易度は DataForSEO の推定値であり、Google Keyword Planner や Search Console とは異なります。
  • 両方の Labs 呼び出しでlimit: 50。keyword_suggestionsは 615 件の一致を報告し、ranked_keywordsは 254 件を報告したため、これは各リストの先頭です。DataForSEO のドキュメントはページング用のoffsetを説明しています。ここではテストしていません。
  • like "%ai agent%"フィルターは部分文字列一致です。「openai agent」にも一致しましたが、ナビゲーショナルインテントフィルターがたまたまそれを落としました。
  • SERP ドメインは 6 分間隔の 2 回の実行間でほぼ完全に変わりました。1 回の取得はランキングではありません。
  • 機会スコアは私が選んだヒューリスティックです。インテントや CPC を重視するなら計算式を変えてください。

FAQ

DataForSEO アカウントなしで DataForSEO API をキーワードリサーチに使用できますか?

SandBase 経由では、SandBase API キーと選択したエンドポイントの契約を使用します。現在の統合はoutputs[0].dataを読み取ります。直接のoutputs[0]の観察はアーカイブされた 2026-10-03 の実験にのみ属します。DataForSEO への直接アクセスは独自の API ログインとパスワードを使用します。

DataForSEO のキーワードデータは Google のものと同じですか?

いいえ。それは DataForSEO のサードパーティ推定値です。ボリュームと難易度は、Google の数値ではなく、自分のリストをランク付けするための相対的なシグナルとして扱ってください。

検索ボリュームの二重計上を避けるにはどうすればよいですか?

近いバリアントをグループ化してください。この実行では、7 つの「ai agent」バリアントがすべて 49,500 を報告し、同一の 12 か月系列を持っていました。系列でグループ化すると、それらはvariants = 7を持つ 1 行になりました。

なぜ LLM にスコアリングをさせないのですか?

算術こそがモデルがつまずくところだからです。私たちの GPT-6.1 Sol vs Claude Sonnet 5.5 テストでは、3 つの誤答すべてがツール出力に対する平均またはカウントでした。Python は無料で正確に行います。モデルは計画を書くだけです。

このようなエージェントに合う他の検索 API はどれですか?

エージェント内での一般的なウェブ検索については、私たちのウェブ検索 API まとめと Exa vs Tavily vs Firecrawl vs SerpAPI 比較をご覧ください。ここでの DataForSEO の利点は SEO メトリクスです: ボリューム、難易度、ドメインごとのランクインキーワード。

次のステップ

SandBase API キーを取得するか、DataForSEO カタログを開くか、ranked_keywordsリファレンスをお読みください。現在のセットアップのセクションで、承認された 1 つのリクエストから始めてください。別の、予算化された SERP 比較を設計する前にレスポンスを検査してください。

役に立ったらシェアしてください