# 用 Claude API 归纳视频号评论

[规范网址](https://social2api.com/forai/anthropic/)

用 Claude Messages API 的 tool\_use 与 tool\_result，把 Social2api 返回的视频号评论按作品整理成读得懂的表格。

## Agent 提示词

~~~~text
按「用 Claude API 归纳视频号评论」接入 Social2api。
先确认我提供的输入和目标。先跑免费合成示例，得到真实数据前请不要把样例写成事实。
识别当前客户端或模型的授权方式，使用环境变量保存凭据，并返回一次最小调用的结果与错误排查方法。
https://social2api.com/forai/anthropic/
~~~~

[打开 HTTP API 文档](https://social2api.com/docs/api/run/)

## 准备这些输入

1. Python 3.10+ 和可用的 ANTHROPIC\_API\_KEY。
2. 默认使用 Claude Sonnet 4.6，可通过 ANTHROPIC\_MODEL 替换。

## 操作步骤

1. **准备 Anthropic SDK**。 执行 python -m pip install -U anthropic，将下方代码保存为 claude\_social.py。
2. **解析模型选择的账号**。 执行 python claude\_social.py。Claude 返回 tool\_use，程序读取 account，并将每条视频的评论上限设为 2 条。
3. **关联调用和返回值**。 把原始 assistant 内容块和带 tool\_use\_id 的 user tool\_result 依次发送，再按 videoId 汇总。

## 运行免费示例

示例返回合成数据，上游调用次数为 0。先确认字段和流程，再决定是否以账号权限发起实时请求。

~~~~bash
curl -fsS https://social2api.com/api/run \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "task": "channels",
  "mode": "demo",
  "params": {
    "account": "示例视频号",
    "limit": 2,
    "commentsPerVideo": 2
  }
}
JSON
~~~~

## claude\_social.py

~~~~python
import json
import os
from urllib.request import Request, urlopen
from anthropic import Anthropic

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()

client = Anthropic()
model = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-4-6")
spec = json.loads("{\"name\":\"get_wechat_channels\",\"description\":\"Run one Social2api synthetic WeChat Channels video and comment lookup.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"account\":{\"type\":\"string\"}},\"required\":[\"account\"],\"additionalProperties\":false}}")
tool = {"name": spec["name"], "description": spec["description"],
        "input_schema": spec["parameters"]}
messages = [{"role": "user", "content": "用工具读取示例视频号的评论，按视频 ID 汇总。"}]
first = client.messages.create(
    model=model, max_tokens=800, system="只根据工具返回回答。mode=demo 时首先标明是合成样例；mode=live 时报告数据源、实际调用数和 warnings。缺失字段留空，禁止补造来源链接。",
    messages=messages, tools=[tool],
    tool_choice={"type": "tool", "name": tool["name"], "disable_parallel_tool_use": True},
)
calls = [block for block in first.content if block.type == "tool_use"]
if len(calls) != 1 or calls[0].name != tool["name"]:
    raise RuntimeError("Expected one Social2api tool call")
call = calls[0]
account = checked_text(call.input["account"], 400)
output = run_social2api("channels", {"account": account, "limit": 2, "commentsPerVideo": 2})
messages += [
    {"role": "assistant", "content": first.content},
    {"role": "user", "content": [
        {"type": "tool_result", "tool_use_id": call.id,
         "content": json.dumps(output, ensure_ascii=False)}
    ]},
]
answer = client.messages.create(
    model=model, max_tokens=800, system="只根据工具返回回答。mode=demo 时首先标明是合成样例；mode=live 时报告数据源、实际调用数和 warnings。缺失字段留空，禁止补造来源链接。",
    messages=messages, tools=[tool], tool_choice={"type": "none"},
)
for block in answer.content:
    if block.type == "text":
        print(block.text)
~~~~

## 可以拿到什么

1. videoId 视频 ID
2. title 视频标题
3. commentText 评论内容
4. commentCount 视频评论总数

## 适用范围与限制

演示请求使用合成样例，上游请求次数为 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 或空结果时按原样说明。

## 常见问题

### 为什么同一个视频有多行？

视频号结果可以按评论展开，每条评论一行。比较时用 videoId 聚合，保留 commentCount 和本次采样的评论数。

### Messages API 报 tool\_result 没有关联的调用？

确认上一条是包含原始 tool\_use 的 assistant 消息，随后的 user 消息使用匹配的 tool\_use\_id。

## 接口文档

- [HTTP 取数接口、返回字段与请求预算](https://social2api.com/docs/api/run/)
- [MCP 工具、授权与故障排查](https://social2api.com/docs/api/mcp/)
- [OpenAPI 接口定义](https://social2api.com/openapi.json)
- [创建 Social2api API Key](https://social2api.com/console/api-keys/)

## 参考来源

- [Claude API 工具定义](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools)

## 给 AI 代理

- [给 AI 的站点说明](https://social2api.com/zh/llms.txt)。 面向代理的功能概览与文档发现索引。
- [接入 AI 的步骤](https://social2api.com/zh/agents/)。 从免费试跑到 API Key 与 MCP 接入。
- [接入步骤（Markdown）](https://social2api.com/agents.md)。 接入指南的纯文本 Markdown 版本。
- [OpenAPI](https://social2api.com/openapi.json)。 查看 HTTP 请求参数、认证方式和响应结构。
- [价格表](https://social2api.com/prices.json)。 查看托管积分规则、扩展 API 报价和充值状态。
- [MCP 地址](https://social2api.com/docs/api/mcp/)。 Streamable HTTP 接入、授权方式和工具说明。

MCP Streamable HTTP 地址 `https://social2api.com/mcp`。

## 相关指南和问答

- [用 AI 连接 Social2api](https://social2api.com/forai/)
- [社媒数据解决方案](https://social2api.com/solutions/)
- [让 OpenAI GPT 调用 Social2api 搜索小红书](https://social2api.com/forai/openai/)
- [用 Gemini 比较抖音关键词趋势](https://social2api.com/forai/gemini/)

[打开 HTTP API 文档](https://social2api.com/docs/api/run/)
