1. 사용자 프롬프트에서 “키워드” 검색 요청
  2. LLM tool calling
  3. /api/web_research/fetch API 함수 호출
@app.post("/api/web_search/fetch", response_model=dict, operation_id="web_search_fetch")
async def web_search_fetch(req: WebSearchFetchRequest):
    query = normalize_query(req.query)
    if not query:
        return standard_response(success=False, message="query required", data=None, error="empty query")

    max_results = max(1, min(req.max_results or 5, 20))
    search_result = await web_search(WebSearchRequest(query=query, max_results=max_results, engine=req.engine))

    if not search_result.get("success"):
        return standard_response(
            success=False,
            message="search failed",
            data=None,
            error=search_result.get("error") or "search_failed",
        )

    items = (search_result.get("data") or {}).get("items") or []
    if not items:
        logger.info("[web_search_fetch] no search results for query=%s", query)
        return standard_response(
            success=False,
            message="no search results",
            data=None,
            error="no_search_results",
        )

    items = items[:max_results]
    logger.info("[web_search_fetch] query=%s engine=%s results=%d", query, req.engine, len(items))

    semaphore = asyncio.Semaphore(MAX_PLAYWRIGHT_CONCURRENCY)
    tasks = [
        _fetch_and_save_article(item, req.timeout_ms or 20000, semaphore)
        for item in items
    ]
    results = await asyncio.gather(*tasks)

    saved: list[dict[str, str]] = []
    failed: list[dict[str, str]] = []

    for ok, err in results:
        if ok:
            saved.append(ok)
            logger.info("[web_search_fetch] saved title=%s path=%s", ok.get("title", ""), ok.get("file_path", ""))
        elif err:
            failed.append(err)
            logger.info("[web_search_fetch] failed link=%s reason=%s", err.get("link", ""), err.get("reason", ""))

    message = f"saved {len(saved)} items"
    return standard_response(
        success=bool(saved) or not failed,  # allow partial success
        message=message,
        data={"query": query, "saved": saved, "failed": failed},
        error=None if saved or not failed else "all_failed",
    )
  1. 쿼리 정규화
# web_search_fetch 함수 내부

		query = normalize_query(req.query)
    if not query:
        return standard_response(success=False, message="query required", data=None, error="empty query")
        
        
# normalize_query 함수 : "" 혹은 '' 로 감싸진 단어를 키워드로 인식

def normalize_query(query: str) -> str:
    """
    Trim whitespace, drop wrapping quotes, and collapse internal spacing.
    """
    if query is None:
        return ""

    text = query.strip()
    if len(text) >= 2 and text[0] == text[-1] and text[0] in {"'", '"'}:
        text = text[1:-1].strip()

    text = re.sub(r"\s+", " ", text)
    return text.strip()
    
# standard_response 

def standard_response(success: bool = True, message: str = "ok", data: Any = None, error: Any = None):
    """
    OpenWebUI HTTP Tool 연동을 위한 공통 응답 포맷.
    - success: bool
    - message: 한 줄 설명
    - data: 주요 응답 페이로드 (dict/모델)
    - error: 에러 상세 (없으면 None)
    """
    return {
        "success": success,
        "message": message,
        "data": data,
        "error": error,
    }

  1. 결과물 설정 및 웹서치 수행
# web_search_fetch 함수 내부

		max_results = max(1, min(req.max_results or 5, 20))
    search_result = await web_search(WebSearchRequest(query=query, max_results=max_results, engine=req.engine))
    
# web_search 함수 

@app.post("/api/web/search", response_model=dict, operation_id="web_search")
async def web_search(req: WebSearchRequest):
    query = normalize_query(req.query)
    if not query:
        return standard_response(success=False, message="query required", data=None, error="empty query")

    max_results = max(1, min(req.max_results or 5, 20))
    engine = (req.engine or "google_news_rss").lower()

    items: list[dict[str, str]] = []
    error: str | None = None

    if engine == "searxng" or (engine != "google_news_rss" and SEARXNG_URL):
        items, error = await _search_searxng(query, max_results)
        engine_used = "searxng"
    else:
        items, error = await _search_google_news_rss(query, max_results)
        engine_used = "google_news_rss"

    if error:
        return standard_response(success=False, message="search failed", data=None, error=error)

    return standard_response(
        success=True,
        message="ok",
        data={"query": query, "engine": engine_used, "items": items[:max_results]},
        error=None,
    )

MAX_PLAYWRIGHT_CONCURRENCY = 2

# _search_searxng 함수

async def _search_searxng(query: str, max_results: int) -> tuple[list[dict[str, str]], str | None]:
    if not SEARXNG_URL:
        return [], "SEARXNG_URL not configured"

    params = {"q": query, "format": "json", "engines": "news"}
    try:
        async with httpx.AsyncClient(timeout=20.0) as client:
            resp = await client.get(SEARXNG_URL.rstrip("/") + "/search", params=params)
    except Exception as exc:
        return [], f"http error: {exc}"

    if resp.status_code >= 400:
        return [], f"searxng status {resp.status_code}"

    try:
        data = resp.json()
    except Exception as exc:
        return [], f"invalid json: {exc}"

    results = []
    for item in data.get("results", []):
        link = item.get("url") or item.get("link")
        title = item.get("title") or ""
        if link and title:
            results.append({"link": link, "title": title})
        if len(results) >= max_results:
            break

    return results, None

# _search_google_news_rss 함수

async def _search_google_news_rss(query: str, max_results: int) -> tuple[list[dict[str, str]], str | None]:
    url = (
        "https://news.google.com/rss/search?"
        f"q={quote_plus(query)}&hl=ko&gl=KR&ceid=KR:ko"
    )
    try:
        async with httpx.AsyncClient(timeout=20.0) as client:
            resp = await client.get(url)
            resp.raise_for_status()
            text = resp.text
    except Exception as exc:
        return [], f"http error: {exc}"

    try:
        import xml.etree.ElementTree as ET

        root = ET.fromstring(text)
        items: list[dict[str, str]] = []
        for item in root.findall(".//item"):
            title_el = item.find("title")
            link_el = item.find("link")
            title = title_el.text.strip() if title_el is not None and title_el.text else ""
            link = link_el.text.strip() if link_el is not None and link_el.text else ""
            if link and title:
                items.append({"link": link, "title": title})
            if len(items) >= max_results:
                break
        return items, None
    except Exception as exc:
        return [], f"parse error: {exc}"

  1. 실패 시
# web_search_fetch 함수 내부

    if not search_result.get("success"):
        return standard_response(
            success=False,
            message="search failed",
            data=None,
            error=search_result.get("error") or "search_failed",
        )

    items = (search_result.get("data") or {}).get("items") or []
    if not items:
        logger.info("[web_search_fetch] no search results for query=%s", query)
        return standard_response(
            success=False,
            message="no search results",
            data=None,
            error="no_search_results",
        )
  1. 성공 시
# web_search_fetch 함수 내부

		items = items[:max_results]
    logger.info("[web_search_fetch] query=%s engine=%s results=%d", query, req.engine, len(items))

    semaphore = asyncio.Semaphore(MAX_PLAYWRIGHT_CONCURRENCY)
    # 크롤링한 내용을 파일로 저장
    tasks = [
        _fetch_and_save_article(item, req.timeout_ms or 20000, semaphore)
        for item in items
    ]
    results = await asyncio.gather(*tasks)

    saved: list[dict[str, str]] = []
    failed: list[dict[str, str]] = []
    
# _fetch_and_save_article 함수

async def _fetch_and_save_article(
    item: dict[str, Any],
    timeout_ms: int,
    semaphore: asyncio.Semaphore,
) -> tuple[dict[str, str] | None, dict[str, str] | None]:
    """
    Fetch article via Playwright MCP and save to WEBRESEARCH_OUT_DIR.
    Returns (saved, failed) where each is a dict.
    """
    link = item.get("link") or item.get("url")
    title = item.get("title") or ""
    if not link:
        return None, {"link": "", "reason": "invalid_link"}

    async with semaphore:
        data, err = await _call_playwright_fetch(link, timeout_ms)
        if err or data is None:
            return None, {"link": link, "reason": f"playwright_failed: {err or 'no data'}"}

        link2, title2, body = _extract_article_payload(data)
        final_link = link2 or link
        final_title = (title2 or title or "").strip()
        if not body:
            return None, {"link": final_link, "reason": "no_body"}

        cleaned_body, llm_reason = await _select_and_clean_article_body(final_title, final_link, body)
        if llm_reason:
            logger.info("[body_clean] llm_reason=%s url=%s", llm_reason, final_link)

        try:
            file_path = save_txt(WEBRESEARCH_OUT_DIR, final_title, final_link, cleaned_body)
        except Exception as exc:
            return None, {"link": final_link, "reason": f"save_failed: {exc}"}

    return {"link": final_link, "title": final_title, "file_path": file_path}, None
    
    
# _call_playwright_fetch 함수

async def _call_playwright_fetch(url: str, timeout_ms: int | None = None) -> tuple[dict[str, Any] | None, str | None]:
    """
    Call Playwright MCP fetch endpoint and return (data, error_message).
    """
    payload: dict[str, Any] = {"url": url}
    if timeout_ms is not None:
        payload["timeout_ms"] = timeout_ms

    base_timeout = max(5.0, (timeout_ms or 20000) / 1000 + 5)
    try:
        async with httpx.AsyncClient(timeout=base_timeout) as client:
            resp = await client.post(f"{PLAYWRIGHT_MCP_URL.rstrip('/')}/fetch", json=payload)
    except Exception as exc:
        return None, f"http error: {exc}"

    if resp.status_code >= 400:
        return None, f"playwright mcp returned status {resp.status_code}"

    try:
        data = resp.json()
    except Exception as exc:
        return None, f"invalid json from playwright mcp: {exc}"

    return data, None

# _extract_article_payload 함수 : 필요한 부분만 추출

def _extract_article_payload(raw: Any) -> tuple[str | None, str | None, str | None]:
    """
    Extract (link, title, body) from various possible MCP payload shapes.
    """
    if not isinstance(raw, dict):
        return None, None, None

    payload = raw
    if isinstance(payload.get("data"), dict):
        payload = payload["data"]

    # try direct keys
    link = payload.get("link") or payload.get("url")
    title = payload.get("title") or payload.get("pageTitle") or payload.get("name")
    body = payload.get("body") or payload.get("text") or payload.get("content")

    # fallback: nested article/result objects
    if body is None:
        for key in ("article", "result", "item"):
            nested = payload.get(key)
            if isinstance(nested, dict):
                link = link or nested.get("link") or nested.get("url")
                title = title or nested.get("title") or nested.get("pageTitle")
                body = nested.get("body") or nested.get("text") or nested.get("content")
                if body:
                    break

    if isinstance(body, (dict, list)):
        body = json.dumps(body, ensure_ascii=False)
    if body is not None:
        body = str(body).strip()

    return link, title, body

ARTICLE_NOISE_KEYWORDS = [
    "공유",
    "스크랩",
    "인쇄",
    "글자 크기",
    "폰트",
    "댓글",
    "구독",
    "로그인",
    "앱에서 보기",
    "바로가기",
    "기자",
    "후원",
    "광고",
    "무단전재",
    "재배포",
    "저작권",
    "뉴스 제공",
    "기사 원문",
]

ARTICLE_NOISE_PATTERNS = [
    r"무단전재\s*/\s*재배포 금지",
    r"copyright",
    r"ⓒ",
    r"사진\s*=\s*",
    r"영상\s*=\s*",
    r"관련\s*기사",
    r"기사\s*입력",
    r"기사\s*승인",
]

# _select_and_clean_article_body 함수

async def _select_and_clean_article_body(title: str, url: str | None, raw_body: str) -> tuple[str, str | None]:
    precleaned = _rule_based_article_cleanup(raw_body)
    llm_reason: str | None = None

    try:
        llm_body, llm_reason = await _llm_select_article_body(title, url, precleaned)
    except Exception as exc:
        logger.info("[body_clean] llm failed for url=%s err=%s", url, exc)
        llm_body = None

    final_body = llm_body or precleaned or (raw_body or "")
    return final_body, llm_reason

# _llm_select_article_body 함수

async def _llm_select_article_body(title: str, url: str | None, body: str) -> tuple[str | None, str | None]:
    blocks = _split_paragraphs(body)
    if not blocks:
        return None, "no_blocks"

    prompt = _build_llm_body_prompt(title, url, blocks)
    raw = await call_llm(prompt)
    js = extract_json_block(raw)

    try:
        data = json.loads(js)
    except Exception:
        return None, "json_parse_failed"

    if data.get("is_article") is False:
        return None, str(data.get("reason") or "rejected")

    cleaned = _normalize_body_text(data.get("clean_body") or data.get("body") or "")
    if len(cleaned) < 80:
        return None, "llm_body_too_short"

    return cleaned, str(data.get("reason") or "llm_selected")
    
# _build_llm_body_prompt 함수

def _build_llm_body_prompt(title: str, url: str | None, blocks: list[str]) -> str:
    blocks_json = json.dumps(blocks, ensure_ascii=False, indent=2)
    return f"""
너는 뉴스/블로그 기사 본문 식별 및 정제기다.
주어진 후보 문단 중 기사 본문만 남기고 UI/광고/공유/폰트 안내/댓글/구독/저작권 문구를 제거한다.

[출력만 JSON으로]
{{
  "is_article": true|false,
  "clean_body": "본문만 자연스럽게 이어붙인 텍스트",
  "reason": "선택 근거 한 줄"
}}

[입력 정보]
- 제목: {title}
- URL: {url or ""}
- 후보 문단 리스트(JSON): {blocks_json}

규칙:
- clean_body에는 기사 본문 문장만 남겨라. 불필요한 공백과 중복을 없애고 문단 사이에는 빈 줄 1개만 둔다.
- 공유/스크랩/인쇄/글자크기/뉴스 제공/저작권/구독/댓글/관련기사/광고 등 UI 텍스트는 모두 제거.
- 본문이 확실하지 않으면 is_article=false로 하고 reason만 채운다.
""".strip()

# _normalize_body_text 함수

def _normalize_body_text(text: str) -> str:
    normalized = re.sub(r"\r\n?", "\n", text or "")
    normalized = re.sub(r"[ \t]+", " ", normalized)
    normalized = re.sub(r"\n{3,}", "\n\n", normalized)
    return normalized.strip()

# save_txt 함수 

def save_txt(out_dir: str | Path, title: str | None, url: str | None, body: str | None) -> str:
    base_dir = ensure_dir(out_dir)
    safe_title = safe_filename(title or url or "article")
    timestamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
    filepath = base_dir / f"{timestamp}_{safe_title}.txt"

    content = f"URL: {url or ''}\nTITLE: {title or ''}\n\n{body or ''}\n"
    filepath.write_text(content, encoding="utf-8")

    return str(filepath)
  1. 저장 및 로깅 / 응답
# web_search_fetch 함수 내부

    for ok, err in results:
        if ok:
            saved.append(ok)
            logger.info("[web_search_fetch] saved title=%s path=%s", ok.get("title", ""), ok.get("file_path", ""))
        elif err:
            failed.append(err)
            logger.info("[web_search_fetch] failed link=%s reason=%s", err.get("link", ""), err.get("reason", ""))

    message = f"saved {len(saved)} items"
    return standard_response(
        success=bool(saved) or not failed,  # allow partial success
        message=message,
        data={"query": query, "saved": saved, "failed": failed},
        error=None if saved or not failed else "all_failed",
    )