llm 붙임 및 리포트 생성 확인

This commit is contained in:
jaehwang committed 2026-05-14 16:16:09 +09:00
1 parent 26cd946e1b
commit 2b8a90e857
26 files changed
+507 -175

No files matched your search

+5 -3
View File
@@ -1,4 +1,5 @@
from http import HTTPMethod
from urllib.parse import urlparse
from common.utils import http_request
APIFY_BASE = "https://api.apify.com/v2"
@@ -32,8 +33,9 @@ class ApifyClient:
return []
return items_resp.json()
async def fetch_instagram_profile(self, handle: str) -> dict | None:
items = await self._run_actor("apify~instagram-profile-scraper", {"usernames": [handle], "resultsLimit": 12})
async def fetch_instagram_profile(self, url: str) -> dict | None:
username = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url.lstrip("@")
items = await self._run_actor("apify~instagram-profile-scraper", {"usernames": [username], "resultsLimit": 12})
return items[0] if items else None
async def get_instagram_profile(self, handle: str) -> dict | None:
@@ -131,7 +133,7 @@ class ApifyClient:
if not page:
return None
return {
"pageName": page["title"],
"pageName": page.get("title") or page.get("name"),
"pageUrl": page.get("pageUrl", page_url),
"followers": page.get("followers", 0),
"likes": page.get("likes", 0),
+82
View File
@@ -67,6 +67,88 @@ class FirecrawlClient:
return []
return (data.get("json") or {}).get("socialLinks", [])
async def fetch_clinic_info(self, url: str) -> dict | None:
resp = await http_request(
HTTPMethod.POST,
url=f"{FIRECRAWL_BASE}/scrape",
headers=self._headers(),
json_body={
"url": url,
"formats": ["json", "links"],
"jsonOptions": {
"prompt": "Extract: clinic name (Korean), clinic name (English), address, phone, business hours, slogan, services offered, doctors with name/title/specialty, brand identity (primary/accent/background/text colors in hex, heading/body fonts, logo URL, favicon URL)",
"schema": {
"type": "object",
"properties": {
"clinicName": {"type": "string"},
"clinicNameEn": {"type": "string"},
"address": {"type": "string"},
"phone": {"type": "string"},
"businessHours": {"type": "string"},
"slogan": {"type": "string"},
"services": {"type": "array", "items": {"type": "string"}},
"doctors": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"title": {"type": "string"},
"specialty": {"type": "string"},
},
},
},
# "socialMedia": {
# "type": "object",
# "properties": {
# "instagram": {"type": "string"},
# "youtube": {"type": "string"},
# "blog": {"type": "string"},
# "facebook": {"type": "string"},
# "tiktok": {"type": "string"},
# "kakao": {"type": "string"},
# },
# },
"branding": {
"type": "object",
"properties": {
"primaryColor": {"type": "string"},
"accentColor": {"type": "string"},
"backgroundColor": {"type": "string"},
"textColor": {"type": "string"},
"headingFont": {"type": "string"},
"bodyFont": {"type": "string"},
"logoUrl": {"type": "string"},
"faviconUrl": {"type": "string"},
},
},
},
},
},
"waitFor": 5000,
},
timeout=60,
label="firecrawl-clinic-info",
)
if not resp or not resp.is_success:
return None
data = resp.json().get("data") or {}
info = data.get("json") or {}
return {
"clinicName": info.get("clinicName"),
"clinicNameEn": info.get("clinicNameEn"),
"address": info.get("address"),
"phone": info.get("phone"),
"businessHours": info.get("businessHours"),
"slogan": info.get("slogan"),
"services": info.get("services", []),
"doctors": info.get("doctors", []),
# "socialMedia": info.get("socialMedia", {}),
"branding": info.get("branding", {}),
"siteLinks": data.get("links", []),
"sourceUrl": url,
}
async def fetch_gangnam_unni(self, hospital_url: str) -> dict | None:
resp = await http_request(
HTTPMethod.POST,
+1 -1
View File
@@ -1,3 +1,3 @@
from .service import LLMService
from .llm_service import LLMService
from .prompt import Prompt
+76
View File
@@ -0,0 +1,76 @@
from pydantic import BaseModel
from openai import AsyncOpenAI
from common.utils import get_env
from .prompt import Prompt
class LLMResponseError(Exception):
def __init__(self, status: str, code: str = None, message: str = None):
self.status = status
self.code = code
self.message = message
super().__init__(f"LLM response failed: status={status}, code={code}, message={message}")
class LLMService:
def __init__(self, provider: str = "openai", max_retries: int = 2):
self.provider = provider
self.max_retries = max_retries
match provider:
case "openai":
self.client = AsyncOpenAI(api_key=get_env("OPENAI_API_KEY"))
case "perplexity":
self.client = AsyncOpenAI(
api_key=get_env("PERPLEXITY_API_KEY"),
base_url="https://api.perplexity.ai",
)
case "gemini":
self.client = AsyncOpenAI(
api_key=get_env("GEMINI_API_KEY"),
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
)
case _:
raise NotImplementedError(f"Unknown provider: {provider}")
async def generate(
self,
prompt: Prompt,
input_data: dict,
) -> BaseModel:
prompt_text = prompt.build(input_data)
last_error = None
for attempt in range(self.max_retries + 1):
if self.provider == "perplexity":
response = await self.client.chat.completions.create(
model=prompt.model,
messages=[{"role": "user", "content": prompt_text}],
response_format={
"type": "json_schema",
"json_schema": {"name": prompt.output_class.__name__, "schema": prompt.output_class.model_json_schema()},
},
)
choice = response.choices[0]
if choice.finish_reason == "stop":
return prompt.output_class.model_validate_json(choice.message.content)
last_error = LLMResponseError("failed", choice.finish_reason, f"unexpected finish_reason: {choice.finish_reason}")
else:
response = await self.client.beta.chat.completions.parse(
model=prompt.model,
messages=[{"role": "user", "content": prompt_text}],
response_format=prompt.output_class,
)
choice = response.choices[0]
finish_reason = choice.finish_reason
if finish_reason == "stop":
return choice.message.parsed
if finish_reason == "length":
last_error = LLMResponseError("incomplete", finish_reason, "max tokens reached")
elif finish_reason == "content_filter":
last_error = LLMResponseError("failed", finish_reason, "blocked by content filter")
else:
last_error = LLMResponseError("failed", finish_reason, f"unexpected finish_reason: {finish_reason}")
raise last_error
+30 -9
View File
@@ -1,19 +1,40 @@
import os
from pydantic import BaseModel
from common.utils import get_env
from integrations.llm.schemas.report import ReportInput, ReportOutput
_PROMPT_DIR = os.path.join(os.path.dirname(__file__), "temp-prompt")
class Prompt:
def __init__(
self,
template: str,
model: str,
input_class: type[BaseModel],
output_class: type[BaseModel],
):
self.template = template
self.model = model
file_name: str
prompt_model: str
input_class: type[BaseModel]
output_class: type[BaseModel]
def __init__(self, file_name: str, prompt_model: str, input_class: type[BaseModel], output_class: type[BaseModel]):
self.file_name = file_name
self.prompt_model = prompt_model
self.input_class = input_class
self.output_class = output_class
self.template, self.model = self._load_prompt()
def _load_prompt(self) -> tuple[str, str]:
with open(os.path.join(_PROMPT_DIR, self.file_name), encoding="utf-8") as f:
template = f.read()
return template, get_env(self.prompt_model)
def _reload_prompt(self):
self.template, self.model = self._load_prompt()
def build(self, input_data: dict) -> str:
verified = self.input_class(**input_data)
return self.template.format(**verified.model_dump())
report_prompt = Prompt(
file_name="report_prompt.txt",
prompt_model="REPORT_MODEL",
input_class=ReportInput,
output_class=ReportOutput,
)
+43
View File
@@ -0,0 +1,43 @@
from pydantic import BaseModel
# template.format(**model_dump()) 에 삽입될 변수들
# 각 채널 raw_data를 호출부에서 json.dumps()로 직렬화해서 넘겨야 함
class ReportInput(BaseModel):
clinic_name: str | None = None
clinic_name_en: str | None = None
address: str | None = None
phone: str | None = None
slogan: str | None = None
services: str | None = None
doctors: str | None = None
instagram: str | None = None
facebook: str | None = None
naver_blog: str | None = None
youtube: str | None = None
gangnam_unni: str | None = None
class ChannelScore(BaseModel):
score: int
summary: str
strengths: list[str]
weaknesses: list[str]
class ConversionStrategy(BaseModel):
summary: str
actions: list[str]
# response_format으로 OpenAI structured output에 전달 — dict 필드 사용 불가
class ReportOutput(BaseModel):
overall_score: int
instagram: ChannelScore | None = None
facebook: ChannelScore | None = None
naver_blog: ChannelScore | None = None
youtube: ChannelScore | None = None
gangnam_unni: ChannelScore | None = None
conversion_strategy: ConversionStrategy
roadmap: list[str]
kpis: list[str]
-61
View File
@@ -1,61 +0,0 @@
from pydantic import BaseModel
from openai import AsyncOpenAI
from common.utils import get_env
from .prompt import Prompt
class LLMResponseError(Exception):
def __init__(self, status: str, code: str = None, message: str = None):
self.status = status
self.code = code
self.message = message
super().__init__(f"LLM response failed: status={status}, code={code}, message={message}")
class LLMService:
def __init__(self, provider: str = "openai", max_retries: int = 2):
self.max_retries = max_retries
match provider:
case "openai":
self.client = AsyncOpenAI(api_key=get_env("OPENAI_API_KEY"))
case "perplexity":
self.client = AsyncOpenAI(
api_key=get_env("PERPLEXITY_API_KEY"),
base_url="https://api.perplexity.ai",
)
case "gemini":
self.client = AsyncOpenAI(
api_key=get_env("GEMINI_API_KEY"),
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
)
case _:
raise NotImplementedError(f"Unknown provider: {provider}")
async def generate(
self,
prompt: Prompt,
input_data: dict,
) -> BaseModel:
prompt_text = prompt.build(input_data)
last_error = None
for attempt in range(self.max_retries + 1):
response = await self.client.beta.chat.completions.parse(
model=prompt.model,
messages=[{"role": "user", "content": prompt_text}],
response_format=prompt.output_class,
)
choice = response.choices[0]
finish_reason = choice.finish_reason
if finish_reason == "stop":
return choice.message.parsed
if finish_reason == "length":
last_error = LLMResponseError("incomplete", finish_reason, "max tokens reached")
elif finish_reason == "content_filter":
last_error = LLMResponseError("failed", finish_reason, "blocked by content filter")
else:
last_error = LLMResponseError("failed", finish_reason, f"unexpected finish_reason: {finish_reason}")
raise last_error
@@ -0,0 +1 @@
@@ -0,0 +1,38 @@
당신은 프리미엄 의료 마케팅 전문 분석가입니다. 아래 실제 수집된 데이터를 기반으로 종합 마케팅 리포트를 생성해주세요.
결과물은 한국어로 생성하세요
⚠️ 중요: 데이터가 null인 채널은 해당 항목을 null로 설정하세요. 데이터에 없는 수치는 절대 추측하지 마세요.
## 병원 기본 정보
- 병원명: {clinic_name}
- 영문명: {clinic_name_en}
- 주소: {address}
- 전화: {phone}
- 슬로건: {slogan}
- 시술: {services}
- 의료진: {doctors}
## 채널 데이터
### 인스타그램
{instagram}
### 페이스북
{facebook}
### 네이버 블로그
{naver_blog}
### 유튜브
{youtube}
### 강남언니
{gangnam_unni}
## 분석 지침
- 점수는 0~100 기준입니다.
- strengths와 weaknesses는 각 3개 이상 작성하세요.
- roadmap은 우선순위 순으로 실행 가능한 액션으로 작성하세요.
- kpis는 실제 수집된 수치 기반으로 현실적인 측정 가능 지표로 작성하세요.
- conversion_strategy의 actions는 구체적인 실행 방안으로 작성하세요.
+5 -3
View File
@@ -1,5 +1,6 @@
import re
from http import HTTPMethod
from urllib.parse import urlparse
from common.utils import http_request
NAVER_BASE = "https://openapi.naver.com/v1/search"
@@ -52,10 +53,10 @@ class NaverClient:
return []
return resp.json().get("items", [])
async def fetch_blog_rss(self, blog_handle: str) -> str | None:
async def fetch_blog_rss(self, handle: str) -> str | None:
resp = await http_request(
HTTPMethod.GET,
url=f"https://rss.blog.naver.com/{blog_handle}.xml",
url=f"https://rss.blog.naver.com/{handle}.xml",
timeout=15,
label="naver-rss",
)
@@ -63,7 +64,8 @@ class NaverClient:
return None
return resp.text
async def get_blog_rss(self, blog_handle: str) -> dict | None:
async def get_blog_rss(self, url: str) -> dict | None:
blog_handle = urlparse(url).path.strip("/").split("/")[0] if "://" in url else url
xml = await self.fetch_blog_rss(blog_handle)
if not xml:
return None
+4 -14
View File
@@ -1,4 +1,5 @@
from http import HTTPMethod
from urllib.parse import urlparse
from common.utils import http_request
YT = "https://www.googleapis.com/youtube/v3"
@@ -9,7 +10,7 @@ class YouTubeClient:
self.api_key = api_key
async def _resolve_channel_id(self, handle: str) -> str:
h = handle.lstrip("@")
h = urlparse(handle).path.strip("/").lstrip("@") if "://" in handle else handle.lstrip("@")
if h.startswith("UC") and len(h) == 24:
return h
for param in ("forHandle", "forUsername"):
@@ -47,14 +48,7 @@ class YouTubeClient:
resp = await http_request(
HTTPMethod.GET,
url=f"{YT}/search",
params={
"part": "snippet",
"channelId": channel_id,
"order": "viewCount",
"type": "video",
"maxResults": 10,
"key": self.api_key,
},
params={"part": "snippet", "channelId": channel_id, "order": "viewCount", "type": "video", "maxResults": 10, "key": self.api_key},
label="yt-search",
)
if resp and resp.is_success:
@@ -65,11 +59,7 @@ class YouTubeClient:
resp = await http_request(
HTTPMethod.GET,
url=f"{YT}/videos",
params={
"part": "snippet,statistics,contentDetails",
"id": ",".join(video_ids),
"key": self.api_key,
},
params={"part": "snippet,statistics,contentDetails", "id": ",".join(video_ids), "key": self.api_key},
label="yt-videos",
)
if resp and resp.is_success: