feat: Perplexity sonar-pro research agent with structured online presence analysis

Replaced simple "find handles" prompt with comprehensive research agent:
- Model: sonar → sonar-pro (advanced multi-step web search)
- System prompt: full research methodology with 2-3 keyword searches,
  URL fetching, quantitative data extraction
- Output: structured JSON with channels (handles + follower counts +
  subscriber counts) + platforms (강남언니 rating, reviews)
- Research results saved to scrape_data.onlinePresenceResearch for
  downstream use in collect-channel-data and generate-report

Added _shared/researchPrompt.ts with prompt template + builder.
Updated agent documentation in doc/.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Opus 4.6 committed 2026-04-04 01:31:00 +09:00
1 parent c74832d764
commit e64d168d34
3 files changed
+389 -43

No files matched your search

@@ -0,0 +1,93 @@
/**
* Perplexity Online Presence Research Agent — System Prompt
*
* Used by discover-channels to conduct comprehensive channel research.
* Model: sonar-pro (advanced web search with multi-step reasoning)
*/
export const RESEARCH_SYSTEM_PROMPT = `당신은 성형외과/피부과 병원의 온라인 프레즌스를 조사·정리하는 리서치 전문가 에이전트입니다.
목표:
- 사용자가 지정한 병원의 Online Presence를 정량·정성적으로 분석하여
채널별 (웹사이트, 유튜브, 인스타그램, 리뷰/플랫폼 등) 현황을 정리합니다.
반드시 지킬 규칙:
1) 검색 전략
- 질의를 2~3개의 짧은 키워드 검색으로 쪼갭니다.
- "<병원명> 유튜브 채널"
- "<병원명> 인스타그램"
- "<병원명> 후기 리뷰"
- 검색 결과에서 다음 URL 유형을 우선 확인합니다:
- 병원 공식 웹사이트
- YouTube 채널/영상
- Instagram 공식 계정
- 리뷰/평점 플랫폼 (강남언니, 바비톡, RealSelf, Bookimed, 대다모, 성예사 등)
2) 채널별 필수 수집 항목
유튜브:
- 공식 채널명, 채널 URL, @핸들
- 구독자 수 (숫자 또는 범위 추정)
- 업로드 영상 수
- 콘텐츠 유형
인스타그램:
- 계정 ID (@handle) — 여러 계정 가능 (국문, 영문, 원장 개인 등)
- 팔로워 수
- 게시물 수
- 주요 콘텐츠 유형
웹사이트:
- 공식 도메인
- 언어 버전 (국문/영문/다국어)
리뷰·후기:
- 강남언니: 평점(/10), 리뷰 수, URL
- 네이버 플레이스: 등록 여부
- Google Maps: 평점, 리뷰 수
- 기타 (바비톡, RealSelf 등)
페이스북/틱톡/네이버블로그/카카오:
- 계정 URL 또는 핸들
- 팔로워/구독자 수 (확인 가능한 경우)
3) 응답 포맷
반드시 아래 JSON 구조로 응답하세요. 설명 텍스트 없이 JSON만 반환하세요.
{
"clinicName": "병원 한국어 이름",
"clinicNameEn": "English name",
"channels": {
"instagram": [
{"handle": "@handle", "followers": 숫자_또는_null, "posts": 숫자_또는_null, "type": "공식/영문/원장 등", "url": "URL"}
],
"youtube": [
{"handle": "@handle_또는_채널명", "channelUrl": "URL", "subscribers": 숫자_또는_null, "videos": 숫자_또는_null, "contentType": "설명"}
],
"facebook": {"handle": "페이지명", "url": "URL", "followers": 숫자_또는_null},
"tiktok": {"handle": "@handle", "url": "URL", "followers": 숫자_또는_null},
"naverBlog": {"blogId": "ID", "url": "URL"},
"kakao": {"channelId": "ID", "url": "URL"},
"website": {"domain": "도메인", "languages": ["ko", "en"]}
},
"platforms": {
"gangnamUnni": {"registered": true, "url": "URL", "rating": 숫자_또는_null, "ratingScale": 10, "reviews": 숫자_또는_null},
"naverPlace": {"registered": true, "rating": 숫자_또는_null, "reviews": 숫자_또는_null},
"googleMaps": {"rating": 숫자_또는_null, "reviews": 숫자_또는_null},
"babitok": {"registered": true}
},
"summary": "1-2문장 온라인 프레즌스 요약"
}
4) 주의사항
- 수치가 정확하면 숫자로, 확인 불가하면 null로 표시
- 추측하지 말고 검색 결과에서 확인된 정보만 포함
- 설명 텍스트 없이 JSON만 반환`;
/**
* Build the user prompt for the research agent.
*/
export function buildResearchUserPrompt(clinicName: string, websiteUrl?: string): string {
return `"${clinicName}" 병원의 Online Presence를 위 규칙대로 분석해줘.${websiteUrl ? ` 공식 웹사이트: ${websiteUrl}` : ''}`;
}
+62 -43
View File
@@ -2,6 +2,7 @@ import "@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
import { extractSocialLinks, mergeSocialLinks } from "../_shared/extractSocialLinks.ts";
import { verifyAllHandles, type VerifiedChannels } from "../_shared/verifyHandles.ts";
import { RESEARCH_SYSTEM_PROMPT, buildResearchUserPrompt } from "../_shared/researchPrompt.ts";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
@@ -283,7 +284,9 @@ Deno.serve(async (req) => {
} catch { /* skip */ }
})());
// ─── B4. Perplexity: Online Presence 종합 분석 ───
// ─── B4. Perplexity sonar-pro: Online Presence 종합 리서치 에이전트 ───
let perplexityResearch: Record<string, unknown> | null = null;
if (PERPLEXITY_API_KEY) {
stageBTasks.push((async () => {
try {
@@ -291,61 +294,75 @@ Deno.serve(async (req) => {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${PERPLEXITY_API_KEY}` },
body: JSON.stringify({
model: "sonar",
model: "sonar-pro",
messages: [
{ role: "system", content: "You are a digital marketing analyst specializing in Korean medical clinics. Search the web thoroughly and provide a comprehensive online presence report. Respond ONLY with valid JSON." },
{ role: "user", content: `"${resolvedName}" 병원의 Online Presence를 종합 분석해줘.
아래 채널들을 모두 검색해서 찾아줘:
- 인스타그램 계정 (병원 공식, 원장 개인, 영문 계정 등 여러개 있을 수 있음)
- 유튜브 채널 (메인 채널, Q&A 채널 등)
- 페이스북 페이지
- 틱톡 계정
- 네이버 블로그 (공식 블로그)
- 카카오톡 채널
- 강남언니 등록 여부 및 URL
- 바비톡 등록 여부
- 네이버 플레이스 등록 여부
각 채널의 핸들/URL/계정명을 정확하게 알려줘.
JSON format:
{
"instagram": ["handle1", "handle2", "handle3"],
"youtube": ["channel URL or @handle1", "channel2"],
"facebook": "page URL or name",
"tiktok": "@handle",
"naverBlog": "blog ID",
"kakao": "channel ID",
"gangnamUnni": {"url": "https://gangnamunni.com/hospitals/...", "registered": true},
"naverPlace": {"registered": true},
"babitok": {"registered": true}
}` },
{ role: "system", content: RESEARCH_SYSTEM_PROMPT },
{ role: "user", content: buildResearchUserPrompt(resolvedName, url) },
],
temperature: 0.2,
temperature: 0.1,
}),
});
const data = await res.json();
let text = data.choices?.[0]?.message?.content || "";
// Strip markdown code blocks
const jsonMatch = text.match(/```(?:json)?\n?([\s\S]*?)```/);
if (jsonMatch) text = jsonMatch[1];
// Try to find JSON in mixed text
const jsonStart = text.indexOf('{');
const jsonEnd = text.lastIndexOf('}');
if (jsonStart >= 0 && jsonEnd > jsonStart) {
text = text.slice(jsonStart, jsonEnd + 1);
}
const parsed = JSON.parse(text);
perplexityResearch = parsed;
// Extract social handles
const igArr = Array.isArray(parsed.instagram) ? parsed.instagram : parsed.instagram ? [parsed.instagram] : [];
const ytArr = Array.isArray(parsed.youtube) ? parsed.youtube : parsed.youtube ? [parsed.youtube] : [];
if (igArr.length) apiHandles.instagram!.push(...igArr);
if (ytArr.length) apiHandles.youtube!.push(...ytArr);
if (parsed.facebook) apiHandles.facebook!.push(typeof parsed.facebook === 'string' ? parsed.facebook : '');
if (parsed.naverBlog) apiHandles.naverBlog!.push(typeof parsed.naverBlog === 'string' ? parsed.naverBlog : '');
if (parsed.tiktok) apiHandles.tiktok!.push(typeof parsed.tiktok === 'string' ? parsed.tiktok : '');
if (parsed.kakao) apiHandles.kakao!.push(typeof parsed.kakao === 'string' ? parsed.kakao : '');
// Extract handles from structured channels data
const ch = parsed.channels || {};
// Instagram
const igAccounts = Array.isArray(ch.instagram) ? ch.instagram : [];
for (const ig of igAccounts) {
const handle = typeof ig === 'string' ? ig : (ig?.handle || ig?.url || '');
if (handle) apiHandles.instagram!.push(String(handle));
}
// YouTube
const ytChannels = Array.isArray(ch.youtube) ? ch.youtube : ch.youtube ? [ch.youtube] : [];
for (const yt of ytChannels) {
const handle = typeof yt === 'string' ? yt : (yt?.handle || yt?.channelUrl || '');
if (handle) apiHandles.youtube!.push(String(handle));
}
// Facebook
if (ch.facebook) {
const fb = typeof ch.facebook === 'string' ? ch.facebook : (ch.facebook?.handle || ch.facebook?.url || '');
if (fb) apiHandles.facebook!.push(String(fb));
}
// TikTok
if (ch.tiktok) {
const tk = typeof ch.tiktok === 'string' ? ch.tiktok : (ch.tiktok?.handle || ch.tiktok?.url || '');
if (tk) apiHandles.tiktok!.push(String(tk));
}
// Naver Blog
if (ch.naverBlog) {
const nb = typeof ch.naverBlog === 'string' ? ch.naverBlog : (ch.naverBlog?.blogId || ch.naverBlog?.url || '');
if (nb) apiHandles.naverBlog!.push(String(nb));
}
// Kakao
if (ch.kakao) {
const kk = typeof ch.kakao === 'string' ? ch.kakao : (ch.kakao?.channelId || ch.kakao?.url || '');
if (kk) apiHandles.kakao!.push(String(kk));
}
// Platform presence hints
const platforms = parsed.platforms || {};
if (platforms.gangnamUnni?.url) gangnamUnniHintUrl = String(platforms.gangnamUnni.url);
// Extract platform presence hints
if (parsed.gangnamUnni?.url) gangnamUnniHintUrl = parsed.gangnamUnni.url;
} catch { /* skip */ }
})());
}
// ─── B5. Apify Instagram: Direct profile search by clinic name variants ───
@@ -431,6 +448,8 @@ JSON format:
clinic, branding: brandData.data?.json || {},
siteLinks, siteMap: mapData.links || [],
sourceUrl: url, scrapedAt: new Date().toISOString(),
// Perplexity research results — raw channel data with subscriber counts etc.
onlinePresenceResearch: perplexityResearch,
};
const { data: saved, error: saveError } = await supabase