跳转到正文
Social2api

AI 接入 让 OpenAI GPT 调用 Social2api 搜索小红书

让 OpenAI GPT 调用 Social2api 搜索小红书

用 OpenAI Responses API 声明一个小红书搜索函数。GPT 返回工具参数,Python 请求 Social2api,再把样例笔记交给 GPT 整理。

准备这些输入

  1. Python 3.10+ 和可用的 OPENAI_API_KEY。
  2. 默认示例使用 GPT-6.2 Sol,可通过 OPENAI_MODEL 替换。

操作步骤

  1. 安装 SDK 并保存示例

    执行 python -m pip install -U openai,把下方代码保存为 openai_social.py,确保 OPENAI_API_KEY 已加载到本机环境。

  2. 完成一次工具调用

    执行 python openai_social.py。第一轮模型输出函数名和 query;程序固定检索三条合成笔记。

  3. 把证据交回模型

    用 call_id 关联工具结果,核对 rows 和 warnings。第二轮模型根据工具结果组织答复。

运行免费示例

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

curl -fsS https://social2api.com/api/run \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "task": "rednote",
  "mode": "demo",
  "params": {
    "query": "露营收纳",
    "limit": 3
  }
}
JSON

openai_social.py

import json
import os
from urllib.request import Request, urlopen
from openai import OpenAI

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 = OpenAI()
model = os.environ.get("OPENAI_MODEL", "gpt-6.2-sol")
instructions = "只根据工具返回回答。mode=demo 时首先标明是合成样例;mode=live 时报告数据源、实际调用数和 warnings。缺失字段留空,禁止补造来源链接。"
tool = {"type": "function", "strict": True, **json.loads("{\"name\":\"search_rednote\",\"description\":\"Run one Social2api synthetic REDnote keyword search.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\"}},\"required\":[\"query\"],\"additionalProperties\":false}}")}

first = client.responses.create(
    model=model, instructions=instructions,
    input="使用工具查询小红书的露营收纳,把结果整理成三行表格。",
    tools=[tool], tool_choice="required", parallel_tool_calls=False,
)
calls = [item for item in first.output if item.type == "function_call"]
if len(calls) != 1 or calls[0].name != tool["name"]:
    raise RuntimeError("Expected one Social2api tool call")
call = calls[0]
query = checked_text(json.loads(call.arguments)["query"], 120)
output = run_social2api("rednote", {"query": query, "limit": 3})

answer = client.responses.create(
    model=model, instructions=instructions, previous_response_id=first.id,
    input=[{"type": "function_call_output", "call_id": call.call_id,
            "output": json.dumps(output, ensure_ascii=False)}],
)
print(answer.output_text)

可以拿到什么

  1. query 模型提取的关键词
  2. rows 样例笔记
  3. warnings 样例说明
  4. requestCount 上游请求次数

适用范围与限制

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

常见问题

需要把 Social2api 密钥作为模型函数参数吗?

示例使用免费的 demo,无需 Social2api Key。改用 live 时,在可信服务端将 Key 放进 Social2api 请求的 Authorization 头。

模型返回了文本却没有 tool call 怎么排查?

确认你使用的是支持函数调用的模型,并检查第一轮是否传入 tools 和 tool_choice。执行函数前始终验证返回的工具名。

接口文档

参考来源

打开 HTTP API 文档