ソーシャルモニターエージェントの構築(OpenAI SDK)

PythonでDouyinとWeiboのブランドモニターを構築:requestsがSandBase公開データAPIを呼び出し、OpenAI SDKがツール呼び出しと感情アラートを実行します。

ソーシャルモニターエージェントの構築(OpenAI SDK)のカバー画像

TL;DR — Python で動作するソーシャルモニタリングエージェント(最小限のスニペットではなく、約340行のリファレンス実装)。requests を使って POST /v1/api/<endpoint> の SandBase パブリックデータ API を呼び出し、LLM のツール呼び出しには OpenAI SDK を使用します。指定したキーワードで Douyin と Weibo を検索し、LLM に感情評価を求め、LLM がフラグを立てた場合、または報告されたネガティブ比率がしきい値を超えた場合にアラートを発します。2026-10-01 (UTC) にテスト済み。

何を作るか

ソーシャルモニタリングエージェントで、以下を行います:

  1. 指定したキーワードの言及を Douyin と Weibo で定期的に検索する
  2. LLM を使って結果を読み、感情と緊急度を評価する
  3. LLM がフラグを立てた場合、または報告されたネガティブ比率が ALERT_THRESHOLD_NEGATIVE を超えた場合に、構造化されたアラートを生成する
  4. データ API には 直接 HTTP リクエスト を、LLM の推論には OpenAI SDK を使用する

ボリュームの急増は検出しません。各検索は結果の1ページのみを読むため、サイクルごとの結果件数はボリュームの指標にはなりません。それに必要なものについては Add trend comparison を参照してください。

なぜこの2クライアント構成なのか

SandBase は各プラットフォームのデータ API をそれぞれ独自のルート POST https://api.sandbase.ai/v1/api/<vendor>/<path> として公開しており、JSON ボディにはそのエンドポイントのパラメータのみを含みます。LLM は OpenAI 互換の chat completions エンドポイントを経由します。したがって:

  • データ取得には requests(各エンドポイントは構造化 JSON を同期的に返す)
  • LLM の推論には OpenAI SDK(ツール呼び出し付き chat completions)
  • 両方に 1つの API キー(同じ SandBase Authorization: Bearer ヘッダー)

この記事で使うデータ

ここで扱うものはすべて公開された読み取り専用データです。Douyin と Weibo で誰でも見られる検索結果と公開コメントです。SandBase の API キーが必要です。SandBase は Douyin や Weibo の公式パートナーではなく、このエージェントはプライベートアカウントのデータ、DM、オーナー専用のアナリティクスを読むことはできず、投稿やアカウント操作を行うこともできません。

このチュートリアル(SandBase パブリックデータ API)公式開発者プラットフォーム(Douyin Open Platform、Weibo Open Platform)
アクセスSandBase API キー1つアプリ登録とプラットフォーム審査
スコープ公開コンテンツ: キーワード検索、公開コメントアプリへのアクセスを許可したアカウントに対する、認可済みのアカウント連携ワークフロー
アカウント操作(投稿、返信、DM)なしプラットフォームが権限を付与する場合
オーナーアナリティクスなし認可済みアカウント向け
選ぶべきケースキーワードに関する公開の会話をプラットフォーム横断で監視したい自分が管理するアカウントに対して操作を行いたい、またはそのプライベートデータを読みたい

どちらのプラットフォームも、任意の公開データに対する汎用の未認証 API を提供していません。このアプローチはそのギャップを埋めるものです。

前提条件

Shell
pip install openai requests pydantic

SandBase API キーと、以下へのアクセスが必要です:

LLM クライアントは SandBase の OpenAI 互換 POST /v1/chat/completions エンドポイントを使用します。詳細は Chat Completions guide に記載されており、モデル ID はプロバイダーのプレフィックスを保持します(openai/gpt-4.1-mini)。2026-10-01 (UTC) 時点で、model: "openai/gpt-4.1-mini" と1つの tools 定義を含むリクエストをこのエンドポイントに送ると、HTTP 200 と finish_reason: "tool_calls"、および tool_calls エントリが返されました。

コード内のすべてのデータ呼び出しのエンドポイントリファレンス:

以下の Douyin 検索リファレンスが、execute_tool のリクエストボディの出典です: POST /v1/api/douyin/search/general-search-v2 ルートで、任意フィールドに keyword、cursor、backtrace があります。

douyin/search/general-search-v2 の SandBase エンドポイントリファレンス。POST ルート、リクエストボディのフィールド、完了時のレスポンス形状を示す

Caption: douyin/search/general-search-v2 エンドポイントリファレンス。POST ルート、backtrace、cursor、keyword フィールド、およびヘルパーが読み取る outputs[0].data レスポンス形状を示す(2026-10-02 取得)。

完全なエージェント

Python
"""
Social Media Monitor Agent — OpenAI SDK + Direct HTTP Pattern
Monitors Douyin and Weibo for brand mentions, analyzes sentiment.
Uses requests for SandBase data APIs + OpenAI SDK for LLM reasoning.
"""

import json
import os
import time
from collections import deque
from datetime import datetime
import requests
from openai import OpenAI
from pydantic import BaseModel

# --- Configuration ---
SANDBASE_API_KEY = os.environ["SANDBASE_API_KEY"]
API_BASE = "https://api.sandbase.ai/v1/api"
MONITOR_KEYWORDS = ["你的品牌", "YourBrand", "品牌产品名"]
CHECK_INTERVAL_SECONDS = 900      # 15 minutes
ALERT_THRESHOLD_NEGATIVE = 30     # alert if the LLM reports >30% negative
MAX_ITERATIONS = 4                # tool-use LLM calls per keyword (upper bound)
MAX_DATA_CALLS_PER_KEYWORD = 4    # data API calls per keyword (upper bound)
MAX_RETRIES = 3

# --- Client Setup ---
HEADERS = {
    "Authorization": f"Bearer {SANDBASE_API_KEY}",
    "Content-Type": "application/json",
}

# OpenAI SDK client for LLM reasoning only
client = OpenAI(
    base_url="https://api.sandbase.ai/v1",
    api_key=SANDBASE_API_KEY,
)

# --- Data Models ---
class Alert(BaseModel):
    timestamp: str
    severity: str  # "low", "medium", "high", "critical"
    keyword: str
    platform: str
    reason: str
    details: str

# --- Rate limiting (client-side pacing you choose, not a documented SandBase limit) ---
class RateLimiter:
    def __init__(self, max_calls: int, window_seconds: float):
        self.max_calls = max_calls
        self.window = window_seconds
        self.calls = deque()

    def wait(self):
        now = time.monotonic()
        while self.calls and self.calls[0] <= now - self.window:
            self.calls.popleft()
        if len(self.calls) >= self.max_calls:
            time.sleep(self.calls[0] + self.window - now)
        self.calls.append(time.monotonic())

limiter = RateLimiter(max_calls=30, window_seconds=60)

# --- Tool name -> SandBase endpoint ---
TOOL_ENDPOINTS = {
    "search_douyin_content": "douyin/search/general-search-v2",
    "search_weibo_topics": "weibo/web-v2/realtime-search",
    "get_douyin_video_comments": "douyin/web/video-comments",
}

# --- Tool Definitions ---
tools = [
    {
        "type": "function",
        "function": {
            "name": "search_douyin_content",
            "description": "Search Douyin for videos matching a keyword. Returns recent videos with engagement metrics.",
            "parameters": {
                "type": "object",
                "properties": {
                    "keyword": {"type": "string", "description": "Search keyword"},
                    "count": {"type": "integer", "description": "Number of results to return (max 20)", "default": 10}
                },
                "required": ["keyword"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_weibo_topics",
            "description": "Search Weibo for recent posts matching a keyword. Returns posts with engagement data.",
            "parameters": {
                "type": "object",
                "properties": {
                    "keyword": {"type": "string", "description": "Search keyword"},
                    "count": {"type": "integer", "description": "Number of results to return (max 20)", "default": 10}
                },
                "required": ["keyword"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_douyin_video_comments",
            "description": "Get public comments on a specific Douyin video for sentiment analysis.",
            "parameters": {
                "type": "object",
                "properties": {
                    "video_id": {"type": "string", "description": "Douyin video ID (video_id from search_douyin_content)"},
                    "count": {"type": "integer", "description": "Number of comments to return (max 20)", "default": 20}
                },
                "required": ["video_id"]
            }
        }
    }
]

# --- Data API call: POST /v1/api/<endpoint>, read outputs[0].data ---
def call_data_api(endpoint: str, params: dict) -> dict:
    """Rate-limited call with retry/backoff on network errors, HTTP 429 and 5xx."""
    last_error = None
    for attempt in range(MAX_RETRIES):
        limiter.wait()
        try:
            resp = requests.post(f"{API_BASE}/{endpoint}", headers=HEADERS, json=params, timeout=90)
        except (requests.ConnectionError, requests.Timeout) as e:
            last_error = e
        else:
            if resp.status_code != 429 and resp.status_code < 500:
                resp.raise_for_status()  # other 4xx (bad params, bad key): retrying won't help
                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')}")
                return outputs[0].get("data") or {}
            last_error = RuntimeError(f"HTTP {resp.status_code} from {endpoint}")
        if attempt < MAX_RETRIES - 1:
            time.sleep(2 ** attempt)  # 1s, 2s
    raise RuntimeError(f"{endpoint} failed after {MAX_RETRIES} attempts: {last_error}")

def execute_tool(tool_name: str, arguments: dict) -> str:
    """Route a tool call to its SandBase endpoint.
    Raw responses are large, so each tool returns a compact list for the LLM."""
    count = min(int(arguments.get("count", 10)), 20)
    endpoint = TOOL_ENDPOINTS.get(tool_name)
    if endpoint is None:
        return json.dumps({"error": f"Unknown tool: {tool_name}"})

    if tool_name == "search_douyin_content":
        data = call_data_api(endpoint, {"keyword": arguments["keyword"], "cursor": 0, "sort_type": "0"})
        items = []
        for card in data.get("business_data") or []:
            aweme = (card.get("data") or {}).get("aweme_info")
            if not aweme:
                continue  # skip related-search cards etc.
            stats = aweme.get("statistics") or {}
            items.append({
                "video_id": aweme.get("aweme_id"),
                "desc": aweme.get("desc"),
                "author": (aweme.get("author") or {}).get("nickname"),
                "likes": stats.get("digg_count"),
                "comments": stats.get("comment_count"),
                "shares": stats.get("share_count"),
            })
        return json.dumps(items[:count], ensure_ascii=False)

    if tool_name == "search_weibo_topics":
        data = call_data_api(endpoint, {"query": arguments["keyword"], "page": 1})
        posts = []
        for p in (data.get("parsed_data") or {}).get("results") or []:
            inter = p.get("interaction") or {}
            posts.append({
                "weibo_id": p.get("weibo_id"),
                "user": p.get("user_name"),
                "content": p.get("content"),
                "publish_time": p.get("publish_time"),
                "reposts": inter.get("repost_count"),
                "comments": inter.get("comment_count"),
                "likes": inter.get("like_count"),
            })
        return json.dumps(posts[:count], ensure_ascii=False)

    # get_douyin_video_comments
    data = call_data_api(endpoint, {"aweme_id": arguments["video_id"], "cursor": 0, "count": 20})
    comments = [
        {"text": c.get("text"), "likes": c.get("digg_count"), "replies": c.get("reply_comment_total")}
        for c in data.get("comments") or []
    ]
    return json.dumps(comments[:count], ensure_ascii=False)

# --- Agent Loop ---
def run_monitoring_cycle(keywords: list[str]) -> list[Alert]:
    """Run one monitoring cycle: search, analyze, alert."""
    alerts = []

    for keyword in keywords:
        # Step 1: Ask the agent to monitor this keyword
        messages = [
            {
                "role": "system",
                "content": """You are a social media monitoring agent. For each keyword:
1. Search both Douyin and Weibo for recent mentions
2. Analyze the sentiment of the results
3. Identify any urgent items (complaints, crises, viral negative content)
4. Produce a structured assessment

Be concise. Focus on actionable signals, not summaries of neutral content.
If engagement is unusually high on negative content, flag it immediately."""
            },
            {
                "role": "user",
                "content": f"Monitor keyword: '{keyword}'. Search both platforms and provide sentiment analysis."
            }
        ]

        # Step 2: Agent reasons and calls tools (both loops are capped)
        data_calls = 0
        for _ in range(MAX_ITERATIONS):
            response = client.chat.completions.create(
                model="openai/gpt-4.1-mini",
                messages=messages,
                tools=tools,
                tool_choice="auto"
            )
            message = response.choices[0].message
            messages.append(message)

            # If no tool calls, agent is done reasoning
            if not message.tool_calls:
                break

            # Every tool call needs a tool message, even when it is refused or fails
            for tool_call in message.tool_calls:
                if data_calls >= MAX_DATA_CALLS_PER_KEYWORD:
                    result = json.dumps({"error": "data call budget for this keyword is used up; answer with what you have"})
                else:
                    data_calls += 1
                    try:
                        arguments = json.loads(tool_call.function.arguments)
                        result = execute_tool(tool_call.function.name, arguments)
                    except Exception as e:
                        result = json.dumps({"error": str(e), "tool": tool_call.function.name})
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": result
                })

        # Step 3: Extract structured assessment
        assessment_prompt = messages + [{
            "role": "user",
            "content": """Based on your analysis, provide a JSON response with:
{
    "keyword": "the keyword",
    "platforms_checked": ["douyin", "weibo"],
    "total_mentions": <number of results you reviewed>,
    "sentiment": {"positive": <pct>, "neutral": <pct>, "negative": <pct>},
    "alert_needed": true/false,
    "alert_severity": "low|medium|high|critical",
    "alert_reason": "why an alert is needed (or empty)",
    "urgent_items": ["list of specific concerning items"],
    "summary": "one-paragraph summary"
}
Only output the JSON, no markdown."""
        }]

        assessment_response = client.chat.completions.create(
            model="openai/gpt-4.1-mini",
            messages=assessment_prompt
        )

        try:
            assessment = json.loads(assessment_response.choices[0].message.content)
        except json.JSONDecodeError:
            print(f"? {keyword}: assessment was not valid JSON, skipped")
            continue

        # Step 4: Alert if the LLM flags it OR the reported negative share is over the threshold
        try:
            negative_pct = float((assessment.get("sentiment") or {}).get("negative") or 0)
        except (TypeError, ValueError):
            negative_pct = 0.0
        over_threshold = negative_pct > ALERT_THRESHOLD_NEGATIVE

        if assessment.get("alert_needed") or over_threshold:
            reason = assessment.get("alert_reason") or (
                f"{negative_pct:.0f}% negative (threshold {ALERT_THRESHOLD_NEGATIVE}%)")
            alert = Alert(
                timestamp=datetime.now().isoformat(),
                severity=assessment.get("alert_severity") or "medium",
                keyword=keyword,
                platform=", ".join(assessment.get("platforms_checked") or ["douyin", "weibo"]),
                reason=reason,
                details=assessment.get("summary", "")
            )
            alerts.append(alert)
            print(f"🚨 ALERT [{alert.severity.upper()}] — {alert.keyword}: {alert.reason}")
        else:
            print(f"✓ {keyword}: Normal ({assessment.get('total_mentions', 0)} results reviewed, "
                  f"{negative_pct:.0f}% negative, {data_calls} data calls)")

    return alerts

# --- Alert Delivery ---
def deliver_alerts(alerts: list[Alert]):
    """Print alerts. To push them to Slack, POST {"text": ...} to an incoming webhook URL."""
    for alert in alerts:
        if alert.severity in ("high", "critical"):
            print(f"\n{'='*60}")
            print(f"🔴 {alert.severity.upper()} ALERT — {alert.timestamp}")
            print(f"   Keyword: {alert.keyword}")
            print(f"   Platform: {alert.platform}")
            print(f"   Reason: {alert.reason}")
            print(f"   Details: {alert.details}")
            print(f"{'='*60}\n")
        else:
            # Low-priority: log for daily digest
            print(f"📋 [{alert.severity}] {alert.keyword}: {alert.reason}")

# --- Main Loop ---
def main():
    """Run the monitoring agent on a schedule."""
    print("🔍 Social Monitor Agent started")
    print(f"   Keywords: {MONITOR_KEYWORDS}")
    print(f"   Interval: {CHECK_INTERVAL_SECONDS}s")
    print(f"   Alert threshold: >{ALERT_THRESHOLD_NEGATIVE}% negative (LLM-reported)")
    print()

    while True:
        print(f"--- Cycle start: {datetime.now().isoformat()} ---")
        alerts = run_monitoring_cycle(MONITOR_KEYWORDS)

        if alerts:
            deliver_alerts(alerts)
        else:
            print("No alerts this cycle.")

        print(f"--- Next cycle in {CHECK_INTERVAL_SECONDS}s ---\n")
        time.sleep(CHECK_INTERVAL_SECONDS)

if __name__ == "__main__":
    main()

このパターンの仕組み

データ API は直接 HTTP を使い、LLM 呼び出しは OpenAI SDK を使う:

Python
# LLM reasoning — OpenAI SDK (chat completions)
client.chat.completions.create(model="openai/gpt-4.1-mini", messages=...)

# Data retrieval — one route per endpoint, body = only that endpoint's params
requests.post("https://api.sandbase.ai/v1/api/douyin/search/general-search-v2",
    headers=HEADERS,
    json={"keyword": "...", "cursor": 0, "sort_type": "0"})

SandBase のデータ API は LLM ではありません。messages を受け取ったり、chat completions を返したりしません。TOOL_ENDPOINTS は各ツールをそのエンドポイントにマッピングし、call_data_api はそのエンドポイントのパラメータのみを POST します。エンドポイントリファレンスは完了時のレスポンスを {id, status, model, outputs: [{data: ...}]} と記載しているため、ヘルパーは outputs[0].data を読み取り、呼び出しが完了しなかった場合は status と error を付けてエラーを発生させます。これらはエンドポイントリファレンスの Model API POST ルートであり、カタログページに表示される GET ルートではありません。

どちらの検索エンドポイントも結果件数を受け取らないため、ツールはローカルでスライスします。エージェントは最初のページのみを読みます。ページネーションはエンドポイントごとに異なります: Douyin の一般検索は前回のレスポンスから cursor、search_id、backtrace を送り返すことでページングし、Weibo のリアルタイム検索は page の数値を受け取り、動画コメントは cursor を受け取ります。

他の2つのリファレンスはこれらのパラメータを直接示しています: Weibo のリアルタイム検索は query(必須)と page を列挙し、動画コメントは aweme_id(必須)、count(デフォルト 20)、cursor(デフォルト 0)を列挙します。

weibo/web-v2/realtime-search の SandBase エンドポイントリファレンス。POST ルートと page および必須の query フィールドを示す

Caption: weibo/web-v2/realtime-search リファレンス。query が必須で page のデフォルトが 1 であり、エージェントが送る {"query": ..., "page": 1} ボディと一致する(2026-10-02 取得)。

douyin/web/video-comments の SandBase エンドポイントリファレンス。POST ルートと aweme_id、count、cursor フィールドを示す

Caption: douyin/web/video-comments リファレンス。必須の aweme_id に加えて count(デフォルト 20)と cursor(デフォルト 0)を示し、get_douyin_video_comments が送る3つのフィールドである(2026-10-02 取得)。

すべての call_data_api 呼び出しは RateLimiter を待機し(ここでは60秒あたり30回。この数値は独自のペーシングであり、SandBase のクォータではありません)、ネットワークエラー、HTTP 429、5xx を 1s/2s のバックオフでリトライします。ツールのエラーは {"error": ...} として LLM に返されるため、1回の失敗でサイクル全体が停止することはありません。

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

上記のエージェントコード全体を、LLM をスタブ化し、すべてのデータ呼び出しをライブで実行しました。ブランドキーワード 瑞幸咖啡(Luckin Coffee)を使用しました。ツールが読み取るビジネスフィールド名はこれらの呼び出しに由来します。これらは観測されたのみで、文書化された保証ではないため、すべての読み取りで .get() を使用しています。以下ではクリエイター名と投稿テキストを <redacted> に置き換えています。数値は返されたとおりです。

Text
POST https://api.sandbase.ai/v1/api/douyin/search/general-search-v2
{"keyword": "瑞幸咖啡", "cursor": 0, "sort_type": "0"}

{"id": "a7e4f79e-0231-4a05-821f-7db4d4799a76", "status": "completed", "model": "douyin/search/general-search-v2",
 "outputs": [{"data": {"business_data": [{"data": {"aweme_info": {
   "aweme_id": "<redacted>", "desc": "<redacted> #瑞幸 ...",
   "author": {"nickname": "<redacted>"},
   "statistics": {"digg_count": 943163, "comment_count": 12982, "share_count": 215170, ...}}}}, ...]}}]}
Text
POST https://api.sandbase.ai/v1/api/weibo/web-v2/realtime-search
{"query": "瑞幸咖啡", "page": 1}

{"id": "0c118fd2-0dda-4b11-9cad-b2cfe1cccefe", "status": "completed", ...
 "outputs": [{"data": {"parsed_data": {"results": [{
   "weibo_id": "<redacted>", "user_name": "<redacted>", "content": "<redacted>",
   "publish_time": "2分钟前", "interaction": {"comment_count": 0, "like_count": 0, "repost_count": 0}}, ...]}}}]}
Text
POST https://api.sandbase.ai/v1/api/douyin/web/video-comments
{"aweme_id": "<video_id from the search above>", "cursor": 0, "count": 20}

{"id": "a0ed3f3d-0c2f-412b-9159-9bfc91569a5e", "status": "completed", ...
 "outputs": [{"data": {"comments": [{"text": "<redacted>", "digg_count": 18, "reply_comment_total": 2}, ...]}}]}

そのサイクルでは、ツールはスライス前に 17 本の動画、9 件の Weibo 投稿、19 件のコメントを取得しました。2回のテスト実行(EN と ZH のコード)での 28 回のデータ呼び出しのうち、2回が HTTP 503 を返し、リトライで成功しました。これらの実行における生の Douyin 検索ペイロードは 1 MB 近くあったため、ツールはレスポンス全体を LLM のコンテキストに流し込むのではなく、コンパクトなリストを返します。

コスト内訳

データ API 呼び出し: 各組織は UTC 日あたり 100 回の無料データ API 呼び出しを利用でき、それを超えると3つのエンドポイントは呼び出しごとに課金されるため、データ側のコストはおおよそ残りの呼び出し数 × SandBase カタログにおける各エンドポイントの価格です(sandbase inspect で確認してください)。LLM: 2026-10-01 時点の SandBase では、openai/gpt-4.1-mini は入力トークン100万あたり $0.40、出力トークン100万あたり $1.60 です。

キーワードあたりの呼び出し回数はコードによって上限が決まります: ツール使用の LLM 呼び出しが 1 から MAX_ITERATIONS(4)回、評価呼び出しが 1 回、データ呼び出しが 0 から MAX_DATA_CALLS_PER_KEYWORD(4)回です。典型的な経路は、両方のプラットフォームを検索し、1本の動画のコメントを取得し、回答する、という流れで、ツール使用呼び出し 3 回、評価 1 回、データ呼び出し 3 回です。

説明的なトークン仮定による見積もり(ツール使用呼び出しは約 2K 入力 + 500 出力、評価は約 1K 入力 + 200 出力):

Text
Tool-use call:   2,000 × $0.40/M + 500 × $1.60/M = $0.0008 + $0.0008   = $0.0016
Assessment call: 1,000 × $0.40/M + 200 × $1.60/M = $0.0004 + $0.00032  = $0.00072

Per keyword (typical, 3 tool-use + 1 assessment): 3 × $0.0016 + $0.00072 = $0.00552
Per keyword (upper bound, 4 + 1):                 4 × $0.0016 + $0.00072 = $0.00712

Per cycle, 3 keywords:  typical $0.01656   upper bound $0.02136
Data calls per cycle:   typical 9          upper bound 12

15分ごとに実行する場合(1日 96 サイクル、30日の月):

Text
Typical LLM:      $0.01656 × 96 = $1.59/day, × 30 ≈ $47.69/month; plus 864 data calls/day (first 100 free, the rest billed per call)
Upper bound LLM:  $0.02136 × 96 = $2.05/day, × 30 ≈ $61.52/month; plus 1,152 data calls/day (first 100 free, the rest billed per call)

これらは見積もりであり、実測値ではありません。実際の入力トークンは、ツール結果が messages に積み重なるにつれて増加し、評価呼び出しは会話全体を再送するため、数日間 response.usage をログに記録し、自分の数値で計算し直してください。

エージェントの拡張

プラットフォームを追加する

Python
# Add Xiaohongshu monitoring: add to TOOL_ENDPOINTS
#   "search_xiaohongshu_notes": "xiaohongshu/app-v2/search-notes"
# and route it in execute_tool with {"keyword": ..., "page": 1}
{
    "type": "function",
    "function": {
        "name": "search_xiaohongshu_notes",
        "description": "Search Xiaohongshu for notes mentioning a keyword.",
        "parameters": {
            "type": "object",
            "properties": {
                "keyword": {"type": "string"},
                "count": {"type": "integer", "default": 10}
            },
            "required": ["keyword"]
        }
    }
}

2026-10-01 に {"keyword": "瑞幸咖啡", "page": 1} を付けて xiaohongshu/app-v2/search-notes を呼び出したところ、data.items[] の下に 20 件のノートが返されました(1a422dd3-d11a-446b-a0ea-0ba15c3a2a9c を実行、観測のみ)。ツールを追加する際は MAX_DATA_CALLS_PER_KEYWORD を増やすことを忘れないでください。

トレンド比較を追加する

上記のエージェントはサイクルごとにステートレスです。スパイク検出には、それに欠けている2つのものが必要です: ページサイズに左右されないボリュームシグナル(たとえば、まだ見ていない Weibo の weibo_id の数)と、再起動をまたいで永続化される履歴です。ループには組み込まれていない出発点:

Python
# In-memory history; persist it (SQLite, JSON file) for real use
class TrendTracker:
    def __init__(self):
        self.history = {}  # keyword -> [(timestamp, new_posts)]

    def record(self, keyword: str, new_posts: int):
        self.history.setdefault(keyword, []).append((time.time(), new_posts))

    def detect_spike(self, keyword: str, window_hours: int = 24) -> bool:
        """True if the latest count is 3x the average over the window."""
        cutoff = time.time() - (window_hours * 3600)
        recent = [n for t, n in self.history.get(keyword, []) if t > cutoff]
        if len(recent) < 10:
            return False
        avg = sum(recent[:-1]) / len(recent[:-1])
        return avg > 0 and recent[-1] > avg * 3

自動応答ドラフトを追加する

Python
def draft_response(alert: Alert) -> str:
    """Use the LLM to draft a response for a human to review."""
    response = client.chat.completions.create(
        model="openai/gpt-4.1-mini",
        messages=[
            {"role": "system", "content": "You are a brand communications specialist. "
             "Draft a brief, empathetic response to the following social media issue. "
             "Keep it professional, acknowledge the concern, and offer next steps."},
            {"role": "user", "content": f"Issue: {alert.reason}\nDetails: {alert.details}\n"
             "Draft a response suitable for posting on social media."}
        ]
    )
    return response.choices[0].message.content

データ API は読み取り専用であるため、ドラフトの投稿はプラットフォーム独自のツールを通じてチームが行います。

関連記事

主なポイント

  1. 2つのクライアント、1つの API キー。 SandBase データ API には requests を POST /v1/api/<endpoint> で使い、LLM の推論には OpenAI SDK を使い、どちらも同じキーで認証します。
  2. ツール呼び出しが統合パターン。 各ツールを1つのエンドポイントにマッピングし、LLM にいつ呼び出すかを決めさせ、LLM ループとデータ呼び出しの両方に上限を設けます。
  3. outputs[0].data のみを読み、失敗は明示的に。 呼び出しが完了しない場合は、黙って {} を返すのではなくエラーを発生させます。
  4. 両方のコスト行を追跡する。 データエンドポイントは毎日100回の無料呼び出しを超えると呼び出しごとにカタログ価格で課金され、LLM 呼び出しはトークン単位で課金されます。呼び出し回数とトークン使用量をログに記録し、支配的な方を調整してください。
  5. 同期 API はループをシンプルに保つ。 ソーシャルデータ API は同期専用であるため、コールバックやタスク管理はありません。レスポンススキーマには pending と running の状態も記載されていますが、このエージェントは completed 以外をポーリングせずエラーとして扱います。

Get a SandBase API key · Browse the Douyin catalog · Browse the Weibo catalog

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