Google Trends 趋势分析

Model: qwen-plus | ¥0.24/call
趋势分析Google TrendsSEO 趋势关键词热度serpapi市场调研

Google Trends 趋势分析 google-trends:透传 serpapi 搜关键词热度趋势(时间序列/地区/相关查询)。适合 SEO 趋势、市场热度、关键词调研。支持统一处理流程。

Skill Documentation

---

name: serpapi-google-trends

description: Google Trends 趋势分析 google-trends:透传 serpapi 搜关键词热度趋势(时间序列/地区/相关查询)。适合 SEO 趋势、市场热度、关键词调研。 支持统一处理流程。

---

⚠️ chat 模式使用须知(重要)

本 skill 的真实能力依赖平台后端工具。在网页 / chat 端点下,这些工具可能不可用:

此时**请勿轻信**,请改用 **agent / CLI 路径**运行本 skill 以获取真实结果。任何路径下都**严禁谎称「已调用 / 已搜索完成」而实际未执行**。

Google Trends 趋势分析(serpapi-google-trends)

调 AIMS 平台 serpapi 官方 API(透传到 google_trends 引擎),返回关键词搜索趋势。支持地区(`--gl`)/语言(`--hl`)/位置(`--location`)过滤、返回条数控制、分页。

典型使用场景

**场景 1:SEO 选题** —— 搜"iphone" 看搜索趋势,做内容日历

**场景 2:竞品热度对比** —— 对比"产品A vs 产品B"搜索热度

**场景 3:行业调研** —— 看某品类在多国的搜索热度差

适用人群

| 角色 | 典型用途 |

|------|----------|

| 外贸业务员 | 关键词搜索趋势做客户调研 |

| 市场调研员 | 关键词搜索趋势 |

| 数据分析师 | 关键词搜索趋势做数据采集 |

| 销售 / 商务 | 关键词搜索趋势做竞品分析 |

完整数据示例(实测)

python scripts/google_trends.py --q "搜索词" [--num 10] [--gl cn] [--hl zh-CN]

返回示例:

{"ok": true, "engine": "google_trends", "result": {... 完整 google_trends 响应 ...}}

为什么选 serpapi-google-trends

触发条件

用户说 "搜索趋势 / 热度调研 / 关键词趋势" 时触发。

SEO 关键词

本 skill 覆盖以下搜索意图(9 个长尾词):

google trends, 谷歌趋势, 搜索趋势, 关键词趋势, 热度调研, 市场调研, SEO 趋势, 关键词热度, 趋势对比

<!-- ===== 以下为内嵌脚本代码(agent 安装时按需落盘为 scripts/<name> 并 chmod +x) ===== -->

文件:scripts/google_trends.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""serpapi Google Trends 引擎搜索(google_trends)。

用法:
  python scripts/serpapi_google_trends.py --q "搜索词" [--num 10] [--page 1]
                                  [--gl us] [--hl en] [--location "Austin, Texas"]
                                  [--api-key aims_sk_xxx]
"""
import argparse
import json
import sys
from pathlib import Path

# _lib 查找(2026-09-22 修复):优先包内 _lib/(发布包已随附),
# 退回开发布局 office-skills/_lib —— 否则装到用户侧会 ModuleNotFoundError。
for _lib_cand in (Path(__file__).resolve().parent.parent / "_lib",
                  Path(__file__).resolve().parent.parent.parent / "_lib"):
    if _lib_cand.is_dir():
        sys.path.insert(0, str(_lib_cand))
        break
else:
    raise RuntimeError(
        "找不到 _lib/(需要 aims_functional_api.py)。"
        "发布包应自带 _lib/;开发环境下请确认 office-skills/_lib 存在。"
    )
from aims_functional_api import estimate_cost, serpapi_search


def main():
    ap = argparse.ArgumentParser(description="serpapi Google Trends 引擎搜索")
    ap.add_argument("--q", help="搜索词")
    ap.add_argument("--num", type=int, default=10, help="返回条数,默认 10")
    ap.add_argument("--page", type=int, default=1, help="页码,默认 1")
    ap.add_argument("--gl", help="地区代码(us / cn / uk ...)")
    ap.add_argument("--hl", help="语言代码(en / zh-CN ...)")
    ap.add_argument("--location", help="位置(如 'Austin, Texas')")
    ap.add_argument("--api-key", default=None)
    ap.add_argument("--estimate", action="store_true",
                    help="只报预估费用,不调用上游、不扣费(免费)")
    ap.add_argument("--approved", action="store_true",
                help="用户已确认费用后才允许调用付费接口(必须)")
    args = ap.parse_args()

    # inject_estimate:estimate-flag
    if args.estimate:
        _est = estimate_cost("serpapi/google_trends", units=args.num,
                             api_key=args.api_key)
        print(json.dumps(_est, ensure_ascii=False, indent=2))
        sys.exit(0 if _est.get('ok') else 1)

    try:
        result = serpapi_search(
            engine="google_trends", q=args.q, num=args.num, page=args.page,
            gl=args.gl, hl=args.hl, location=args.location, api_key=args.api_key, confirm=args.approved,
        )
        print(json.dumps({"ok": True, "engine": "google_trends", "result": result}, ensure_ascii=False, indent=2))
    except Exception as e:
        # needs-confirmation:structured-payload
        # 平台未确认付费调用(-32006)→ NeedsConfirmation。
        # 必须原样吐结构化载荷:needs_confirmation / estimated_cost_yuan
        # / cost_basis 要能被上层机读,不能拍平成一句错误文本。
        # exit 3 = 待用户确认(0=成功 / 1=失败 / 3=待确认)。
        if hasattr(e, "to_dict") and hasattr(e, "estimated_cost_yuan"):
            print(json.dumps(e.to_dict(), ensure_ascii=False, indent=2))
            sys.exit(3)
        print(json.dumps({"ok": False, "error": str(e)}, ensure_ascii=False))
        sys.exit(1)


if __name__ == "__main__":
    main()

<!-- ===== 以下为共享依赖 _lib(落盘为 _lib/<name>,与 scripts/ 同级上层) ===== -->

文件:_lib/aims_functional_api.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AIMS 平台功能型 API 公共调用 helper(付费 skill 共用)。

能力:
  - call_functional_api(resource_id, arguments)  统一调用平台托管功能型 API
  - needs_confirm → 抛出 NeedsConfirmation(结构化,带真实报价)
  - estimate_cost(resource_id, units)            免费报价(不调上游,0 花费)

协议(2026-09-22 platform-paid-confirm-protocol):
  付费工具默认 **confirm=False**(安全默认)。平台返回 -32006 时不扣费,
  本模块把它翻译成 NeedsConfirmation 异常(带 estimated_cost_yuan),
  而不是笼统的 RuntimeError——这样 agent 能把真实报价展示给用户,
  用户确认后加 --approved 重试。

环境:依赖 AIMS_API_KEY 环境变量或 --api-key
"""
import argparse
import json
import os
import time
import urllib.request

AIMS_URL = "https://aimsgateway.cn/mcp/"

# 内部源名 → 对外目录名(与平台 application/services/public_naming.py 的
# PUBLIC_SOURCES 对齐;未登记的源原样透出)。estimate 用它把内部 resource_id
# 映射成 list_functional_apis 返回的对外 id。
_EXTERNALIZE = {"serpapi": "web", "hunter": "email", "jev": "decision", "apis": "public-api"}


class NeedsConfirmation(RuntimeError):
    """付费工具未确认 —— 平台返回 -32006 / requires_confirmation。

    仍未扣费。调用方应把 estimated_cost_yuan 展示给用户,
    用户同意后带 confirm=True 重试。

    继承 RuntimeError 是为了向后兼容既有 ``except RuntimeError`` 调用方。
    """

    def __init__(self, resource_id, estimated_cost_yuan=0.0, basis="", raw=None, hint=""):
        self.resource_id = resource_id
        self.estimated_cost_yuan = float(estimated_cost_yuan or 0.0)
        self.basis = basis or ""
        self.raw = raw if isinstance(raw, dict) else {}
        self.hint = hint or ""
        super().__init__(
            f"付费工具需确认: {resource_id} 约 ¥{self.estimated_cost_yuan:.2f} "
            f"(价格依据: {self.basis or 'unknown'})。"
            f"请把该报价展示给用户;确认后加 --approved 重试。未确认不会扣费。"
        )

    def to_dict(self):
        """给 CLI 输出的结构化载荷(agent 可直接机读)。"""
        return {
            "ok": False,
            "needs_confirmation": True,
            "resource_id": self.resource_id,
            "estimated_cost_yuan": self.estimated_cost_yuan,
            "cost_basis": self.basis or "unknown",
            "hint": self.hint or "把费用展示给用户;用户确认后加 --approved 重试",
        }


def _external_rid(resource_id):
    """内部 resource_id → 对外目录 id。serpapi/google → web/google"""
    src, _, rest = (resource_id or "").strip().partition("/")
    ext = _EXTERNALIZE.get(src, src)
    return f"{ext}/{rest}" if rest else ext


def _maybe_needs_confirmation(resource_id, parsed):
    """把平台的 -32006 载荷翻译成 NeedsConfirmation;不是则返回 None。

    兼容三种形态:
      A {"error": {"code": -32006, "data": {...}}}   平台 JSON-RPC 包装
      B {"code": -32006, "data": {...}}              已解包的 error 对象
      C {"requires_confirmation": true, ...}         直接是 data
    """
    if not isinstance(parsed, dict):
        return None

    err = parsed.get("error")
    if isinstance(err, dict) and err.get("code") == -32006:
        d = err.get("data") if isinstance(err.get("data"), dict) else {}
        return NeedsConfirmation(resource_id, d.get("estimated_cost_yuan"),
                                 d.get("cost_basis", ""), err, d.get("hint", ""))

    if parsed.get("code") == -32006:
        d = parsed.get("data") if isinstance(parsed.get("data"), dict) else {}
        return NeedsConfirmation(resource_id, d.get("estimated_cost_yuan"),
                                 d.get("cost_basis", ""), parsed, d.get("hint", ""))

    if parsed.get("requires_confirmation") is True:
        return NeedsConfirmation(resource_id, parsed.get("estimated_cost_yuan"),
                                 parsed.get("cost_basis", ""), parsed, parsed.get("hint", ""))

    return None


def raise_if_needs_confirmation(resource_id, parsed):
    """载荷是 -32006 时抛 NeedsConfirmation,否则原样返回 parsed。

    给自建 _rpc_call 的 skill 复用(它们拿到 isError 载荷后调这个,
    就能和走本模块的 skill 有同一套结构化确认语义)。
    """
    nc = _maybe_needs_confirmation(resource_id, parsed)
    if nc is not None:
        raise nc
    return parsed


# ---------- 鉴权 & 协议 ----------
def _get_key(api_key=None):
    key = api_key or os.environ.get("AIMS_API_KEY")
    if not key:
        raise RuntimeError(
            "缺少 AIMS API Key:请设置环境变量 AIMS_API_KEY,或调用方传 --api-key"
        )
    return key


def _rpc(url, key, method, params, mid, tries=3, timeout=120):
    body = json.dumps({"jsonrpc": "2.0", "id": mid, "method": method, "params": params}).encode()
    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {key}"}
    last = None
    for _ in range(tries):
        try:
            req = urllib.request.Request(url, data=body, method="POST", headers=headers)
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read().decode())
        except Exception as e:  # noqa: BLE001
            last = e
            time.sleep(2)
    raise RuntimeError(f"MCP 调用失败: {last}")


def _handshake(key):
    _rpc(AIMS_URL, key, "initialize",
         {"protocolVersion": "2025-03-26", "capabilities": {},
          "clientInfo": {"name": "office-skills-func-api", "version": "1.0"}}, 1)
    try:
        _rpc(AIMS_URL, key, "notifications/initialized", {}, 2)
    except Exception:
        pass


# ---------- 功能型 API 调用 ----------
def call_functional_api(resource_id, arguments=None, api_key=None, mid=3, confirm=False):
    """调 AIMS 平台的功能型 API。

    Args:
        resource_id: 资源 ID,9 个可选值:
            - hunter/account
            - hunter/domain-search
            - hunter/email-finder
            - hunter/email-verifier
            - serpapi/account
            - serpapi/{engine}
            - apis/catalog
            - apis/{slug}
            - apis/{slug}/{path}
        arguments: dict,参数键值对(按上游 API 的 params 字段说明)
        api_key: 可选 Bearer Token(默认读 env)
        confirm: True 时附 confirm:true,平台放行付费工具;False 时平台返回
            -32006 / requires_confirmation,未付费不扣费(默认 False,安全默认)

    返回 dict(平台直接返回上游响应 + 末尾 `_aimschina` 元数据)
    抛出 RuntimeError 当 isError=True
    """
    key = _get_key(api_key)
    _handshake(key)
    args = dict(arguments or {})
    if confirm:
        args["confirm"] = True
    resp = _rpc(AIMS_URL, key, "tools/call",
                {"name": "aims.call_functional_api",
                 "arguments": {"resource_id": resource_id, "arguments": args}}, mid)
    is_err = resp.get("result", {}).get("isError")
    text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
    parsed = json.loads(text)
    if is_err:
        _nc = _maybe_needs_confirmation(resource_id, parsed)
        if _nc is not None:
            raise _nc
        raise RuntimeError(f"{resource_id} 错误: {parsed}")
    return parsed


# ---------- 9 个快捷封装 ----------
def hunter_account(api_key=None, confirm=False):
    """hunter 账户与配额(免费)。"""
    return call_functional_api("hunter/account", {}, api_key=api_key, confirm=confirm)


def hunter_domain_search(domain, limit=10, offset=0, type=None,
                         seniority=None, department=None, api_key=None, confirm=False):
    """按域名搜邮箱。返回 {"domain":..., "emails":[{value,type,confidence,position,...}], "_aimschina":{cost_yuan,...}}"""
    args = {"domain": domain, "limit": str(limit)}
    if offset:
        args["offset"] = str(offset)
    if type:
        args["type"] = type
    if seniority:
        args["seniority"] = seniority
    if department:
        args["department"] = department
    return call_functional_api("hunter/domain-search", args, api_key=api_key, confirm=confirm)


def hunter_email_finder(domain, full_name=None, first_name=None, last_name=None,
                        max_duration=10, api_key=None, confirm=False):
    """按人名 + 域名推断邮箱。"""
    args = {"domain": domain, "max_duration": str(max_duration)}
    if full_name:
        args["full_name"] = full_name
    elif first_name and last_name:
        args["first_name"] = first_name
        args["last_name"] = last_name
    return call_functional_api("hunter/email-finder", args, api_key=api_key, confirm=confirm)


def hunter_email_verifier(email, api_key=None, confirm=False):
    """验证邮箱是否可投递。返回 {"status": "valid"|"invalid"|"accept_all"|"webmail"|"disposable"|"unknown", ...}"""
    return call_functional_api("hunter/email-verifier", {"email": email}, api_key=api_key, confirm=confirm)


def serpapi_account(api_key=None, confirm=False):
    """serpapi 账户与配额(免费)。"""
    return call_functional_api("serpapi/account", {}, api_key=api_key, confirm=confirm)


def serpapi_search(engine, q=None, num=10, page=1, gl=None, hl=None,
                   location=None, api_key=None, confirm=False):
    """透传到任意 serpapi 引擎(google / google_maps / google_shopping 等)。

    engine 必填,例如 "google_maps" 拿 POI、"google" 拿网页搜索结果、"google_shopping" 拿商品。
    实际调 serpapi.engine 工具(不是走 functional_api 路由)。

    confirm=True 时附 confirm:true 放行付费工具;默认 False 平台返回 -32006 不扣费。
    """
    args = {"engine": engine, "num": str(num), "page": str(page)}
    if q:
        args["q"] = q
    if gl:
        args["gl"] = gl
    if hl:
        args["hl"] = hl
    if location:
        args["location"] = location
    if confirm:
        args["confirm"] = True
    key = _get_key(api_key)
    _handshake(key)
    resp = _rpc(AIMS_URL, key, "tools/call",
                {"name": "serpapi.engine", "arguments": args}, 3)
    is_err = resp.get("result", {}).get("isError")
    text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
    parsed = json.loads(text)
    if is_err:
        _nc = _maybe_needs_confirmation("serpapi/" + str(engine or ""), parsed)
        if _nc is not None:
            raise _nc
        raise RuntimeError(f"serpapi.engine({engine}) 错误: {parsed}")
    return parsed


def apis_catalog(api_key=None):
    """列出所有 apis 目录(450+ 免密钥公共 API)。"""
    return call_functional_api("apis/catalog", {}, api_key=api_key)


def apis_slug(slug, api_key=None):
    """调 apis/{slug} 顶层端点(GET)。"""
    return call_functional_api(f"apis/{slug}", {}, api_key=api_key)


def apis_slug_path(slug, path, method="GET", body=None, params=None, api_key=None):
    """调 apis/{slug}/{path} 任意端点。

    Args:
        slug: 例如 "openweather"
        path: 例如 "data/2.5/weather"
        method: GET / POST / PUT / DELETE
        body: POST/PUT body
        params: query 参数
    """
    args = {"method": method}
    if body is not None:
        args["body"] = body
    if params is not None:
        args["params"] = params
    return call_functional_api(f"apis/{slug}/{path}", args, api_key=api_key)


# ---------- 免费报价 estimate(0 上游花费) ----------
# 本地兜底价:**只登记实测过的资源**(来源:lead-miner install.md §17.4,
# 实测日期 2026-09-17)。平台实时价取不到时才用它,且 cost_basis 会明确标
# local_fallback + price_note 提示可能有偏差——绝不拿它冒充权威报价。
# 没实测过的资源**一律不给兜底价**(宁可 ok=False,也不猜)。
LOCAL_FALLBACK_PRICE_YUAN = {
    "serpapi/google_maps": 0.21,
    "hunter/domain-search": 0.204,
    "hunter/email-verifier": 0.10,
}


def estimate_cost(resource_id, units=1, api_key=None):
    """纯报价:走**免费**的 aims.list_functional_apis 读实时单价,不调上游。

    这是唯一可靠的报价途径——catalog 声明价与实收价实测差 ~18%,
    而 list_functional_apis 返回的是平台已折算的 effective 单价
    (observed 实测价优先,缺失才回落 declared)。

    Args:
        resource_id: 内部 resource_id,如 "serpapi/google" / "hunter/domain-search"
        units: 预计调用次数
        api_key: 可选 Bearer Token(默认读 env)

    Returns:
        dict: {ok, resource_id, external_resource_id, units, unit_cost_yuan,
               cost_basis, total_yuan, upstream_called: False, note}
        查不到价时返回 ok=False(不抛异常——报价失败不该让调用方崩)
    """
    ext = _external_rid(resource_id)
    base = {
        "resource_id": resource_id,
        "external_resource_id": ext,
        "units": int(units or 1),
        "upstream_called": False,
    }

    def _fallback(note):
        """平台价拿不到时用本地实测兜底;没登记的资源保持 ok=False(不猜价)。"""
        unit = LOCAL_FALLBACK_PRICE_YUAN.get(resource_id)
        if unit is None:
            return False
        base.update({
            "ok": True,
            "unit_cost_yuan": round(unit, 4),
            "cost_basis": "local_fallback",
            "billing_unit": "per_call",
            "total_yuan": round(unit * base["units"], 4),
            "price_note": ("本地登记的【实测兜底价】(2026-09-17),非平台实时价,"
                           "实收可能偏差约 ±18%;要准数请配好 AIMS_API_KEY 重跑 estimate。"),
            "note": note,
        })
        return True

    try:
        key = _get_key(api_key)
    except RuntimeError as e:
        if not _fallback("用本地实测兜底价(未触达平台)"):
            base.update({"ok": False, "error": str(e),
                         "note": "estimate 需要 AIMS_API_KEY 才能读到平台实时单价"})
        return base
    try:
        _handshake(key)
        resp = _rpc(AIMS_URL, key, "tools/call",
                    {"name": "aims.list_functional_apis",
                     "arguments": {"limit": 200}}, 7)
        text = resp.get("result", {}).get("content", [{}])[0].get("text", "{}")
        payload = json.loads(text)
    except Exception as e:  # noqa: BLE001
        if not _fallback("用本地实测兜底价(平台单价查询失败)"):
            base.update({"ok": False, "error": f"读取平台单价失败: {e}"})
        return base

    items = payload.get("apis") or []
    hit = None
    for it in items:
        if isinstance(it, dict) and it.get("resource_id") in (ext, resource_id):
            hit = it
            break
    if hit is None:
        if _fallback("平台目录里没有该资源,改用本地实测兜底价"):
            base["not_in_catalog"] = True
            return base
        base.update({
            "ok": False,
            "error": f"平台目录里没找到 {ext}(内部 id: {resource_id})",
            "note": "单价未知——不要凭猜测报给用户;请确认该资源是否已上架/被 chat 策略隐藏",
            "available_count": len(items),
        })
        return base

    unit = float(hit.get("unit_cost_yuan") or 0.0)
    base.update({
        "ok": True,
        "name": hit.get("name") or "",
        "unit_cost_yuan": round(unit, 4),
        "cost_basis": hit.get("price_basis") or "declared",
        "billing_unit": hit.get("billing_unit") or "per_call",
        "total_yuan": round(unit * base["units"], 4),
        "note": "本报价未调用上游、未扣费;用户确认后加 --approved 真实执行",
    })
    return base


def emit_estimate(resource_id, units=1, api_key=None):
    """CLI 用:打印报价 JSON 并以退出码结束(0=有报价 / 1=查不到)。

    在 skill 里这样用(parse_args 之后、真调付费接口之前):
        if args.estimate:
            emit_estimate("serpapi/google")
    """
    est = estimate_cost(resource_id, units=units, api_key=api_key)
    print(json.dumps(est, ensure_ascii=False, indent=2))
    raise SystemExit(0 if est.get("ok") else 1)


def add_estimate_flag(parser):
    """给 skill 的 argparse 统一加 --estimate(免费报价,不调上游)。"""
    parser.add_argument(
        "--estimate", action="store_true",
        help="只报预估费用,不调用上游、不扣费(免费)",
    )
    return parser


# ---------- 列出当前所有可用 resource_id ----------
KNOWN_RESOURCES = [
    "hunter/account",
    "hunter/domain-search",
    "hunter/email-finder",
    "hunter/email-verifier",
    "serpapi/account",
    "serpapi/{engine}",
    "apis/catalog",
    "apis/{slug}",
    "apis/{slug}/{path}",
]


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(description="AIMS 功能型 API helper 自检")
    ap.add_argument("--api-key", default=None)
    ap.add_argument("--resource", default="hunter/account", help=f"资源 ID,已知: {KNOWN_RESOURCES}")
    ap.add_argument("--args", default="{}", help="JSON 字符串参数")
    args = ap.parse_args()

    print(f"=== call_functional_api({args.resource}) ===")
    parsed_args = json.loads(args.args)
    result = call_functional_api(args.resource, parsed_args, api_key=args.api_key)
    print(json.dumps(result, ensure_ascii=False, indent=2)[:2000])