소셜 모니터 에이전트 구축하기 (OpenAI SDK)

Python으로 Douyin과 Weibo 브랜드 모니터를 구축하세요: requests가 SandBase 공개 데이터 API를 호출하고, OpenAI SDK가 도구 호출과 감정 알림을 실행합니다.

Build a Social Monitor Agent (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이 플래그를 세우거나 LLM이 보고한 부정 비율이 ALERT_THRESHOLD_NEGATIVE을 넘으면 구조화된 알림을 생성합니다
  4. 데이터 API에는 직접 HTTP 요청을, LLM 추론에는 OpenAI SDK를 사용합니다

볼륨 급증은 감지하지 않습니다. 각 검색은 결과 한 페이지를 읽으므로 사이클당 결과 수는 볼륨 측정치가 아닙니다. 그렇게 하려면 무엇이 필요한지는 추세 비교 추가를 참고하세요.

왜 이 두 클라이언트 패턴인가

SandBase는 각 플랫폼 데이터 API를 자체 라우트 POST https://api.sandbase.ai/v1/api/<vendor>/<path>로 노출하며, JSON 본문에는 해당 엔드포인트의 파라미터만 담깁니다. LLM은 OpenAI 호환 chat completions 엔드포인트를 통해 호출합니다. 따라서:

  • **requests**는 데이터 조회용입니다(각 엔드포인트는 구조화된 JSON을 동기적으로 반환합니다)
  • OpenAI SDK는 LLM 추론용입니다(도구 호출을 사용하는 chat completions)
  • 하나의 API 키로 둘 다 사용합니다(동일한 SandBase Authorization: Bearer 헤더)

어떤 데이터를 사용하는가

여기의 모든 것은 공개, 읽기 전용 데이터입니다. Douyin과 Weibo에서 누구나 볼 수 있는 검색 결과와 공개 댓글입니다. SandBase API 키가 필요합니다. SandBase는 Douyin이나 Weibo의 공식 파트너가 아니며, 이 에이전트는 비공개 계정 데이터, DM, 소유자 전용 분석을 읽을 수 없고, 게시하거나 계정 작업을 수행할 수 없습니다.

이 튜토리얼(SandBase 공개 데이터 API)공식 개발자 플랫폼(Douyin Open Platform, Weibo Open Platform)
접근SandBase API 키 하나앱 등록 및 플랫폼 심사
범위공개 콘텐츠: 키워드 검색, 공개 댓글앱에 접근 권한을 부여한 계정에 대한, 권한이 부여된 계정 연동 워크플로
계정 작업(게시, 답글, DM)아니요플랫폼이 권한을 부여하는 경우
소유자 분석아니요권한이 부여된 계정의 경우
선택 기준키워드에 대한 공개 대화를 여러 플랫폼에서 지켜봐야 할 때관리하는 계정에 대해 작업하거나 비공개 데이터를 읽어야 할 때

어느 플랫폼도 임의의 공개 데이터에 대한 일반적인 비인증 API를 제공하지 않으며, 이 접근 방식이 채우는 것이 바로 그 공백입니다.

사전 요구 사항

Shell
pip install openai requests pydantic

SandBase API 키와 다음에 대한 접근이 필요합니다:

LLM 클라이언트는 SandBase의 OpenAI 호환 POST /v1/chat/completions 엔드포인트를 사용하며, Chat Completions 가이드에 설명되어 있습니다. 모델 ID는 제공자 접두사를 유지합니다(openai/gpt-4.1-mini). 2026-10-01 (UTC)에 model: "openai/gpt-4.1-mini"과 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 라우트, 요청 본문 필드, 완료된 응답 형태를 보여줍니다

캡션: 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은 해당 엔드포인트의 파라미터만 전송합니다. 엔드포인트 참조는 완료된 응답을 {id, status, model, outputs: [{data: ...}]}로 문서화하므로, 헬퍼는 outputs[0].data을 읽고 호출이 완료되지 않았을 때 status과 error로 오류를 발생시킵니다. 이는 엔드포인트 참조의 Model API POST 라우트이며, 카탈로그 페이지에 표시된 GET 라우트가 아닙니다.

어느 검색 엔드포인트도 결과 개수를 받지 않으므로 도구는 로컬에서 잘라냅니다. 에이전트는 첫 페이지만 읽습니다. 페이지네이션은 엔드포인트마다 다릅니다. Douyin 일반 검색은 이전 응답의 cursor, search_id, backtrace을 다시 보내 페이지를 넘기고, Weibo 실시간 검색은 page 숫자를 받으며, 동영상 댓글은 cursor을 받습니다.

다른 두 참조는 그 파라미터를 직접 보여줍니다. Weibo 실시간 검색은 query(필수)과 page을 나열하고, 동영상 댓글은 aweme_id(필수), count(기본값 20), cursor(기본값 0)을 나열합니다.

weibo/web-v2/realtime-search에 대한 SandBase 엔드포인트 참조로, page와 필수 query 필드가 있는 POST 라우트를 보여줍니다

캡션: weibo/web-v2/realtime-search 참조로, query이 필수이고 page의 기본값이 1이며, 에이전트가 보내는 {"query": ..., "page": 1} 본문과 일치합니다(2026-10-02 캡처).

douyin/web/video-comments에 대한 SandBase 엔드포인트 참조로, aweme_id, count, cursor 필드가 있는 POST 라우트를 보여줍니다

캡션: douyin/web/video-comments 참조로, 필수 aweme_id과 count(기본값 20), cursor(기본값 0)을 보여주며, get_douyin_video_comments이 보내는 세 필드입니다(2026-10-02 캡처).

모든 call_data_api 호출은 RateLimiter을 기다리고(여기서는 60초당 30회 호출이며, 이 숫자는 SandBase 할당량이 아니라 자체 페이싱입니다), 네트워크 오류, HTTP 429, 5xx를 1초/2초 백오프로 재시도합니다. 도구 오류는 {"error": ...}으로 LLM에 다시 전달되므로 한 번의 실패한 호출이 사이클을 죽이지 않습니다.

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개, Weibo 게시물 9개, 댓글 19개를 받았습니다. 두 번의 테스트 실행(EN 및 ZH 코드)에서 총 28번의 데이터 호출 중 두 번이 HTTP 503을 반환했고 재시도가 성공했습니다. 이 실행에서 원시 Douyin 검색 페이로드는 거의 1 MB였으므로, 도구는 전체 응답을 LLM 컨텍스트에 쏟아붓는 대신 간결한 목록을 반환합니다.

비용 분석

데이터 API 호출: 각 조직은 UTC 기준 하루에 100번의 무료 데이터 API 호출을 받고, 그 이후에는 세 엔드포인트가 호출당 과금되므로, 데이터 측 비용은 대략 남은 호출 수 × SandBase 카탈로그의 각 엔드포인트 가격입니다(sandbase inspect로 확인하세요). LLM: 2026-10-01 기준 SandBase에서 openai/gpt-4.1-mini은 백만 입력 토큰당 $0.40, 백만 출력 토큰당 $1.60입니다.

키워드당 호출 수는 코드로 제한됩니다. 도구 사용 LLM 호출 1~MAX_ITERATIONS(4)회, 평가 호출 1회, 데이터 호출 0~MAX_DATA_CALLS_PER_KEYWORD(4)회입니다. 일반적인 경로는 두 플랫폼 검색, 동영상 하나의 댓글 가져오기, 답변으로, 도구 사용 호출 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분마다 실행하면(하루 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을 올리는 것을 잊지 마세요.

추세 비교 추가

위의 에이전트는 사이클마다 상태가 없습니다. 급증 감지는 그것이 갖지 못한 두 가지가 필요합니다. 페이지 크기로 고정되지 않는 볼륨 신호(예: 이전에 보지 못한 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. 두 클라이언트, 하나의 API 키. requests는 POST /v1/api/<endpoint>의 SandBase 데이터 API용이고, OpenAI SDK는 LLM 추론용이며, 둘 다 같은 키로 인증합니다.
  2. 도구 호출이 통합 패턴입니다. 각 도구를 하나의 엔드포인트에 매핑하고, LLM이 언제 호출할지 결정하게 하며, LLM 루프와 데이터 호출 모두에 상한을 두세요.
  3. outputs[0].data만 읽고, 크게 실패하세요. 호출이 완료되지 않으면 조용히 {}을 반환하는 대신 오류를 발생시키세요.
  4. 두 비용 항목을 모두 추적하세요. 데이터 엔드포인트는 하루 100번의 무료 호출 이후 카탈로그 가격으로 호출당 과금되고, LLM 호출은 토큰으로 과금되므로, 호출 수와 토큰 사용량을 기록하고 더 큰 쪽을 조정하세요.
  5. 동기 API는 루프를 단순하게 유지합니다. 소셜 데이터 API는 동기 전용이므로 콜백이나 작업 관리가 없습니다. 응답 스키마에는 pending과 running 상태도 나열되며, 이 에이전트는 폴링하는 대신 completed이 아닌 모든 것을 오류로 처리합니다.

SandBase API 키 받기 · Douyin 카탈로그 둘러보기 · Weibo 카탈로그 둘러보기

유용했다면 공유해 주세요