feat: initial commit for Blog Expert multi-agent system
This commit is contained in:
@@ -0,0 +1 @@
|
||||
from .config import settings, Settings
|
||||
@@ -0,0 +1,110 @@
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv, find_dotenv
|
||||
import os
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
ENV_PATH = BASE_DIR / ".env"
|
||||
|
||||
if not ENV_PATH.exists():
|
||||
found = find_dotenv()
|
||||
if found:
|
||||
ENV_PATH = Path(found)
|
||||
|
||||
load_dotenv(ENV_PATH, override=True)
|
||||
|
||||
|
||||
def _get_env(*names, default=None):
|
||||
load_dotenv(ENV_PATH, override=True)
|
||||
for name in names:
|
||||
value = os.getenv(name)
|
||||
|
||||
if value is not None and value != "":
|
||||
val = str(value).strip().strip('"').strip("'")
|
||||
if val.startswith("-") and not val.startswith("-sk-"):
|
||||
val = val.lstrip("-")
|
||||
return val
|
||||
|
||||
try:
|
||||
if ENV_PATH.exists():
|
||||
with open(ENV_PATH, "r", encoding="utf-8") as env_file:
|
||||
for line in env_file:
|
||||
if "=" not in line:
|
||||
continue
|
||||
|
||||
key, value = line.split("=", 1)
|
||||
|
||||
if key.strip() in names:
|
||||
val = value.strip().strip('"').strip("'")
|
||||
if val.startswith("-") and not val.startswith("-sk-"):
|
||||
val = val.lstrip("-")
|
||||
return val
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return default
|
||||
|
||||
class Settings:
|
||||
|
||||
@property
|
||||
def GROQ_API_KEY(self):
|
||||
return _get_env("GROQ_API_KEY")
|
||||
|
||||
@property
|
||||
def OPENAI_API_KEY(self):
|
||||
return _get_env("OPENAI_API_KEY")
|
||||
|
||||
@property
|
||||
def PINECONE_API_KEY(self):
|
||||
return _get_env("PINECONE_API_KEY")
|
||||
|
||||
@property
|
||||
def PINECONE_INDEX_NAME(self):
|
||||
return _get_env("PINECONE_INDEX_NAME")
|
||||
|
||||
@property
|
||||
def TAVILY_API_KEY(self):
|
||||
return _get_env("TAVILY_API_KEY")
|
||||
|
||||
@property
|
||||
def FIRECRAWL_API_KEY(self):
|
||||
return _get_env("FIRECRAWL_API_KEY")
|
||||
|
||||
@property
|
||||
def NEMOTRON_MODEL(self):
|
||||
return _get_env("NEMOTRON_MODEL", default="NEMOTRON MODEL")
|
||||
|
||||
@property
|
||||
def NEMOTRON_API_KEY(self):
|
||||
return _get_env("NEMOTRON_API_KEY")
|
||||
|
||||
@property
|
||||
def NEMOTRON_BASE_URL(self):
|
||||
return _get_env("NEMOTRON_BASE_URL", default="https://openrouter.ai/api/v1")
|
||||
|
||||
MODEL = _get_env("GROQ_MODEL", "MODEL", default="llama-3.1-8b-instant")
|
||||
|
||||
OPENAI_MODEL = _get_env("OPENAI_MODEL", default="gpt-4o")
|
||||
|
||||
GEMINI_API_KEY = _get_env("GEMINI_API_KEY")
|
||||
|
||||
GEMINI_MODEL = _get_env("GEMINI_MODEL", default="gemini-3.5-flash-lite")
|
||||
|
||||
EMBEDDING_MODEL = _get_env(
|
||||
"EMBEDDING_MODEL",
|
||||
default="sentence-transformers/all-MiniLM-L6-v2",
|
||||
)
|
||||
|
||||
# EMBEDDING_PROVIDER controls which embedding backend is used.
|
||||
# Supported values: "openai" | "gemini" | "huggingface"
|
||||
# Default: auto-detected from EMBEDDING_MODEL name.
|
||||
EMBEDDING_PROVIDER = _get_env("EMBEDDING_PROVIDER", default="auto")
|
||||
|
||||
EMBEDDING_DIMENSION = int(_get_env("EMBEDDING_DIMENSION", default="384"))
|
||||
|
||||
CHUNK_SIZE = int(_get_env("CHUNK_SIZE", default="1000"))
|
||||
|
||||
CHUNK_OVERLAP = int(_get_env("CHUNK_OVERLAP", default="200"))
|
||||
|
||||
TOP_K = int(_get_env("TOP_K", default="5"))
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
embeddings.py — unified embedding provider routing.
|
||||
|
||||
Supported providers (set EMBEDDING_PROVIDER in .env):
|
||||
openai — OpenAI text-embedding-3-large / text-embedding-3-small / ada-002
|
||||
Requires: OPENAI_API_KEY
|
||||
Dimensions: 3072 (3-large), 1536 (3-small / ada-002)
|
||||
|
||||
gemini — Google text-embedding-004 (free tier, no credit card)
|
||||
Requires: GEMINI_API_KEY
|
||||
Dimensions: 768
|
||||
Free limits: 1500 RPD, 100 RPM
|
||||
|
||||
huggingface — Local sentence-transformers (no API key, runs on CPU)
|
||||
Default model: sentence-transformers/all-MiniLM-L6-v2
|
||||
Dimensions: 384
|
||||
Cost: free, but slower on first run (downloads model)
|
||||
|
||||
EMBEDDING_PROVIDER=auto (default):
|
||||
Detects from EMBEDDING_MODEL name:
|
||||
text-embedding-* → openai
|
||||
models/text-embedding-* or gemini-embedding-* → gemini
|
||||
anything else → huggingface
|
||||
|
||||
IMPORTANT — Pinecone index dimension must match:
|
||||
If you change provider/model, the existing Pinecone index must be
|
||||
recreated with the correct dimension. The system auto-recreates it
|
||||
if the dimension doesn't match.
|
||||
|
||||
Recommended .env for each provider:
|
||||
# OpenAI (paid)
|
||||
EMBEDDING_PROVIDER=openai
|
||||
EMBEDDING_MODEL=text-embedding-3-large
|
||||
EMBEDDING_DIMENSION=3072
|
||||
|
||||
# Gemini (free)
|
||||
EMBEDDING_PROVIDER=gemini
|
||||
EMBEDDING_MODEL=models/text-embedding-004
|
||||
EMBEDDING_DIMENSION=768
|
||||
|
||||
# HuggingFace (free, local)
|
||||
EMBEDDING_PROVIDER=huggingface
|
||||
EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2
|
||||
EMBEDDING_DIMENSION=384
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from config import settings
|
||||
|
||||
# ── Provider auto-detection ───────────────────────────────────────────────────
|
||||
_OPENAI_MODELS = {
|
||||
"text-embedding-3-large",
|
||||
"text-embedding-3-small",
|
||||
"text-embedding-ada-002",
|
||||
}
|
||||
|
||||
_GEMINI_MODELS = {
|
||||
"models/gemini-embedding-001",
|
||||
"models/gemini-embedding-2-preview",
|
||||
"models/gemini-embedding-2",
|
||||
"gemini-embedding-001",
|
||||
"gemini-embedding-2-preview",
|
||||
"gemini-embedding-2",
|
||||
# Legacy v1beta names (no longer valid but kept for detection)
|
||||
"models/text-embedding-004",
|
||||
"text-embedding-004",
|
||||
"gemini-embedding-exp-03-07",
|
||||
}
|
||||
|
||||
|
||||
def _detect_provider(model: str) -> str:
|
||||
"""Infer provider from model name when EMBEDDING_PROVIDER=auto."""
|
||||
m = model.lower()
|
||||
if m in {x.lower() for x in _OPENAI_MODELS} or m.startswith("text-embedding-3") or m == "text-embedding-ada-002":
|
||||
return "openai"
|
||||
if (m in {x.lower() for x in _GEMINI_MODELS}
|
||||
or "gemini-embedding" in m
|
||||
or m.startswith("models/gemini")):
|
||||
return "gemini"
|
||||
return "huggingface"
|
||||
|
||||
|
||||
_raw_provider = (settings.EMBEDDING_PROVIDER or "auto").strip().lower()
|
||||
_model = settings.EMBEDDING_MODEL or "sentence-transformers/all-MiniLM-L6-v2"
|
||||
|
||||
if _raw_provider == "auto":
|
||||
_provider = _detect_provider(_model)
|
||||
else:
|
||||
_provider = _raw_provider
|
||||
|
||||
|
||||
# ── Build the embeddings object ───────────────────────────────────────────────
|
||||
|
||||
if _provider == "openai":
|
||||
if not getattr(settings, "OPENAI_API_KEY", None):
|
||||
raise ValueError(
|
||||
"EMBEDDING_PROVIDER=openai requires OPENAI_API_KEY in .env. "
|
||||
"Switch to EMBEDDING_PROVIDER=gemini or huggingface to avoid this."
|
||||
)
|
||||
import os
|
||||
from langchain_openai import OpenAIEmbeddings
|
||||
os.environ["OPENAI_API_KEY"] = settings.OPENAI_API_KEY
|
||||
embeddings = OpenAIEmbeddings(
|
||||
model=_model,
|
||||
openai_api_key=settings.OPENAI_API_KEY,
|
||||
)
|
||||
|
||||
elif _provider == "gemini":
|
||||
if not getattr(settings, "GEMINI_API_KEY", None):
|
||||
raise ValueError(
|
||||
"EMBEDDING_PROVIDER=gemini requires GEMINI_API_KEY in .env. "
|
||||
"Get a free key at https://aistudio.google.com/app/apikey"
|
||||
)
|
||||
from langchain_google_genai import GoogleGenerativeAIEmbeddings
|
||||
# Ensure the model has the models/ prefix — required by the API
|
||||
_gem_model = _model if _model.startswith("models/") else f"models/{_model.split('/')[-1]}"
|
||||
embeddings = GoogleGenerativeAIEmbeddings(
|
||||
model=_gem_model,
|
||||
google_api_key=settings.GEMINI_API_KEY,
|
||||
)
|
||||
|
||||
else:
|
||||
# HuggingFace local — no API key needed
|
||||
from langchain_huggingface import HuggingFaceEmbeddings
|
||||
embeddings = HuggingFaceEmbeddings(model_name=_model)
|
||||
@@ -0,0 +1,121 @@
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from config import settings
|
||||
|
||||
|
||||
def _get_value(item, key, default=None):
|
||||
if isinstance(item, dict):
|
||||
return item.get(key, default)
|
||||
|
||||
return getattr(item, key, default)
|
||||
|
||||
|
||||
def _normalize_url(url, source_url):
|
||||
if not url:
|
||||
return ""
|
||||
|
||||
if url.startswith("//"):
|
||||
return f"https:{url}"
|
||||
|
||||
if url.startswith("http://") or url.startswith("https://"):
|
||||
return url
|
||||
|
||||
if source_url and url.startswith("/"):
|
||||
from urllib.parse import urljoin
|
||||
|
||||
return urljoin(source_url, url)
|
||||
|
||||
return url
|
||||
|
||||
|
||||
def _is_usable_image_url(url):
|
||||
if not url:
|
||||
return False
|
||||
|
||||
if not isinstance(url, str):
|
||||
return False
|
||||
|
||||
lowered = url.lower()
|
||||
|
||||
if lowered.startswith("data:") or lowered.endswith(".svg"):
|
||||
return False
|
||||
|
||||
return lowered.startswith("http://") or lowered.startswith("https://")
|
||||
|
||||
|
||||
def _extract_image_from_html(html, source_url):
|
||||
if not html:
|
||||
return ""
|
||||
|
||||
soup = BeautifulSoup(html, "lxml")
|
||||
|
||||
for selector in [
|
||||
("meta", {"property": "og:image"}),
|
||||
("meta", {"name": "twitter:image"}),
|
||||
]:
|
||||
tag = soup.find(*selector)
|
||||
image_url = tag.get("content") if tag else ""
|
||||
|
||||
if _is_usable_image_url(_normalize_url(image_url, source_url)):
|
||||
return _normalize_url(image_url, source_url)
|
||||
|
||||
for img in soup.find_all("img"):
|
||||
image_url = img.get("src") or img.get("data-src")
|
||||
normalized_url = _normalize_url(image_url, source_url)
|
||||
|
||||
if _is_usable_image_url(normalized_url):
|
||||
return normalized_url
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def search_images(query: str, limit: int = 3, context: str = "", placement: str = ""):
|
||||
try:
|
||||
from firecrawl import Firecrawl
|
||||
except ImportError:
|
||||
return []
|
||||
|
||||
firecrawl = Firecrawl(api_key=settings.FIRECRAWL_API_KEY)
|
||||
search_result = firecrawl.search(query, limit=max(limit * 3, 6))
|
||||
|
||||
web_results = _get_value(search_result, "web", []) or []
|
||||
images = []
|
||||
seen = set()
|
||||
|
||||
for item in web_results:
|
||||
if len(images) >= limit:
|
||||
break
|
||||
|
||||
page_url = _get_value(item, "url") or _get_value(item, "source_url")
|
||||
title = _get_value(item, "title", "Suggested image")
|
||||
description = _get_value(item, "description", "")
|
||||
direct_image = (
|
||||
_get_value(item, "image_url")
|
||||
or _get_value(item, "image")
|
||||
or _get_value(item, "thumbnail")
|
||||
)
|
||||
|
||||
if not page_url:
|
||||
continue
|
||||
|
||||
image_url = _normalize_url(direct_image, page_url)
|
||||
|
||||
if not _is_usable_image_url(image_url):
|
||||
continue
|
||||
|
||||
if not image_url or image_url in seen:
|
||||
continue
|
||||
|
||||
seen.add(image_url)
|
||||
images.append(
|
||||
{
|
||||
"url": image_url,
|
||||
"alt": title,
|
||||
"caption": description or title,
|
||||
"source_url": page_url,
|
||||
"context": context,
|
||||
"placement": placement,
|
||||
}
|
||||
)
|
||||
|
||||
return images
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
gemini_llm.py — Google Gemini LLM wrapper.
|
||||
|
||||
Uses langchain-google-genai which is the official LangChain integration
|
||||
for Google's Gemini API. Interface mirrors RotatingChatGroq so all agents
|
||||
use it transparently through llm_registry.make_llm().
|
||||
|
||||
Free tier (as of 2026):
|
||||
gemini-2.0-flash — 15 RPM, 250 000 TPM, 1 500 RPD (no credit card)
|
||||
gemini-1.5-flash — 15 RPM, 250 000 TPM, 1 500 RPD (fallback)
|
||||
|
||||
Install:
|
||||
pip install langchain-google-genai
|
||||
|
||||
Key must be set in .env:
|
||||
GEMINI_API_KEY=<your key from https://aistudio.google.com/app/apikey>
|
||||
GEMINI_MODEL=gemini-2.0-flash # optional — this is the default
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from config import settings as _settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_MODEL = "gemini-3.5-flash-lite"
|
||||
_FALLBACK_CHAIN = [
|
||||
"gemini-3.5-flash-lite",
|
||||
"gemini-3.5-flash",
|
||||
"gemini-3.6-flash",
|
||||
"gemini-3.7-flash",
|
||||
"gemini-2.5-flash",
|
||||
"gemini-flash-latest",
|
||||
]
|
||||
|
||||
_raw_gemini_model = getattr(_settings, "GEMINI_MODEL", None)
|
||||
if _raw_gemini_model and _raw_gemini_model.strip() in (
|
||||
"gemini-2.0-flash", "gemini-2.0-flash-exp", "models/gemini-2.0-flash",
|
||||
"gemini-2.5-flash-lite", "models/gemini-2.5-flash-lite"
|
||||
):
|
||||
logger.warning("Deprecated Gemini model '%s' specified. Migrating to '%s'.", _raw_gemini_model, _DEFAULT_MODEL)
|
||||
_ACTIVE_MODEL = _DEFAULT_MODEL
|
||||
else:
|
||||
_ACTIVE_MODEL = _raw_gemini_model or _DEFAULT_MODEL
|
||||
|
||||
|
||||
class GeminiChatLLM:
|
||||
"""
|
||||
Google Gemini wrapper matching the RotatingChatGroq / OpenAIChatLLM interface.
|
||||
|
||||
Exposes:
|
||||
self._client — raw LangChain ChatGoogleGenerativeAI instance
|
||||
self._invoke_chain() — rate-limit-aware invocation
|
||||
"""
|
||||
|
||||
def __init__(self, max_tokens: int = 700):
|
||||
self._max_tokens = max_tokens
|
||||
self._active_model = _ACTIVE_MODEL
|
||||
self._client = self._build()
|
||||
|
||||
def _build(self):
|
||||
from langchain_google_genai import ChatGoogleGenerativeAI
|
||||
model_name = self._active_model
|
||||
if model_name.startswith("models/"):
|
||||
model_name = model_name[len("models/"):]
|
||||
return ChatGoogleGenerativeAI(
|
||||
model=model_name,
|
||||
google_api_key=_settings.GEMINI_API_KEY,
|
||||
temperature=0.3,
|
||||
max_output_tokens=self._max_tokens,
|
||||
# Disable safety blocks that would reject blog content
|
||||
convert_system_message_to_human=True,
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
def _invoke_chain(self, chain, inputs: dict):
|
||||
"""
|
||||
Invoke with Gemini-specific error handling and dynamic model fallback.
|
||||
|
||||
429 / ResourceExhausted → try next fallback model in chain, then backoff.
|
||||
404 / Model not found → immediately switch to next fallback in chain.
|
||||
5xx server errors → short sleep then try next fallback.
|
||||
"""
|
||||
backoff = 10.0
|
||||
prompt_template = None
|
||||
if hasattr(chain, "steps") and len(chain.steps) > 0:
|
||||
prompt_template = chain.steps[0]
|
||||
|
||||
for attempt in range(len(_FALLBACK_CHAIN) * 2):
|
||||
try:
|
||||
if prompt_template is not None:
|
||||
runnable = prompt_template | self._client
|
||||
else:
|
||||
runnable = chain
|
||||
return runnable.invoke(inputs)
|
||||
|
||||
except Exception as exc:
|
||||
msg = str(exc).lower()
|
||||
|
||||
is_rate = (
|
||||
"429" in msg
|
||||
or "resource_exhausted" in msg
|
||||
or "quota" in msg
|
||||
or "rate limit" in msg
|
||||
)
|
||||
if is_rate:
|
||||
is_daily = (
|
||||
"limit: 0" in msg
|
||||
or "per day" in msg
|
||||
or "daily" in msg
|
||||
)
|
||||
if is_daily:
|
||||
if self._try_next_fallback():
|
||||
continue
|
||||
raise RuntimeError(
|
||||
"All Gemini models have exhausted their daily quota. "
|
||||
"Please upgrade your plan or try again tomorrow."
|
||||
) from exc
|
||||
|
||||
if self._try_next_fallback():
|
||||
continue
|
||||
wait = min(backoff * (2 ** (attempt % 3)), 60)
|
||||
logger.warning(
|
||||
"Gemini quota exhausted on all models (attempt %d) — waiting %.0fs.",
|
||||
attempt + 1, wait,
|
||||
)
|
||||
time.sleep(wait)
|
||||
continue
|
||||
|
||||
is_model_err = (
|
||||
"not found" in msg
|
||||
or "invalid model" in msg
|
||||
or "model_not_found" in msg
|
||||
or "404" in msg
|
||||
or "no longer available" in msg
|
||||
)
|
||||
if is_model_err:
|
||||
if self._try_next_fallback():
|
||||
continue
|
||||
|
||||
if "500" in msg or "503" in msg or "internal" in msg:
|
||||
time.sleep(5)
|
||||
if self._try_next_fallback():
|
||||
continue
|
||||
|
||||
raise
|
||||
|
||||
raise RuntimeError("Gemini request failed after maximum retries on all fallback models.")
|
||||
|
||||
def _try_next_fallback(self) -> bool:
|
||||
"""Switch to the next model in the fallback chain. Returns True if switched."""
|
||||
try:
|
||||
curr = self._active_model
|
||||
if curr.startswith("models/"):
|
||||
curr = curr[len("models/"):]
|
||||
clean_chain = [m[len("models/"):] if m.startswith("models/") else m for m in _FALLBACK_CHAIN]
|
||||
if curr in clean_chain:
|
||||
next_idx = clean_chain.index(curr) + 1
|
||||
else:
|
||||
next_idx = 0
|
||||
except Exception:
|
||||
next_idx = 0
|
||||
|
||||
if next_idx >= len(_FALLBACK_CHAIN):
|
||||
return False
|
||||
|
||||
next_model = _FALLBACK_CHAIN[next_idx]
|
||||
logger.warning("Gemini switching from %s → %s.", self._active_model, next_model)
|
||||
self._active_model = next_model
|
||||
self._client = self._build()
|
||||
return True
|
||||
|
||||
def _rotate(self) -> bool:
|
||||
"""Alias for _try_next_fallback for uniform streaming rotation."""
|
||||
return self._try_next_fallback()
|
||||
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
"""
|
||||
LLM factory with automatic model rotation.
|
||||
|
||||
Rotation pool — models with context sufficient for long outputs.
|
||||
Free-tier TPM limits (per model):
|
||||
llama-3.3-70b-versatile : ~6 000 TPM (use for analysis agents ≤700 output)
|
||||
llama-3.1-8b-instant : ~30 000 TPM (same)
|
||||
|
||||
IMPORTANT: aggregator and optimizer request 4 096 output tokens.
|
||||
With any Groq free-tier model that has an 8 000 TPM window, input must
|
||||
stay under 3 904 tokens. These two agents use the prose provider
|
||||
(Gemini / OpenAI) set by the user, NOT Groq, so they are unaffected by
|
||||
Groq TPM limits. All force_groq=True agents output ≤2 000 tokens and
|
||||
have input budgets well under 6 000 tokens total.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
|
||||
from langchain_groq import ChatGroq
|
||||
from groq import RateLimitError, APIStatusError, NotFoundError
|
||||
|
||||
from config import settings as _settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Rotation pool ──────────────────────────────────────────────────────────
|
||||
_MODEL_POOL: list[str] = [
|
||||
"llama-3.1-8b-instant",
|
||||
"llama-3.3-70b-versatile",
|
||||
]
|
||||
|
||||
# Per-model TPM caps (approximate free-tier limits).
|
||||
# Used to decide whether a 413 should rotate (model genuinely too small)
|
||||
# or sleep-and-retry (hit per-minute window on a capable model).
|
||||
_MODEL_TPM: dict[str, int] = {
|
||||
"llama-3.1-8b-instant": 30_000,
|
||||
"llama-3.3-70b-versatile": 6_000,
|
||||
}
|
||||
|
||||
_configured = _settings.MODEL
|
||||
_active_model: str = _configured if _configured in _MODEL_POOL else _MODEL_POOL[0]
|
||||
_exhausted: set[str] = set()
|
||||
|
||||
|
||||
def _next_model() -> str | None:
|
||||
for m in _MODEL_POOL:
|
||||
if m not in _exhausted:
|
||||
return m
|
||||
return None
|
||||
|
||||
|
||||
def _is_tpd(msg: str) -> bool:
|
||||
m = msg.lower()
|
||||
return "tokens per day" in m or "tpd" in m or "requests per day" in m or "rpd" in m
|
||||
|
||||
|
||||
def _is_tpm(msg: str) -> bool:
|
||||
m = msg.lower()
|
||||
return "tokens per minute" in m or "tpm" in m or "requests per minute" in m or "rpm" in m
|
||||
|
||||
|
||||
|
||||
def _parse_wait(msg: str) -> float | None:
|
||||
match = re.search(
|
||||
r"try again in\s+(?:(\d+)h)?(?:(\d+)m)?(?:([\d.]+)s)?",
|
||||
msg, re.IGNORECASE,
|
||||
)
|
||||
if not match or not any(match.groups()):
|
||||
return None
|
||||
return (
|
||||
float(match.group(1) or 0) * 3600
|
||||
+ float(match.group(2) or 0) * 60
|
||||
+ float(match.group(3) or 0)
|
||||
+ 1.0
|
||||
)
|
||||
|
||||
|
||||
class RotatingChatGroq:
|
||||
"""
|
||||
Wraps ChatGroq with transparent model rotation on TPD exhaustion.
|
||||
|
||||
Usage in agents:
|
||||
self.llm = make_llm(max_tokens=700)
|
||||
...
|
||||
response = invoke_with_retry(self.prompt, self.llm, inputs)
|
||||
|
||||
invoke_with_retry rebuilds `prompt | self.llm._client` on every call so
|
||||
the chain always references the currently active model.
|
||||
"""
|
||||
|
||||
def __init__(self, max_tokens: int = 700):
|
||||
self._max_tokens = max_tokens
|
||||
self._client: ChatGroq = self._build()
|
||||
|
||||
def _build(self) -> ChatGroq:
|
||||
return ChatGroq(
|
||||
model=_active_model,
|
||||
temperature=0.3,
|
||||
max_tokens=self._max_tokens,
|
||||
max_retries=2,
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
def _rotate(self) -> bool:
|
||||
global _active_model, _exhausted
|
||||
_exhausted.add(_active_model)
|
||||
logger.warning("Model %s TPD exhausted — rotating.", _active_model)
|
||||
nxt = _next_model()
|
||||
if nxt is None:
|
||||
return False
|
||||
_active_model = nxt
|
||||
self._client = self._build()
|
||||
logger.info("Active model → %s", _active_model)
|
||||
return True
|
||||
|
||||
def _invoke_chain(self, chain, inputs: dict):
|
||||
"""
|
||||
Invoke a pre-built chain with rotation + retry logic.
|
||||
Called by invoke_with_retry after it builds chain = prompt | self._client.
|
||||
"""
|
||||
tpm_attempt = 0
|
||||
tpm_base = 15.0
|
||||
|
||||
while True:
|
||||
try:
|
||||
return chain.invoke(inputs)
|
||||
|
||||
except RateLimitError as exc:
|
||||
msg = str(exc)
|
||||
|
||||
if _is_tpd(msg):
|
||||
rotated = self._rotate()
|
||||
if not rotated:
|
||||
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
|
||||
provider = get_provider()
|
||||
if provider == "groq":
|
||||
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
|
||||
provider = "gemini"
|
||||
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
|
||||
provider = "openai"
|
||||
if provider != "groq":
|
||||
logger.warning("Groq daily quota exhausted. Falling back dynamically to '%s'.", provider)
|
||||
if provider == "openai":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
|
||||
else: # gemini
|
||||
from config.gemini_llm import GeminiChatLLM
|
||||
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
|
||||
self._client = fallback_llm._client
|
||||
self._invoke_chain = fallback_llm._invoke_chain
|
||||
raise _RotationOccurred() from exc
|
||||
raise RuntimeError(
|
||||
"All Groq models have exhausted their daily quota. "
|
||||
"Try again tomorrow or upgrade your plan."
|
||||
) from exc
|
||||
# Rebuild the chain with the new model and retry
|
||||
chain = chain.first | self._client # type: ignore[attr-defined]
|
||||
# Simpler: let invoke_with_retry handle the rebuild on next call
|
||||
# by raising a sentinel that it catches
|
||||
raise _RotationOccurred() from exc
|
||||
|
||||
elif _is_tpm(msg):
|
||||
tpm_attempt += 1
|
||||
if tpm_attempt > 3:
|
||||
logger.warning("Max TPM retries (3) exceeded for model %s. Attempting model rotation or provider fallback.", _active_model)
|
||||
rotated = self._rotate()
|
||||
if not rotated:
|
||||
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
|
||||
provider = get_provider()
|
||||
if provider == "groq":
|
||||
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
|
||||
provider = "gemini"
|
||||
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
|
||||
provider = "openai"
|
||||
if provider != "groq":
|
||||
logger.warning("Groq TPM limit reached on all models. Falling back dynamically to '%s'.", provider)
|
||||
if provider == "openai":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
|
||||
else: # gemini
|
||||
from config.gemini_llm import GeminiChatLLM
|
||||
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
|
||||
self._client = fallback_llm._client
|
||||
self._invoke_chain = fallback_llm._invoke_chain
|
||||
raise _RotationOccurred() from exc
|
||||
raise RuntimeError(
|
||||
"Request size or rate exceeds Groq free tier model limits. "
|
||||
"Please select Gemini or OpenAI as your LLM Provider in settings."
|
||||
) from exc
|
||||
raise _RotationOccurred() from exc
|
||||
|
||||
wait = _parse_wait(msg) or min(tpm_base * (2 ** (tpm_attempt - 1)), 120)
|
||||
logger.warning("TPM limit (attempt %d/3) — waiting %.1fs.", tpm_attempt, wait)
|
||||
time.sleep(wait)
|
||||
# chain is still valid, retry same model
|
||||
|
||||
else:
|
||||
raise
|
||||
|
||||
except (APIStatusError, NotFoundError) as exc:
|
||||
status_code = getattr(exc, "status_code", None)
|
||||
if isinstance(exc, NotFoundError) or status_code == 404:
|
||||
msg = str(exc)
|
||||
logger.warning("HTTP 404 on %s: %s. Attempting model rotation or provider fallback.", _active_model, msg)
|
||||
rotated = self._rotate()
|
||||
if not rotated:
|
||||
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
|
||||
provider = get_provider()
|
||||
if provider == "groq":
|
||||
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
|
||||
provider = "gemini"
|
||||
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
|
||||
provider = "openai"
|
||||
if provider != "groq":
|
||||
logger.warning("Groq 404 on all models. Falling back dynamically to '%s'.", provider)
|
||||
if provider == "openai":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
|
||||
else:
|
||||
from config.gemini_llm import GeminiChatLLM
|
||||
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
|
||||
self._client = fallback_llm._client
|
||||
self._invoke_chain = fallback_llm._invoke_chain
|
||||
raise _RotationOccurred() from exc
|
||||
raise RuntimeError(
|
||||
f"Model {_active_model} was not found on Groq and no alternative provider is configured. "
|
||||
"Please check your Groq API key or select Gemini / OpenAI in settings."
|
||||
) from exc
|
||||
raise _RotationOccurred() from exc
|
||||
|
||||
if status_code == 413:
|
||||
msg = str(exc)
|
||||
logger.warning("HTTP 413 on %s: %s. Attempting model rotation or provider fallback.", _active_model, msg)
|
||||
rotated = self._rotate()
|
||||
if not rotated:
|
||||
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
|
||||
provider = get_provider()
|
||||
if provider == "groq":
|
||||
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
|
||||
provider = "gemini"
|
||||
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
|
||||
provider = "openai"
|
||||
if provider != "groq":
|
||||
logger.warning("Groq 413 limit reached on all models. Falling back dynamically to '%s'.", provider)
|
||||
if provider == "openai":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
|
||||
else: # gemini
|
||||
from config.gemini_llm import GeminiChatLLM
|
||||
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
|
||||
self._client = fallback_llm._client
|
||||
self._invoke_chain = fallback_llm._invoke_chain
|
||||
raise _RotationOccurred() from exc
|
||||
raise RuntimeError(
|
||||
"Request size exceeds the 8,000 TPM limit of Groq free tier models. "
|
||||
"Please select Gemini or OpenAI as your LLM Provider in settings."
|
||||
) from exc
|
||||
raise _RotationOccurred() from exc
|
||||
|
||||
if status_code and status_code < 500:
|
||||
raise
|
||||
time.sleep(10)
|
||||
raise
|
||||
|
||||
except Exception as exc:
|
||||
msg = str(exc).lower()
|
||||
if "model_not_found" in msg or "does not exist" in msg or "404" in msg or "invalid_request_error" in msg:
|
||||
logger.warning("Model error on %s: %s. Attempting model rotation or provider fallback.", _active_model, exc)
|
||||
rotated = self._rotate()
|
||||
if not rotated:
|
||||
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
|
||||
provider = get_provider()
|
||||
if provider == "groq":
|
||||
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
|
||||
provider = "gemini"
|
||||
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
|
||||
provider = "openai"
|
||||
if provider != "groq":
|
||||
logger.warning("Groq model error on all models. Falling back dynamically to '%s'.", provider)
|
||||
if provider == "openai":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
|
||||
else:
|
||||
from config.gemini_llm import GeminiChatLLM
|
||||
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
|
||||
self._client = fallback_llm._client
|
||||
self._invoke_chain = fallback_llm._invoke_chain
|
||||
raise _RotationOccurred() from exc
|
||||
raise RuntimeError(
|
||||
f"Model {_active_model} failed on Groq and no alternative provider is configured. "
|
||||
"Please check your Groq API key or select Gemini / OpenAI in settings."
|
||||
) from exc
|
||||
raise _RotationOccurred() from exc
|
||||
raise
|
||||
|
||||
|
||||
class _RotationOccurred(Exception):
|
||||
"""Internal sentinel: rotation happened, caller should rebuild chain and retry."""
|
||||
|
||||
|
||||
def make_llm(max_tokens: int = 700) -> RotatingChatGroq:
|
||||
"""
|
||||
Return a RotatingChatGroq with the given output token budget.
|
||||
|
||||
Budgets by role:
|
||||
specialist agents (language/facts/structure/seo/geo) : 700
|
||||
aggregator (editorial brief) : 800
|
||||
evaluator (JSON scores) : 500
|
||||
planner / learner (JSON) : 600
|
||||
researcher (research brief) : 2000
|
||||
optimizer (full article) : 3000
|
||||
"""
|
||||
return RotatingChatGroq(max_tokens=max_tokens)
|
||||
|
||||
|
||||
# Shared default for agents that `from config.llm import llm`
|
||||
llm = make_llm(max_tokens=700)
|
||||
@@ -0,0 +1,346 @@
|
||||
"""
|
||||
llm_registry.py — single import point for ALL agents.
|
||||
|
||||
Mixed-provider routing
|
||||
──────────────────────
|
||||
The UI-selected provider (Groq / Gemini / OpenAI) is the PROSE provider.
|
||||
It is used only for aggregator and optimizer — the two agents that write
|
||||
long-form article text and benefit most from a high-quality model.
|
||||
|
||||
All other agents (evaluators, specialists, researchers, learner, planner)
|
||||
always run on Groq regardless of the UI selection. This has two benefits:
|
||||
|
||||
1. Token cost: Gemini/OpenAI free-tier quota is preserved for prose only.
|
||||
A typical run uses ~9 000 tokens on the prose provider instead of
|
||||
~175 000 if every agent used it.
|
||||
|
||||
2. Speed: Groq is faster for short structured outputs (JSON scores,
|
||||
review notes, research briefs) than Gemini Flash or GPT-4o.
|
||||
|
||||
Usage in agents:
|
||||
# Prose agent — uses whatever provider the user selected
|
||||
llm = make_llm(max_tokens=4096)
|
||||
|
||||
# Analysis agent — always Groq, fast + free
|
||||
llm = make_llm(max_tokens=700, force_groq=True)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import os
|
||||
import logging
|
||||
import time
|
||||
|
||||
_lock = threading.Lock()
|
||||
_provider = "groq" # changed by set_provider() from Streamlit
|
||||
|
||||
|
||||
# ── Token budgets ──────────────────────────────────────────────────────────────
|
||||
_GROQ_MAX_TOKENS: dict[str, int] = {
|
||||
"small": 600,
|
||||
"medium": 1200,
|
||||
"large": 4096,
|
||||
}
|
||||
_OPENAI_MODEL: dict[str, str] = {
|
||||
"small": "gpt-4o-mini",
|
||||
"medium": "gpt-4o-mini",
|
||||
"large": "gpt-4o",
|
||||
}
|
||||
_OPENAI_MAX_TOKENS: dict[str, int] = {
|
||||
"small": 600,
|
||||
"medium": 1200,
|
||||
"large": 4096,
|
||||
}
|
||||
|
||||
|
||||
# ── Provider & Execution Mode management ──────────────────────────────────────
|
||||
|
||||
_execution_mode = "online" # "online" | "offline" | "hybrid"
|
||||
_local_engine = "ollama"
|
||||
_local_model_name = "qwen2.5:7b"
|
||||
_local_base_url = "http://localhost:11434/v1"
|
||||
_local_api_key = "ollama"
|
||||
|
||||
_custom_model_name = ""
|
||||
_custom_api_key = ""
|
||||
_custom_base_url = ""
|
||||
|
||||
|
||||
def set_execution_mode(
|
||||
mode: str = "online",
|
||||
local_engine: str = "ollama",
|
||||
local_model_name: str = "qwen2.5:7b",
|
||||
local_base_url: str = "http://localhost:11434/v1",
|
||||
local_api_key: str = "ollama",
|
||||
) -> None:
|
||||
global _execution_mode, _local_engine, _local_model_name, _local_base_url, _local_api_key
|
||||
with _lock:
|
||||
_execution_mode = (mode or "online").lower().strip()
|
||||
_local_engine = local_engine or "ollama"
|
||||
_local_model_name = local_model_name or "qwen2.5:7b"
|
||||
_local_base_url = local_base_url or "http://localhost:11434/v1"
|
||||
_local_api_key = local_api_key or "ollama"
|
||||
|
||||
|
||||
def set_custom_llm_settings(model_name: str, api_key: str, base_url: str) -> None:
|
||||
global _custom_model_name, _custom_api_key, _custom_base_url
|
||||
with _lock:
|
||||
_custom_model_name = model_name
|
||||
_custom_api_key = api_key
|
||||
_custom_base_url = base_url
|
||||
|
||||
|
||||
def set_provider(name: str) -> None:
|
||||
"""
|
||||
Switch the active prose provider globally.
|
||||
Called once from prepare_blog before the graph runs.
|
||||
Also clears OPENAI_API_KEY from the environment when not using OpenAI
|
||||
so LangChain internals don't auto-validate it and hit quota.
|
||||
"""
|
||||
global _provider
|
||||
allowed = {"groq", "openai", "gemini", "custom", "local", "ollama", "lmstudio"}
|
||||
name = name.lower().strip()
|
||||
if name not in allowed:
|
||||
raise ValueError(f"Unknown LLM provider '{name}'. Choose from: {allowed}")
|
||||
with _lock:
|
||||
_provider = name
|
||||
if name not in ("openai", "custom"):
|
||||
os.environ.pop("OPENAI_API_KEY", None)
|
||||
|
||||
|
||||
def _is_valid_gemini_key(key: str | None) -> bool:
|
||||
if not key: return False
|
||||
k = key.strip()
|
||||
return len(k) >= 15
|
||||
|
||||
def _is_valid_openai_key(key: str | None) -> bool:
|
||||
if not key: return False
|
||||
k = key.strip()
|
||||
return (k.startswith("sk-") or len(k) >= 20)
|
||||
|
||||
def get_provider() -> str:
|
||||
with _lock:
|
||||
return _provider
|
||||
|
||||
def get_execution_mode() -> str:
|
||||
with _lock:
|
||||
return _execution_mode
|
||||
|
||||
|
||||
# ── LLM factory ───────────────────────────────────────────────────────────────
|
||||
|
||||
def make_llm(max_tokens: int | None = None, size: str = "large", force_groq: bool = False):
|
||||
"""
|
||||
Factory used by every agent.
|
||||
|
||||
Supports:
|
||||
Online Mode: Analysis agents -> Groq (rotating), Prose -> Gemini/OpenAI/Groq
|
||||
Offline Mode: All agents -> LocalChatLLM (Ollama/LM Studio on GPU)
|
||||
Hybrid Mode: Analysis agents -> LocalChatLLM, Prose -> Cloud (Gemini/OpenAI)
|
||||
|
||||
Args:
|
||||
max_tokens: Explicit token budget. Overrides size preset if provided.
|
||||
size: "small" | "medium" | "large" — role-based token preset.
|
||||
force_groq: If True, flags this agent as an analysis/specialist agent.
|
||||
|
||||
Returns:
|
||||
LocalChatLLM | RotatingChatGroq | OpenAIChatLLM | GeminiChatLLM
|
||||
"""
|
||||
with _lock:
|
||||
provider = _provider
|
||||
mode = _execution_mode
|
||||
loc_model = _local_model_name
|
||||
loc_base = _local_base_url
|
||||
loc_key = _local_api_key
|
||||
|
||||
size = size if size in ("small", "medium", "large") else "large"
|
||||
tokens = max_tokens if max_tokens is not None else _GROQ_MAX_TOKENS[size]
|
||||
|
||||
# 1. 💻 100% Offline Mode — Route ALL agents to local GPU LLM
|
||||
if mode == "offline" or provider in ("local", "ollama", "lmstudio"):
|
||||
from config.local_llm import LocalChatLLM
|
||||
return LocalChatLLM(
|
||||
model=loc_model,
|
||||
base_url=loc_base,
|
||||
api_key=loc_key,
|
||||
max_tokens=tokens,
|
||||
)
|
||||
|
||||
# 2. 🔀 Hybrid Mode — Analysis on Local GPU, Prose on Cloud
|
||||
if mode == "hybrid" and force_groq:
|
||||
from config.local_llm import LocalChatLLM
|
||||
return LocalChatLLM(
|
||||
model=loc_model,
|
||||
base_url=loc_base,
|
||||
api_key=loc_key,
|
||||
max_tokens=tokens,
|
||||
)
|
||||
|
||||
# 3. 🌐 Online Cloud Mode (or Hybrid Prose)
|
||||
use_groq = force_groq or provider == "groq"
|
||||
if use_groq:
|
||||
import logging
|
||||
from config.llm import _MODEL_POOL, _exhausted
|
||||
from config import settings
|
||||
|
||||
fallback_provider = provider
|
||||
if fallback_provider == "groq":
|
||||
if _is_valid_gemini_key(settings.GEMINI_API_KEY):
|
||||
fallback_provider = "gemini"
|
||||
elif _is_valid_openai_key(settings.OPENAI_API_KEY):
|
||||
fallback_provider = "openai"
|
||||
|
||||
if len(_exhausted) >= len(_MODEL_POOL) and fallback_provider != "groq":
|
||||
logging.getLogger(__name__).warning("Groq is fully exhausted. Falling back to '%s' pre-emptively.", fallback_provider)
|
||||
use_groq = False
|
||||
provider = fallback_provider
|
||||
|
||||
if use_groq:
|
||||
from config.llm import RotatingChatGroq
|
||||
return RotatingChatGroq(max_tokens=tokens)
|
||||
|
||||
if provider == "custom":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
t_custom = max_tokens if max_tokens is not None else _OPENAI_MAX_TOKENS[size]
|
||||
with _lock:
|
||||
model = _custom_model_name
|
||||
api_key = _custom_api_key
|
||||
base_url = _custom_base_url
|
||||
return OpenAIChatLLM(max_tokens=t_custom, model_override=model, api_key=api_key, base_url=base_url)
|
||||
|
||||
if provider == "openai":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
t_openai = max_tokens if max_tokens is not None else _OPENAI_MAX_TOKENS[size]
|
||||
model = _OPENAI_MODEL[size]
|
||||
return OpenAIChatLLM(max_tokens=t_openai, model_override=model)
|
||||
|
||||
# gemini — prose provider
|
||||
from config.gemini_llm import GeminiChatLLM
|
||||
return GeminiChatLLM(max_tokens=tokens)
|
||||
|
||||
|
||||
# ── Streaming invoke ───────────────────────────────────────────────────────────
|
||||
|
||||
def stream_invoke(prompt, llm, inputs: dict, chunk_callback) -> str:
|
||||
"""
|
||||
Streaming invoke used by aggregator and optimizer.
|
||||
Handles retries, model rotation, and dynamic provider fallbacks for RotatingChatGroq.
|
||||
"""
|
||||
from utilis.retry import invoke_with_retry
|
||||
try:
|
||||
from config.llm import _RotationOccurred
|
||||
except ImportError:
|
||||
_RotationOccurred = type("_RotationOccurred", (Exception,), {})
|
||||
try:
|
||||
from groq import RateLimitError, APIStatusError as GroqAPIStatusError
|
||||
except ImportError:
|
||||
RateLimitError = GroqAPIStatusError = None
|
||||
|
||||
tpm_attempt = 0
|
||||
tpm_base = 15.0
|
||||
|
||||
while True:
|
||||
try:
|
||||
chain = prompt | llm._client
|
||||
full_text = ""
|
||||
for chunk in chain.stream(inputs):
|
||||
raw_token = chunk.content if hasattr(chunk, "content") else chunk
|
||||
if isinstance(raw_token, list):
|
||||
extracted = []
|
||||
for item in raw_token:
|
||||
if isinstance(item, dict) and "text" in item:
|
||||
extracted.append(item["text"])
|
||||
elif isinstance(item, str):
|
||||
extracted.append(item)
|
||||
token = "".join(extracted)
|
||||
elif isinstance(raw_token, str):
|
||||
token = raw_token
|
||||
else:
|
||||
token = str(raw_token) if raw_token is not None else ""
|
||||
|
||||
if token:
|
||||
chunk_callback(token)
|
||||
full_text += token
|
||||
try:
|
||||
from utilis.token_counter import add_tokens
|
||||
p_tok = len(str(inputs)) // 4
|
||||
c_tok = len(full_text) // 4
|
||||
add_tokens(p_tok, c_tok)
|
||||
except Exception:
|
||||
pass
|
||||
return full_text
|
||||
|
||||
except Exception as exc:
|
||||
err_msg = str(exc).lower()
|
||||
|
||||
if isinstance(exc, _RotationOccurred):
|
||||
continue
|
||||
|
||||
if hasattr(llm, "_rotate") and hasattr(llm, "_invoke_chain"):
|
||||
if RateLimitError and isinstance(exc, RateLimitError):
|
||||
from config.llm import _is_tpd, _is_tpm, _parse_wait
|
||||
if _is_tpd(err_msg):
|
||||
rotated = llm._rotate()
|
||||
if not rotated:
|
||||
provider = get_provider()
|
||||
if provider == "groq":
|
||||
from config import settings
|
||||
if settings.GEMINI_API_KEY:
|
||||
provider = "gemini"
|
||||
elif settings.OPENAI_API_KEY:
|
||||
provider = "openai"
|
||||
if provider != "groq":
|
||||
logging.getLogger(__name__).warning("Groq daily quota exhausted. Falling back dynamically to '%s'.", provider)
|
||||
if provider == "openai":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
fallback_llm = OpenAIChatLLM(max_tokens=getattr(llm, "_max_tokens", 3500))
|
||||
else:
|
||||
from config.gemini_llm import GeminiChatLLM
|
||||
fallback_llm = GeminiChatLLM(max_tokens=getattr(llm, "_max_tokens", 3500))
|
||||
llm._client = fallback_llm._client
|
||||
llm._invoke_chain = fallback_llm._invoke_chain
|
||||
continue
|
||||
raise RuntimeError("All Groq models have exhausted their daily quota. Try again tomorrow or upgrade your plan.") from exc
|
||||
continue
|
||||
elif _is_tpm(err_msg):
|
||||
tpm_attempt += 1
|
||||
wait = _parse_wait(err_msg) or min(tpm_base * (2 ** (tpm_attempt - 1)), 120)
|
||||
logging.getLogger(__name__).warning("TPM limit in streaming — waiting %.1fs.", wait)
|
||||
time.sleep(wait)
|
||||
continue
|
||||
|
||||
if GroqAPIStatusError and isinstance(exc, GroqAPIStatusError) and getattr(exc, "status_code", None) in (404, 413):
|
||||
status_code = getattr(exc, "status_code", None)
|
||||
logging.getLogger(__name__).warning("HTTP %s on Groq in streaming (%s). Attempting model rotation or provider fallback.", status_code, err_msg)
|
||||
rotated = llm._rotate()
|
||||
if not rotated:
|
||||
provider = get_provider()
|
||||
if provider == "groq":
|
||||
from config import settings
|
||||
if settings.GEMINI_API_KEY:
|
||||
provider = "gemini"
|
||||
elif settings.OPENAI_API_KEY:
|
||||
provider = "openai"
|
||||
if provider != "groq":
|
||||
logging.getLogger(__name__).warning("413 on Groq: all Groq models exhausted/too small. Falling back dynamically to '%s'.", provider)
|
||||
if provider == "openai":
|
||||
from config.openai_llm import OpenAIChatLLM
|
||||
fallback_llm = OpenAIChatLLM(max_tokens=getattr(llm, "_max_tokens", 3500))
|
||||
else:
|
||||
from config.gemini_llm import GeminiChatLLM
|
||||
fallback_llm = GeminiChatLLM(max_tokens=getattr(llm, "_max_tokens", 3500))
|
||||
llm._client = fallback_llm._client
|
||||
llm._invoke_chain = fallback_llm._invoke_chain
|
||||
continue
|
||||
raise RuntimeError("Request size exceeds the 8,000 TPM limit of Groq free tier models. Please select Gemini or OpenAI as your LLM Provider in settings.") from exc
|
||||
continue
|
||||
|
||||
# Fall back for streaming-not-supported type errors
|
||||
if any(k in err_msg for k in ("stream", "not support", "chunk")):
|
||||
response = invoke_with_retry(prompt, llm, inputs)
|
||||
text = response.content if hasattr(response, "content") else str(response)
|
||||
chunk_callback(text)
|
||||
return text
|
||||
|
||||
raise
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
local_llm.py — Local / Offline LLM adapter and discovery utilities.
|
||||
|
||||
Supports:
|
||||
1. Ollama (default: http://localhost:11434)
|
||||
2. LM Studio / vLLM / llama.cpp (default: http://localhost:1234/v1)
|
||||
3. Custom Local OpenAI-compatible server
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import requests
|
||||
from typing import List, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Default endpoints
|
||||
OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434"
|
||||
LMSTUDIO_DEFAULT_BASE_URL = "http://localhost:1234/v1"
|
||||
|
||||
|
||||
def discover_ollama_models(base_url: str = OLLAMA_DEFAULT_BASE_URL) -> Tuple[bool, List[str], str]:
|
||||
"""
|
||||
Queries Ollama's API (/api/tags) to list all locally installed models.
|
||||
Returns: (is_connected: bool, model_names: list[str], message: str)
|
||||
"""
|
||||
clean_url = base_url.rstrip("/")
|
||||
if clean_url.endswith("/v1"):
|
||||
clean_url = clean_url[:-3]
|
||||
|
||||
try:
|
||||
resp = requests.get(f"{clean_url}/api/tags", timeout=1.5)
|
||||
if resp.status_code == 200:
|
||||
data = resp.json()
|
||||
models = [m.get("name") for m in data.get("models", []) if m.get("name")]
|
||||
if models:
|
||||
return True, models, f"Connected ({len(models)} model(s) found)"
|
||||
return True, ["qwen2.5:7b", "llama3.2", "mistral"], "Connected (no models pulled yet)"
|
||||
return False, [], f"HTTP {resp.status_code}"
|
||||
except Exception as e:
|
||||
return False, [], f"Not reachable: {e.__class__.__name__}"
|
||||
|
||||
|
||||
def discover_lmstudio_models(base_url: str = LMSTUDIO_DEFAULT_BASE_URL) -> Tuple[bool, List[str], str]:
|
||||
"""
|
||||
Queries LM Studio / vLLM / Local OpenAI-compatible API (/v1/models).
|
||||
Returns: (is_connected: bool, model_names: list[str], message: str)
|
||||
"""
|
||||
clean_url = base_url.rstrip("/")
|
||||
if not clean_url.endswith("/v1"):
|
||||
endpoint = f"{clean_url}/v1/models"
|
||||
else:
|
||||
endpoint = f"{clean_url}/models"
|
||||
|
||||
try:
|
||||
resp = requests.get(endpoint, timeout=1.5)
|
||||
if resp.status_code == 200:
|
||||
data = resp.json()
|
||||
models = [m.get("id") for m in data.get("data", []) if m.get("id")]
|
||||
if models:
|
||||
return True, models, f"Connected ({len(models)} model(s) loaded)"
|
||||
return True, ["local-model"], "Connected"
|
||||
return False, [], f"HTTP {resp.status_code}"
|
||||
except Exception as e:
|
||||
return False, [], f"Not reachable: {e.__class__.__name__}"
|
||||
|
||||
|
||||
class LocalChatLLM:
|
||||
"""
|
||||
LangChain-compatible wrapper for local LLM engines (Ollama, LM Studio, vLLM).
|
||||
Uses ChatOpenAI pointed at local base_url.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: str = "qwen2.5:7b",
|
||||
base_url: str = "http://localhost:11434/v1",
|
||||
api_key: str = "ollama",
|
||||
temperature: float = 0.3,
|
||||
max_tokens: int = 3500,
|
||||
timeout: int = 120,
|
||||
):
|
||||
self.model = model or "qwen2.5:7b"
|
||||
self.base_url = base_url or "http://localhost:11434/v1"
|
||||
self.api_key = api_key or "ollama"
|
||||
self.temperature = temperature
|
||||
self._max_tokens = max_tokens
|
||||
self.timeout = timeout
|
||||
self._client = self._build()
|
||||
|
||||
def _build(self):
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
# Ensure base_url ends with /v1
|
||||
b_url = self.base_url.rstrip("/")
|
||||
if not b_url.endswith("/v1"):
|
||||
b_url = f"{b_url}/v1"
|
||||
|
||||
return ChatOpenAI(
|
||||
model=self.model,
|
||||
base_url=b_url,
|
||||
api_key=self.api_key or "ollama",
|
||||
temperature=self.temperature,
|
||||
max_tokens=self._max_tokens,
|
||||
timeout=self.timeout,
|
||||
extra_body={"options": {"num_gpu": 99, "num_ctx": 4096}},
|
||||
)
|
||||
|
||||
def _invoke_chain(self, chain, inputs: dict):
|
||||
"""Invoke local LLM with helpful connection error messaging."""
|
||||
try:
|
||||
return chain.invoke(inputs)
|
||||
except Exception as exc:
|
||||
msg = str(exc)
|
||||
err_lower = msg.lower()
|
||||
if any(k in err_lower for k in ("connection error", "connect", "connection refused", "target machine actively refused", "failed to establish a new connection")):
|
||||
clean_url = self.base_url.replace("/v1", "")
|
||||
raise RuntimeError(
|
||||
f"Cannot connect to local LLM server at '{self.base_url}'. "
|
||||
f"Please make sure your local engine ({clean_url}) is running, "
|
||||
f"or switch 'Execution Mode' to 'Online Cloud' in the sidebar."
|
||||
) from exc
|
||||
logger.error("Local LLM invocation error on model '%s' (%s): %s", self.model, self.base_url, exc)
|
||||
raise
|
||||
|
||||
def _rotate(self) -> bool:
|
||||
"""No-op rotate for local LLMs."""
|
||||
return False
|
||||
@@ -0,0 +1,11 @@
|
||||
import logging
|
||||
|
||||
logging.basicConfig(
|
||||
|
||||
level=logging.INFO,
|
||||
|
||||
format="%(asctime)s | %(levelname)s | %(message)s"
|
||||
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -0,0 +1,190 @@
|
||||
import json
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
from openai import OpenAI
|
||||
import requests
|
||||
|
||||
from config import settings
|
||||
|
||||
|
||||
IMAGE_DIR = Path(__file__).resolve().parents[1] / "generated_images"
|
||||
|
||||
|
||||
def _client():
|
||||
if not settings.NEMOTRON_API_KEY or not settings.NEMOTRON_MODEL:
|
||||
return None
|
||||
|
||||
return OpenAI(
|
||||
api_key=settings.NEMOTRON_API_KEY,
|
||||
base_url=settings.NEMOTRON_BASE_URL,
|
||||
timeout=60.0,
|
||||
)
|
||||
|
||||
|
||||
def _candidate_text(candidates):
|
||||
lines = []
|
||||
|
||||
for index, candidate in enumerate(candidates, start=1):
|
||||
lines.append(
|
||||
"\n".join(
|
||||
[
|
||||
f"{index}. URL: {candidate.get('url', '')}",
|
||||
f"Alt: {candidate.get('alt', '')}",
|
||||
f"Caption: {candidate.get('caption', '')}",
|
||||
f"Source: {candidate.get('source_url', '')}",
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def _parse_selection(content, candidates, limit):
|
||||
try:
|
||||
payload = json.loads(content)
|
||||
except json.JSONDecodeError:
|
||||
# Bad JSON from the model — return nothing rather than a random candidate
|
||||
return []
|
||||
|
||||
selected = payload.get("selected_images", payload if isinstance(payload, list) else [])
|
||||
ranked = []
|
||||
|
||||
for item in selected:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
|
||||
index = item.get("index")
|
||||
score = item.get("score", 0)
|
||||
|
||||
# Hard threshold: below 60 means the model itself considers it irrelevant
|
||||
try:
|
||||
if int(score) < 60:
|
||||
continue
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
try:
|
||||
candidate = candidates[int(index) - 1].copy()
|
||||
except (TypeError, ValueError, IndexError):
|
||||
continue
|
||||
|
||||
candidate["relevance_score"] = score
|
||||
candidate["relevance_reason"] = item.get("reason", "")
|
||||
candidate["alt"] = item.get("alt") or candidate.get("alt")
|
||||
candidate["caption"] = item.get("caption") or candidate.get("caption")
|
||||
ranked.append(candidate)
|
||||
|
||||
# Do NOT fall back to candidates[:limit] — return empty if nothing passes
|
||||
return ranked[:limit]
|
||||
|
||||
|
||||
def _vision_content(prompt, candidates):
|
||||
content = [{"type": "text", "text": prompt}]
|
||||
|
||||
for index, candidate in enumerate(candidates[:6], start=1):
|
||||
content.append({"type": "text", "text": f"Candidate {index}"})
|
||||
content.append(
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": candidate.get("url", "")},
|
||||
}
|
||||
)
|
||||
|
||||
return content
|
||||
|
||||
|
||||
def select_relevant_images(context, section, candidates, limit=1):
|
||||
if not candidates:
|
||||
return []
|
||||
|
||||
from config.llm_registry import make_llm
|
||||
from utilis.retry import invoke_with_retry
|
||||
from langchain_core.prompts import ChatPromptTemplate
|
||||
|
||||
prompt = f"""
|
||||
You are a strict editorial image reviewer for a professional business blog.
|
||||
|
||||
Blog topic: {section}
|
||||
|
||||
Section context (the text this image must illustrate):
|
||||
{context}
|
||||
|
||||
Image candidates:
|
||||
{_candidate_text(candidates)}
|
||||
|
||||
RULES:
|
||||
- Only select an image if it DIRECTLY illustrates the section context above.
|
||||
- The image must be a photograph, diagram, infographic, or chart relevant to the blog topic.
|
||||
- REJECT any image that shows: people (unless they are clearly in a business/workplace context), entertainment, sports, martial arts, movies, TV shows, celebrities, cartoon characters, food, nature scenes unrelated to the topic, or anything that a reader would find confusing next to this blog section.
|
||||
- A score below 60 means REJECT — do not include it.
|
||||
- If NO candidate is relevant enough, return an empty selected_images array.
|
||||
|
||||
Return ONLY JSON:
|
||||
{{
|
||||
"selected_images": [
|
||||
{{
|
||||
"index": 1,
|
||||
"score": 0-100,
|
||||
"reason": "why this image fits the section context",
|
||||
"alt": "descriptive alt text for the image",
|
||||
"caption": "short caption for display under the image"
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
If nothing is suitable, return: {{"selected_images": []}}
|
||||
"""
|
||||
|
||||
try:
|
||||
llm = make_llm(max_tokens=800, force_groq=True)
|
||||
chat_prompt = ChatPromptTemplate.from_messages([("human", prompt)])
|
||||
response = invoke_with_retry(chat_prompt, llm, {})
|
||||
content = response.content or ""
|
||||
except Exception:
|
||||
return candidates[:limit]
|
||||
|
||||
return _parse_selection(content, candidates, limit)
|
||||
|
||||
|
||||
def download_image(image, section):
|
||||
url = image.get("url")
|
||||
if not url:
|
||||
return image
|
||||
|
||||
IMAGE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
safe_section = "".join(
|
||||
character.lower() if character.isalnum() else "-"
|
||||
for character in section
|
||||
).strip("-")[:50] or "blog-image"
|
||||
|
||||
try:
|
||||
response = requests.get(url, timeout=8, headers={"User-Agent": "Mozilla/5.0"})
|
||||
response.raise_for_status()
|
||||
# Reject tiny icons, tracking pixels, and empty responses (< 3500 bytes)
|
||||
if len(response.content) < 3500:
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
content_type = response.headers.get("content-type", "").split(";")[0]
|
||||
extension = {
|
||||
"image/jpeg": ".jpg",
|
||||
"image/jpg": ".jpg",
|
||||
"image/png": ".png",
|
||||
"image/webp": ".webp",
|
||||
"image/gif": ".gif",
|
||||
}.get(content_type, ".jpg")
|
||||
|
||||
content_hash = hashlib.md5(response.content).hexdigest()
|
||||
file_name = f"{safe_section}-{content_hash[:12]}{extension}"
|
||||
file_path = IMAGE_DIR / file_name
|
||||
file_path.write_bytes(response.content)
|
||||
|
||||
image["remote_url"] = url
|
||||
image["local_path"] = file_path.as_posix()
|
||||
image["url"] = file_path.as_posix()
|
||||
image["content_hash"] = content_hash
|
||||
image["byte_size"] = len(response.content)
|
||||
|
||||
return image
|
||||
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
openai_llm.py — OpenAI GPT-4 LLM wrapper.
|
||||
|
||||
Provides an OpenAIChatLLM class whose interface matches RotatingChatGroq
|
||||
so every agent can use it transparently through the shared registry.
|
||||
|
||||
Supported models (override via OPENAI_MODEL in .env):
|
||||
gpt-4o — default, best quality, 128K context
|
||||
gpt-4-turbo — faster, slightly cheaper
|
||||
gpt-4 — original GPT-4
|
||||
gpt-3.5-turbo — fallback / cost saving
|
||||
|
||||
Token limits are set per-call via max_tokens, same as Groq.
|
||||
OpenAI does not have a per-minute rotation requirement — it uses
|
||||
standard 429 rate-limit handling with exponential back-off.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from langchain_openai import ChatOpenAI
|
||||
from openai import RateLimitError, APIStatusError
|
||||
|
||||
from config import settings as _settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Default model — can be overridden in .env as OPENAI_MODEL
|
||||
_DEFAULT_MODEL = "gpt-4o"
|
||||
_ACTIVE_MODEL = getattr(_settings, "OPENAI_MODEL", None) or _DEFAULT_MODEL
|
||||
|
||||
# Available models in priority order (used if the primary hits a hard cap)
|
||||
_MODEL_POOL = [
|
||||
"gpt-4o",
|
||||
"gpt-4-turbo",
|
||||
"gpt-4",
|
||||
"gpt-3.5-turbo",
|
||||
]
|
||||
|
||||
|
||||
class OpenAIChatLLM:
|
||||
"""
|
||||
OpenAI LLM wrapper that mirrors the RotatingChatGroq interface.
|
||||
|
||||
Agents call it exactly the same way:
|
||||
self.llm = make_llm(max_tokens=700) # from llm_registry
|
||||
response = invoke_with_retry(prompt, self.llm, inputs)
|
||||
|
||||
Internally exposes:
|
||||
self._client — the raw ChatOpenAI instance (used by invoke_with_retry)
|
||||
self._invoke_chain(chain, inputs) — rate-limit aware invocation
|
||||
"""
|
||||
|
||||
def __init__(self, max_tokens: int = 700, model_override: str | None = None, api_key: str | None = None, base_url: str | None = None):
|
||||
self._max_tokens = max_tokens
|
||||
self._active_model = model_override or _ACTIVE_MODEL
|
||||
self._api_key = api_key or _settings.OPENAI_API_KEY
|
||||
self._base_url = base_url
|
||||
self._client: ChatOpenAI = self._build()
|
||||
|
||||
def _build(self) -> ChatOpenAI:
|
||||
kwargs = {
|
||||
"model": self._active_model,
|
||||
"temperature": 0.3,
|
||||
"max_tokens": self._max_tokens,
|
||||
"max_retries": 2,
|
||||
"api_key": self._api_key,
|
||||
"timeout": 60,
|
||||
}
|
||||
if self._base_url:
|
||||
kwargs["base_url"] = self._base_url
|
||||
return ChatOpenAI(**kwargs)
|
||||
|
||||
def _invoke_chain(self, chain, inputs: dict):
|
||||
"""
|
||||
Invoke a pre-built chain with OpenAI-specific rate-limit handling.
|
||||
|
||||
429 RateLimitError → exponential back-off up to 120 s then re-raise.
|
||||
413 / context-length errors → try falling back to a smaller model.
|
||||
5xx errors → short sleep then re-raise.
|
||||
"""
|
||||
backoff = 10.0
|
||||
max_wait = 120.0
|
||||
|
||||
for attempt in range(6):
|
||||
try:
|
||||
return chain.invoke(inputs)
|
||||
|
||||
except RateLimitError as exc:
|
||||
if attempt >= 5:
|
||||
raise
|
||||
wait = min(backoff * (2 ** attempt), max_wait)
|
||||
logger.warning(
|
||||
"OpenAI RateLimitError (attempt %d) — waiting %.0fs.",
|
||||
attempt + 1, wait,
|
||||
)
|
||||
time.sleep(wait)
|
||||
|
||||
except APIStatusError as exc:
|
||||
# Context length exceeded — try a model with larger context
|
||||
if exc.status_code in (400, 413):
|
||||
next_model = self._fallback_model()
|
||||
if next_model:
|
||||
logger.warning(
|
||||
"OpenAI %d on %s — falling back to %s.",
|
||||
exc.status_code, self._active_model, next_model,
|
||||
)
|
||||
self._active_model = next_model
|
||||
self._client = self._build()
|
||||
chain = chain.first | self._client # type: ignore[attr-defined]
|
||||
continue
|
||||
if exc.status_code >= 500:
|
||||
time.sleep(10)
|
||||
raise
|
||||
|
||||
raise RuntimeError("OpenAI request failed after maximum retries.")
|
||||
|
||||
def _fallback_model(self) -> str | None:
|
||||
"""Return the next model in the pool after the currently active one."""
|
||||
try:
|
||||
idx = _MODEL_POOL.index(self._active_model)
|
||||
return _MODEL_POOL[idx + 1] if idx + 1 < len(_MODEL_POOL) else None
|
||||
except ValueError:
|
||||
return _MODEL_POOL[0]
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
pinecone_manager.py
|
||||
|
||||
Creates or retrieves the Pinecone index.
|
||||
|
||||
Auto-recreation: if an existing index was built with a different dimension
|
||||
(e.g. 3072 for OpenAI but now using Gemini at 768), the old index is deleted
|
||||
and a new one is created with the correct dimension. All previously ingested
|
||||
vectors are lost — the next ingest_blog() call will repopulate it.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from pinecone import Pinecone, ServerlessSpec
|
||||
|
||||
from config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
pc = Pinecone(api_key=settings.PINECONE_API_KEY)
|
||||
INDEX_NAME = settings.PINECONE_INDEX_NAME
|
||||
DIMENSION = settings.EMBEDDING_DIMENSION
|
||||
|
||||
|
||||
def get_or_create_index():
|
||||
existing = {i.name: i for i in pc.list_indexes()}
|
||||
|
||||
if INDEX_NAME in existing:
|
||||
index_info = existing[INDEX_NAME]
|
||||
# Check dimension match — access via dict-style or attribute
|
||||
try:
|
||||
stored_dim = (
|
||||
index_info.dimension # pinecone-client ≥ 3
|
||||
if hasattr(index_info, "dimension")
|
||||
else index_info["dimension"] # older client
|
||||
)
|
||||
except Exception:
|
||||
stored_dim = None
|
||||
|
||||
if stored_dim is not None and int(stored_dim) != int(DIMENSION):
|
||||
logger.warning(
|
||||
"Pinecone index '%s' has dimension %d but current embedding "
|
||||
"model requires %d. Deleting and recreating the index.",
|
||||
INDEX_NAME, stored_dim, DIMENSION,
|
||||
)
|
||||
pc.delete_index(INDEX_NAME)
|
||||
else:
|
||||
return pc.Index(INDEX_NAME)
|
||||
|
||||
pc.create_index(
|
||||
name=INDEX_NAME,
|
||||
dimension=DIMENSION,
|
||||
metric="cosine",
|
||||
spec=ServerlessSpec(cloud="aws", region="us-east-1"),
|
||||
)
|
||||
return pc.Index(INDEX_NAME)
|
||||
@@ -0,0 +1,106 @@
|
||||
import logging
|
||||
|
||||
from tavily import TavilyClient
|
||||
from config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_QUERY_LENGTH = 390
|
||||
|
||||
|
||||
def _get_client():
|
||||
key = settings.TAVILY_API_KEY
|
||||
if not key:
|
||||
return None
|
||||
return TavilyClient(api_key=key)
|
||||
|
||||
|
||||
def _limit_query(query, max_length=MAX_QUERY_LENGTH):
|
||||
query = " ".join(str(query).split())
|
||||
|
||||
if len(query) <= max_length:
|
||||
return query
|
||||
|
||||
return query[:max_length].rsplit(" ", 1)[0].strip()
|
||||
|
||||
|
||||
def search(query, max_results=5, search_depth="advanced"):
|
||||
client = _get_client()
|
||||
if not client:
|
||||
logger.warning("Tavily API key not found.")
|
||||
return {"results": []}
|
||||
|
||||
try:
|
||||
response = client.search(
|
||||
query=_limit_query(query),
|
||||
max_results=max_results,
|
||||
search_depth=search_depth
|
||||
)
|
||||
return response
|
||||
except Exception as exc:
|
||||
logger.warning("Tavily search error: %s", exc)
|
||||
return {"results": []}
|
||||
|
||||
|
||||
def search_image_candidates(query, max_results=8, search_depth="advanced"):
|
||||
client = _get_client()
|
||||
if not client:
|
||||
logger.warning("Tavily API key not found.")
|
||||
return []
|
||||
|
||||
try:
|
||||
response = client.search(
|
||||
query=_limit_query(query),
|
||||
max_results=max_results,
|
||||
search_depth=search_depth,
|
||||
include_images=True,
|
||||
include_image_descriptions=True
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Tavily image search error: %s", exc)
|
||||
response = {}
|
||||
|
||||
images = response.get("images", []) if isinstance(response, dict) else []
|
||||
candidates = []
|
||||
seen = set()
|
||||
|
||||
for image in images:
|
||||
if isinstance(image, str):
|
||||
image_url = image
|
||||
description = ""
|
||||
else:
|
||||
image_url = image.get("url") or image.get("image_url")
|
||||
description = image.get("description") or image.get("alt") or ""
|
||||
|
||||
if not image_url or image_url in seen:
|
||||
continue
|
||||
|
||||
seen.add(image_url)
|
||||
candidates.append(
|
||||
{
|
||||
"url": image_url,
|
||||
"alt": description,
|
||||
"caption": description,
|
||||
"source_url": image_url,
|
||||
}
|
||||
)
|
||||
|
||||
results = response.get("results", []) if isinstance(response, dict) else []
|
||||
|
||||
for result in results:
|
||||
image_url = result.get("image_url") or result.get("thumbnail")
|
||||
|
||||
if not image_url or image_url in seen:
|
||||
continue
|
||||
|
||||
seen.add(image_url)
|
||||
candidates.append(
|
||||
{
|
||||
"url": image_url,
|
||||
"alt": result.get("title", ""),
|
||||
"caption": result.get("content", "") or result.get("title", ""),
|
||||
"source_url": result.get("url") or image_url,
|
||||
}
|
||||
)
|
||||
|
||||
return candidates
|
||||
Reference in New Issue
Block a user