用 Gemini 比较抖音关键词趋势
让 Gemini 通过 Google Gen AI SDK 调用 Python 函数,把 Social2api 的逐日抖音搜索指数转成可对照的趋势摘要。
准备这些输入
- Python 3.10+ 和可用的 GEMINI_API_KEY。
- 默认使用 Gemini 3.8 Flash,可通过 GEMINI_MODEL 替换。
操作步骤
- 安装 Python SDK
执行 python -m pip install -U google-genai,把代码保存为 gemini_social.py。
- 限制工具范围
把两个关键词作为函数参数,脚本将日期固定在 2026-11-01 到 2026-11-07,最多执行一轮自动工具调用。
- 核对趋势证据
执行 python gemini_social.py。检查调用次数、每个关键词的日期覆盖和峰值日期,搜索指数与综合指数分别解释。
运行免费示例
示例返回合成数据,上游调用次数为 0。先确认字段和流程,再决定是否以账号权限发起实时请求。
curl -fsS https://social2api.com/api/run \
-H 'Content-Type: application/json' \
--data-binary @- <<'JSON'
{
"task": "douyin",
"mode": "demo",
"params": {
"keywords": [
"防晒衣",
"冰袖"
],
"since": "2026-11-01",
"until": "2026-11-07"
}
}
JSONgemini_social.py
import json
import os
from urllib.request import Request, urlopen
from google import genai
from google.genai import types
def run_social2api(task, params):
mode = os.environ.get("SOCIAL2API_MODE", "demo")
if mode not in ("demo", "live"):
raise ValueError("SOCIAL2API_MODE must be demo or live")
payload = {"task": task, "mode": mode, "params": params}
headers = {"Content-Type": "application/json"}
if mode == "live":
if os.environ.get("SOCIAL2API_LIVE_TASK") != task:
raise ValueError("Set SOCIAL2API_LIVE_TASK to opt in to this task")
budget = int(os.environ["SOCIAL2API_MAX_REQUESTS"])
if not 1 <= budget <= 36:
raise ValueError("SOCIAL2API_MAX_REQUESTS must be in 1–36")
payload["maxRequests"] = budget
headers["Authorization"] = "Bearer " + os.environ["SOCIAL2API_API_KEY"]
request = Request(
"https://social2api.com/api/run",
data=json.dumps(payload).encode("utf-8"),
headers=headers,
method="POST",
)
with urlopen(request, timeout=90 if mode == "live" else 15) as response:
result = json.load(response)
if (result["mode"] != mode or (mode == "demo" and result["requestCount"] != 0)
or (mode == "live" and result["requestCount"] > budget)):
raise RuntimeError("Unexpected Social2api mode or usage")
rows = result["rows"][:20]
return {"mode": mode, "provider": result["provider"], "rows": rows,
"returnedRows": len(result["rows"]), "warnings": result["warnings"],
"requestCount": result["requestCount"]}
def checked_text(value, limit):
if not isinstance(value, str) or not 1 <= len(value.strip()) <= limit:
raise ValueError("Invalid tool argument")
return value.strip()
call_count = 0
def get_douyin_trends(first: str, second: str) -> dict:
"""Return synthetic daily Douyin search indices for two keyword labels."""
global call_count
if call_count >= 1:
return {"error": "One Social2api call is allowed in this demo."}
words = [checked_text(first, 40), checked_text(second, 40)]
if words[0] == words[1] or any("," in word or "," in word for word in words):
raise ValueError("Provide two distinct single keyword labels")
call_count += 1
return run_social2api("douyin", {"keywords": words,
"since": "2026-11-01", "until": "2026-11-07"})
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
answer = client.models.generate_content(
model=os.environ.get("GEMINI_MODEL", "gemini-3.8-flash"),
contents="请先调用 get_douyin_trends 比较防晒衣和冰袖,再按日期总结峰值。",
config=types.GenerateContentConfig(
system_instruction="只根据工具返回回答。mode=demo 时首先标明是合成样例;mode=live 时报告数据源、实际调用数和 warnings。缺失字段留空,禁止补造来源链接。",
tools=[get_douyin_trends],
automatic_function_calling=types.AutomaticFunctionCallingConfig(maximum_remote_calls=2),
),
)
if call_count != 1 or not answer.text:
raise RuntimeError("Expected one tool call and a textual answer")
print(answer.text)可以拿到什么
- keyword 关键词
- date 日期
- searchIndex 搜索指数
- combinedIndex 综合指数
适用范围与限制
演示请求使用合成样例,上游请求次数为 0。运行真实取数前,请核对数据源、工具权限和用量限额。
完整 SDK 示例会请求模型厂商,可能产生模型费用;上方 cURL 只请求合成数据。默认保持 demo。需要执行真实查询时,在应用端设 SOCIAL2API_MODE=live、SOCIAL2API_LIVE_TASK 为本页唯一任务、SOCIAL2API_MAX_REQUESTS 为 1–36,并从密钥存储注入含相应任务权限的 SOCIAL2API_API_KEY。不要让模型控制这些设置。
小红书示例的任务是 rednote,视频号是 channels,抖音是 douyin。HTTP 异常应结束本次处理并核对额度,不能向模型提交虚构的取数结果。真实返回为空时保留 warnings、数据源和调用数;模型只接收最多 20 行,returnedRows 显示原始行数。
仅将工具返回作为数据处理。保留来源字段,样例链接缺失时留空,遇到 warnings 或空结果时按原样说明。
常见问题
Gemini 没执行 Python 函数怎么办?
确认安装的是 google-genai,把带类型标注和 docstring 的函数对象传入 tools,并检查模型是否支持函数调用。
可以把空指数补为 0 吗?
保留空值。指数缺失时,比较同一天有数据的关键词,避免将缺失解释成冷门。