feat: initial commit for Blog Expert multi-agent system

This commit is contained in:
2026-10-16 11:59:15 +05:30
commit 1f952ded52
79 changed files with 9156 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm, stream_invoke
from utilis.prompt_loader import load_prompt
prompt = ChatPromptTemplate.from_messages([
("system", f"{load_prompt('aggregator.txt')}\n\n{load_prompt('images.txt')}"),
("human", (
"Original Blog\n\n{blog}"
"\n\nLanguage Notes\n\n{language}"
"\n\nFacts Notes\n\n{facts}"
"\n\nStructure Notes\n\n{structure}"
"\n\nSEO Notes\n\n{seo}"
"\n\nGEO Notes\n\n{geo}"
"\n\nImages\n\n{images}"
"\n\nDate: {current_date} | Year: {current_year}"
"\n\nQuality: {language_quality} | Length: {target_length}"
)),
])
# Input budget per field (chars). Total input ~10 000 chars = ~2 857 tokens.
# With aggregator.txt (~5 315 chars = ~1 519 tokens) system prompt,
# total input = ~4 376 tokens. Output capped at 3 500 = 7 876 total — under 8K.
_BLOG_CHARS = 3_000 # original blog snippet
_BRIEF_LANG = 800
_BRIEF_FACTS = 1_000
_BRIEF_STRUCT = 1_200 # structure needs room (skeleton + FAQ headings)
_BRIEF_SEO = 1_200 # SEO needs keyword list + H2s
_BRIEF_GEO = 600
_OUTPUT_TOKENS = 4_500 # provides full headroom for 2800-3200 words + FAQs + table
from utilis.tracing import traceable
class AggregatorAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=_OUTPUT_TOKENS)
inputs = {
"blog": state.blog_snippet(max_chars=_BLOG_CHARS),
"language": state._truncate(state.language_output, _BRIEF_LANG),
"facts": state._truncate(state.facts_output, _BRIEF_FACTS),
"structure": state._truncate(state.structure_output, _BRIEF_STRUCT),
"seo": state._truncate(state.seo_output, _BRIEF_SEO),
"geo": state._truncate(state.geo_output, _BRIEF_GEO),
"images": state.image_output,
"current_date": state.current_date,
"current_year": state.current_year,
"language_quality": state.language_quality,
"target_length": state.target_length,
}
full_text = stream_invoke(prompt, llm, inputs, state.stream_chunk)
from utilis.image_formatter import ensure_exact_images_in_markdown
state.aggregated_blog = ensure_exact_images_in_markdown(full_text, state.image_output)
state.editorial_brief = ""
state.stream_done()
return state
+88
View File
@@ -0,0 +1,88 @@
"""
baseline_evaluator.py
Scores the original scraped blog (state.cleaned_blog) using the same
evaluator rubric before any enhancement is applied.
Runs once, immediately after prepare_blog, and writes to the
baseline_* fields in BlogState so the UI can show a before/after
comparison at the end of the run.
Uses a smaller token budget than the main evaluator (800 tokens) because
the original blog is typically shorter and less structured — less to say.
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("evaluator.txt")),
("human", (
"Target Length\n\n{target_length}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nLanguage Quality\n\n{language_quality}"
"\n\nArticle\n\n{blog}"
)),
])
# Reduced from 8 000 — original blogs are short, 5 000 chars is enough.
_BASELINE_MAX_CHARS = 5_000
from utilis.tracing import traceable
class BaselineEvaluatorAgent:
def _score(self, result, key):
value = result.get(key) or result.get(f"{key}_score") or result.get(key.title())
if isinstance(value, dict):
value = value.get("score") or value.get("Score") or value.get("value")
return int(value or 0)
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=800, force_groq=True) # baseline = Groq always
response = invoke_with_retry(prompt, llm, {
"blog": state._truncate(state.cleaned_blog, _BASELINE_MAX_CHARS),
"current_date": state.current_date,
"current_year": state.current_year,
"language_quality": state.language_quality,
"target_length": state.target_length,
})
result = load_json(response.content)
def s(key):
return self._score(result, key)
state.baseline_language_score = s("language")
state.baseline_facts_score = s("facts")
state.baseline_structure_score = s("structure")
state.baseline_seo_score = s("seo")
state.baseline_geo_score = s("geo")
state.baseline_freshness_score = s("freshness")
scores = [
state.baseline_language_score,
state.baseline_facts_score,
state.baseline_structure_score,
state.baseline_seo_score,
state.baseline_geo_score,
state.baseline_freshness_score,
]
valid = [sc for sc in scores if sc > 0]
state.baseline_overall_score = round(sum(valid) / len(valid)) if valid else 0
return state
+91
View File
@@ -0,0 +1,91 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("evaluator.txt")),
("human", (
"Target Length\n\n{target_length}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nLanguage Quality\n\n{language_quality}"
"\n\nArticle\n\n{blog}"
)),
])
# 35 000 chars easily covers a full 3500-word article (~22 000 chars)
# ensuring the evaluator sees the complete text including FAQs, conclusion, and tables.
_EVAL_MAX_CHARS = 35_000
from utilis.tracing import traceable
class EvaluatorAgent:
def _score(self, result, key):
value = result.get(key) or result.get(f"{key}_score") or result.get(key.title())
if isinstance(value, dict):
value = value.get("score") or value.get("Score") or value.get("value")
return int(value or 0)
def _feedback(self, result, key):
value = (
result.get(f"{key}_feedback")
or result.get(f"{key}_notes")
or result.get(f"{key}_review")
or ""
)
if isinstance(value, dict):
value = value.get("feedback") or value.get("Feedback") or ""
return str(value)
def _overall_score(self, state):
scores = [state.language_score, state.facts_score, state.structure_score,
state.seo_score, state.geo_score, state.freshness_score]
valid = [s for s in scores if s > 0]
return round(sum(valid) / len(valid)) if valid else 0
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=1200, force_groq=True) # evaluation = Groq always
blog_to_eval = state._truncate(
state.optimized_blog or state.aggregated_blog,
max_chars=_EVAL_MAX_CHARS,
)
response = invoke_with_retry(prompt, llm, {
"blog": blog_to_eval,
"current_date": state.current_date,
"current_year": state.current_year,
"language_quality": state.language_quality,
"target_length": state.target_length,
})
result = load_json(response.content)
state.language_score = self._score(result, "language")
state.facts_score = self._score(result, "facts")
state.structure_score = self._score(result, "structure")
state.seo_score = self._score(result, "seo")
state.geo_score = self._score(result, "geo")
state.freshness_score = self._score(result, "freshness")
state.overall_score = self._overall_score(state)
state.language_feedback = self._feedback(result, "language")
state.facts_feedback = self._feedback(result, "facts")
state.structure_feedback = self._feedback(result, "structure")
state.seo_feedback = self._feedback(result, "seo")
state.geo_feedback = self._feedback(result, "geo")
state.freshness_feedback = self._feedback(result, "freshness")
state.iteration += 1
return state
+40
View File
@@ -0,0 +1,40 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("facts.txt")),
("human", (
"Blog\n\n{blog}"
"\n\nFacts Research Brief\n\n{facts_research}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class FactsAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
result = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"facts_research": state._truncate(state.facts_research, 1000),
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
})
state.facts_output = result.content
return state
+40
View File
@@ -0,0 +1,40 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("geo.txt")),
("human", (
"SEO Output\n\n{seo}"
"\n\nGEO Research Brief\n\n{geo_research}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class GeoAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"seo": state._truncate(state.seo_output, 900),
"geo_research": state._truncate(state.geo_research, 1000),
"current_date": state.current_date,
"current_year": state.current_year,
"target_length":state.target_length,
})
state.geo_output = response.content
return state
+449
View File
@@ -0,0 +1,449 @@
from pathlib import Path
import re
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from config.firecrawl_manager import search_images
from config.nemotron_image_selector import download_image, select_relevant_images
from config.tavily_search import search_image_candidates
# ---------------------------------------------------------------------------
# Terms that indicate images are NOT useful for a professional blog:
# cartoons, comic art, logos without context, generic stock icons, etc.
# If an image URL or alt text contains any of these, reject it.
# ---------------------------------------------------------------------------
_REJECT_PATTERNS = re.compile(
# Entertainment / promotional content
r"netflix|hulu|disney|amazon prime|hbo|peacock|paramount|"
r"movie|film\b|cinema|poster\b|trailer\b|series\b|episode|"
r"actor|actress|celebrity|red.?carpet|billboard\b|"
# Comic / cartoon art
r"clipart|cartoon|comic\b|superhero|avengers|marvel|dc.?comics|"
r"anime|manga|"
# Generic web junk
r"vector|icon\b|logo\b|favicon|banner\b|badge|sticker|"
r"thumbnail|avatar|emoji|smiley|wallpaper|meme|gif\b|"
# Stock photo filler words in the URL path
r"gettyimages|shutterstock|istockphoto|dreamstime|depositphotos",
re.IGNORECASE,
)
# Only accept common photo/diagram image extensions
_ACCEPT_EXTENSIONS = re.compile(r"\.(jpg|jpeg|png|webp)(\?.*)?$", re.IGNORECASE)
from utilis.tracing import traceable
class ImageAgent:
def _search_depth(self, research_level):
return "basic" if str(research_level).lower() in {"easy", "basic"} else "advanced"
def _clean_heading(self, line):
return re.sub(r"^#+\s*", "", line).strip(" :#")
def _topic(self, state) -> str:
"""Extract the core blog topic from the planner or URL for query grounding."""
intent = state.learner_output.get("intent") or ""
topic = state.planner_output.get("research_query") or intent or state.url
# Keep it short — first 80 chars
return str(topic)[:80].strip()
def _context_windows(self, markdown: str, count: int) -> list[dict]:
"""
Split the article into `count` evenly distributed section windows.
Each window carries its heading and the surrounding body text as context
for a highly specific image search.
"""
if count <= 0:
return []
blocks = []
current_heading = ""
current_lines: list[str] = []
for line in markdown.splitlines():
if re.match(r"^#{1,3}\s+", line.strip()):
if current_heading and current_lines:
blocks.append({
"heading": current_heading,
"context": " ".join(current_lines).strip(),
})
current_heading = self._clean_heading(line)
current_lines = []
continue
stripped = line.strip()
if current_heading and stripped and not stripped.startswith("!"):
current_lines.append(stripped)
if current_heading and current_lines:
blocks.append({
"heading": current_heading,
"context": " ".join(current_lines).strip(),
})
# Drop very short blocks and FAQ sections (usually no good image)
blocks = [
b for b in blocks
if len(b["context"]) > 80
and not b["heading"].lower().startswith("faq")
and not b["heading"].lower().startswith("conclusion")
]
if not blocks:
return []
# Distribute `count` windows across blocks or fill with distinct concept slots
if len(blocks) < count:
needed = count - len(blocks)
fallbacks = self._fallback_contexts(state, count)
# Use unique fallbacks not already in blocks
used_headings = {b["heading"].lower() for b in blocks}
for fb in fallbacks:
if fb["heading"].lower() not in used_headings:
blocks.append(fb)
used_headings.add(fb["heading"].lower())
if len(blocks) >= count:
break
step = max(1, len(blocks) // count)
windows = []
for i in range(count):
idx = min(int(i * step), len(blocks) - 1)
b = blocks[idx]
words = str(b.get("context", "")).split()
preceding_100 = " ".join(words[-100:]) if len(words) > 100 else str(b.get("context", ""))
placement = b.get("placement") or f"Place after the paragraph in '{b['heading']}' that discusses this topic."
windows.append({
"heading": b["heading"],
"context": preceding_100,
"placement": placement,
})
return windows
def _fallback_contexts(self, state, count: int) -> list[dict]:
topic = self._topic(state)
slots = [
("Technology Architecture & Workflow", f"{topic} system architecture workflow framework diagram"),
("Industry Data & Growth Trends", f"{topic} market analysis statistics growth chart infographic"),
("Strategic Implementation & Deployment", f"{topic} implementation deployment strategy model"),
("Best Practices & Operational Efficiency", f"{topic} operational workflow optimization best practices"),
("Future Roadmap & Innovations", f"{topic} innovation roadmap future technology landscape"),
]
contexts = []
for i in range(max(count, 1)):
slot_heading, slot_query = slots[i % len(slots)]
heading = f"{slot_heading} Part {i+1}" if i >= len(slots) else slot_heading
contexts.append({
"heading": heading,
"context": f"{topic} — {slot_query}",
"placement": f"Place after the section discussing '{heading}'.",
})
return contexts
def _image_query(self, state, section: dict) -> str:
"""
Build a precise, topic-anchored image search query.
Format: "<blog topic> <section heading> <key context words> photo diagram"
This greatly reduces the chance of returning irrelevant stock/cartoon images.
"""
topic = self._topic(state)
heading = section["heading"]
# Use up to 15 words of section context as additional signal
context_words = " ".join(section["context"].split()[:15])
year = state.current_year
return f"{topic} {heading} {context_words} {year} photo infographic"[:300]
def _filter_candidates(self, candidates: list[dict], section: dict) -> list[dict]:
"""
Remove candidates that are clearly irrelevant or low quality.
Checks both the URL (full path) and alt/caption text.
"""
filtered = []
for c in candidates:
url = (c.get("url") or "").lower()
alt = (c.get("alt") or c.get("caption") or "").lower()
combined = url + " " + alt
# Reject by combined URL + alt pattern
if _REJECT_PATTERNS.search(combined):
continue
# Require a recognised photo extension
if not _ACCEPT_EXTENSIONS.search(url):
continue
filtered.append(c)
return filtered
def _process_custom_images(self, custom_images: list[dict], markdown: str, state) -> list[dict]:
"""
Contextually maps user-supplied custom images into blog sections using
the user's description, caption, and placement hints.
"""
if not custom_images:
return []
# Extract available sections from markdown or fallbacks
sections = self._context_windows(markdown, max(len(custom_images), 4)) or self._fallback_contexts(state, len(custom_images))
processed = []
used_sections = set()
for idx, c_img in enumerate(custom_images):
img_path = c_img.get("image_path") or c_img.get("url") or ""
if not img_path:
continue
img_path = Path(img_path).as_posix()
caption = c_img.get("caption") or ""
desc = c_img.get("description") or ""
hint = c_img.get("placement_hint") or ""
source = c_img.get("source") or "Custom Upload"
# Combine signals to find the best matching section
combined_query = f"{caption} {desc} {hint}".lower().strip()
query_tokens = set(re.findall(r"\w{3,}", combined_query))
best_section = None
best_score = -1
for s in sections:
s_heading = s.get("heading", "")
s_context = s.get("context", "")
s_text = f"{s_heading} {s_context}".lower()
s_tokens = set(re.findall(r"\w{3,}", s_text))
overlap = len(query_tokens & s_tokens)
if s_heading in used_sections:
overlap -= 2
if overlap > best_score:
best_score = overlap
best_section = s
# If no strong match, pick an unused section or round-robin
if not best_section or best_score <= 0:
available = [s for s in sections if s.get("heading") not in used_sections]
best_section = available[0] if available else sections[idx % len(sections)]
heading = best_section.get("heading", f"Section {idx+1}")
used_sections.add(heading)
context = best_section.get("context", desc or "Article body context")
# Formulate explicit placement guidance
if hint:
placement = f"Place in section '{heading}' - Note: {hint}. Context: '{desc or context[-80:]}'."
elif desc:
placement = f"Place immediately after the paragraph in '{heading}' that discusses: '{desc[:100]}'."
else:
placement = best_section.get("placement") or f"Place in section '{heading}'."
processed.append({
"url": img_path,
"local_path": img_path,
"caption": caption or desc or f"Illustration for {heading}",
"alt": caption or desc or f"{heading} image",
"source_url": source,
"context": f"{desc}. Section context: {context[:300]}".strip(),
"placement": placement,
"section": heading,
"is_custom": True,
})
return processed
@traceable
def invoke(self, state):
if getattr(state, "image_output", None):
return state
custom_images = getattr(state, "custom_images", []) or []
source_markdown = state.cleaned_blog
images: list[dict] = []
seen_urls: set[str] = set()
seen_hashes: set[str] = set()
# 1. Process custom images first if provided
if custom_images:
processed_custom = self._process_custom_images(custom_images, source_markdown, state)
for img in processed_custom:
url = img.get("url")
if url:
seen_urls.add(url)
images.append(img)
# Total requested images
target_total = max(0, min(int(state.image_count or 0), 20))
# Ensure at least all custom images are included
target_total = max(target_total, len(images))
if target_total == 0:
state.image_output = []
return state
remaining = target_total - len(images)
# 2. If additional images are needed, fetch automated images
if remaining > 0:
selected_sections = (
self._context_windows(source_markdown, remaining)
or self._fallback_contexts(state, remaining)
)
fallback_sections: list[dict] = []
for section in selected_sections:
query = self._image_query(state, section)
candidates = search_image_candidates(
query,
max_results=12,
search_depth=self._search_depth(state.research_level),
)
candidates = self._filter_candidates(candidates, section)
found = select_relevant_images(
section["context"][:800],
section["heading"],
candidates,
limit=1,
)
# Firecrawl fallback — only use if filter passes
if not found:
firecrawl_candidates = search_images(
query,
limit=3,
context=section["context"][:500],
placement=section["placement"],
)
found = self._filter_candidates(firecrawl_candidates, section)
if found:
found = select_relevant_images(
section["context"][:800],
section["heading"],
found,
limit=1,
)
if not found:
fallback_sections.append(section)
continue
for img in found:
dl = download_image(img, section["heading"])
if not dl:
continue
url = dl.get("url")
chash = dl.get("content_hash")
if not url or url in seen_urls or (chash and chash in seen_hashes):
continue
seen_urls.add(url)
if chash:
seen_hashes.add(chash)
dl.setdefault("context", section["context"])
dl.setdefault("placement", section["placement"])
dl["section"] = section["heading"]
dl["alt"] = dl.get("alt") or f"{section['heading']} — {self._topic(state)}"
dl["caption"] = dl.get("caption") or dl["alt"]
dl["source_url"] = dl.get("source_url") or dl.get("remote_url") or url
images.append(dl)
if len(images) >= target_total:
break
if len(images) >= target_total:
break
# Second pass for fallback sections if still below target
if len(images) < target_total:
for section in fallback_sections:
if len(images) >= target_total:
break
query = self._image_query(state, section)
candidates = self._filter_candidates(
search_image_candidates(query, max_results=10,
search_depth=self._search_depth(state.research_level)),
section,
)
found = select_relevant_images(
section["context"][:800], section["heading"], candidates, limit=1
)
if not found:
firecrawl_candidates = self._filter_candidates(
search_images(query, limit=3,
context=section["context"][:500],
placement=section["placement"]),
section,
)
found = select_relevant_images(
section["context"][:800], section["heading"],
firecrawl_candidates, limit=1,
) if firecrawl_candidates else []
found = self._filter_candidates(found or [], section)
for img in found:
dl = download_image(img, section["heading"])
if not dl:
continue
url = dl.get("url")
chash = dl.get("content_hash")
if not url or url in seen_urls or (chash and chash in seen_hashes):
continue
seen_urls.add(url)
if chash:
seen_hashes.add(chash)
dl.setdefault("context", section["context"])
dl.setdefault("placement", section["placement"])
dl["section"] = section["heading"]
dl["source_url"] = dl.get("source_url") or dl.get("remote_url") or url
images.append(dl)
if len(images) >= target_total:
break
# 3. Third pass: broad topic search if still below target
if len(images) < target_total:
topic = self._topic(state)
broad_queries = [
f"{topic} infographic chart {state.current_year}",
f"{topic} technology architecture framework diagram",
f"{topic} market analysis statistics trends",
f"{topic} enterprise workflow implementation roadmap",
f"{topic} executive strategy guide",
]
for bq in broad_queries:
if len(images) >= target_total:
break
cands = self._filter_candidates(
search_image_candidates(bq, max_results=8, search_depth=self._search_depth(state.research_level)),
{"heading": "Key Analysis", "context": topic}
)
for c in cands:
dl = download_image(c, "Overview")
if not dl:
continue
url = dl.get("url")
chash = dl.get("content_hash")
if not url or url in seen_urls or (chash and chash in seen_hashes):
continue
seen_urls.add(url)
if chash:
seen_hashes.add(chash)
dl.setdefault("context", f"Comprehensive analysis for {topic}")
dl.setdefault("placement", f"Place in the section illustrating {topic}.")
dl["section"] = "Key Insights"
dl["source_url"] = dl.get("source_url") or dl.get("remote_url") or url
images.append(dl)
if len(images) >= target_total:
break
state.image_output = images[:target_total]
return state
+38
View File
@@ -0,0 +1,38 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("language.txt")),
("human", (
"Blog\n\n{blog}"
"\n\nLanguage Research Brief\n\n{language_research}"
"\n\nLanguage Quality\n\n{language_quality}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class LanguageAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"language_research": state._truncate(state.language_research, 800),
"language_quality": state.language_quality,
"target_length": state.target_length,
})
state.language_output = response.content
return state
+33
View File
@@ -0,0 +1,33 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from graph.state import BlogState
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("learner.txt")),
("human", "Target Length\n\n{target_length}\n\nBlog\n\n{blog}"),
])
from utilis.tracing import traceable
class LearnerAgent:
@traceable
def invoke(self, state: BlogState):
llm = make_llm(max_tokens=600, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"target_length": state.target_length,
})
state.learner_output = load_json(response.content)
return state
+81
View File
@@ -0,0 +1,81 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm, stream_invoke
from utilis.prompt_loader import load_prompt
prompt = ChatPromptTemplate.from_messages([
("system", f"{load_prompt('optimizer.txt')}\n\n{load_prompt('images.txt')}"),
("human", (
"Article Draft\n\n{current_draft}"
"\n\nEvaluator Fix Instructions"
"\nLanguage ({language_score}/100): {language_feedback}"
"\nFacts ({facts_score}/100): {facts_feedback}"
"\nStructure ({structure_score}/100): {structure_feedback}"
"\nSEO ({seo_score}/100): {seo_feedback}"
"\nGEO ({geo_score}/100): {geo_feedback}"
"\nFreshness ({freshness_score}/100): {freshness_feedback}"
"\n\nTargeted Research\n\n{targeted_research}"
"\n\nImage Recommendations\n\n{images}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nLanguage Quality\n\n{language_quality}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class OptimizerAgent:
_DRAFT_MAX_CHARS = 25_000 # full draft context for complete rewrite
_FEEDBACK_MAX_CHARS = 1_200 # rich feedback from evaluator
_OUTPUT_TOKENS = 4_500 # full output headroom for complete 2800-word article
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=self._OUTPUT_TOKENS)
current_draft = state._truncate(
state.optimized_blog or state.aggregated_blog,
max_chars=self._DRAFT_MAX_CHARS,
)
state.optimizer_iteration += 1
def _fb(text: str) -> str:
return state._truncate(text, self._FEEDBACK_MAX_CHARS) if text else "Passing."
inputs = {
"current_draft": current_draft,
"language_score": state.language_score,
"language_feedback": _fb(state.language_feedback),
"facts_score": state.facts_score,
"facts_feedback": _fb(state.facts_feedback),
"structure_score": state.structure_score,
"structure_feedback": _fb(state.structure_feedback),
"seo_score": state.seo_score,
"seo_feedback": _fb(state.seo_feedback),
"geo_score": state.geo_score,
"geo_feedback": _fb(state.geo_feedback),
"freshness_score": state.freshness_score,
"freshness_feedback": _fb(state.freshness_feedback),
"targeted_research": state._truncate(
state.targeted_research_output, 1200
) if state.targeted_research_output else "None.",
"images": state.image_output,
"current_date": state.current_date,
"current_year": state.current_year,
"language_quality": state.language_quality,
"target_length": state.target_length,
}
full_text = stream_invoke(prompt, llm, inputs, state.stream_chunk)
from utilis.image_formatter import ensure_exact_images_in_markdown
state.optimized_blog = ensure_exact_images_in_markdown(full_text, state.image_output)
state.stream_done()
return state
+62
View File
@@ -0,0 +1,62 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("planner.txt")),
("human", "Article\n\n{blog}\n\nLearner\n\n{learner}\n\nCurrent Date\n\n{current_date}\n\nCurrent Year\n\n{current_year}\n\nTarget Length\n\n{target_length}"),
])
from utilis.tracing import traceable
class PlannerAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=600, force_groq=True)
if getattr(state, "mode", "enhance") == "generate":
gen_prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("planner.txt")),
("human", "Topic\n\n{topic}\n\nGuidelines & Important Info\n\n{other_info}\n\nCurrent Date\n\n{current_date}\n\nCurrent Year\n\n{current_year}\n\nTarget Length\n\n{target_length}"),
])
response = invoke_with_retry(gen_prompt, llm, {
"topic": state.title or state.topic_idea,
"other_info": state.other_info,
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
})
else:
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"learner": state.learner_output,
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
})
output = load_json(response.content)
if "research_query" not in output or not output["research_query"]:
output["research_query"] = (
output.get("researchQuery")
or output.get("research_queries")
or output.get("query")
or (state.planner_output.get("research_query") if isinstance(state.planner_output, dict) else "")
or f"{state.title or state.url} {state.current_year} latest statistics examples SEO GEO keywords"
)
if isinstance(output["research_query"], list):
output["research_query"] = " ".join(output["research_query"])
state.planner_output = output
return state
+42
View File
@@ -0,0 +1,42 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
from utilis.tracing import traceable
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("prompt_generator.txt")),
("human", "Topic Idea: {topic_idea}\n\nGuidelines & Other Info: {other_info}"),
])
class PromptGeneratorAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=500, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"topic_idea": state.topic_idea,
"other_info": state.other_info,
})
output = load_json(response.content)
state.title = output.get("optimized_topic") or state.topic_idea
state.research_output = ""
state.planner_output = {
"research_query": output.get("research_prompt") or state.topic_idea,
"primary_keyword": state.topic_idea,
"h1_title": state.title,
"h2_headings": [],
"faq_questions": [],
"secondary_keywords": [],
"target_outline": []
}
return state
+110
View File
@@ -0,0 +1,110 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from config.tavily_search import search
from graph.state import BlogState
from utilis.prompt_loader import load_prompt
from utilis.research_cache import get_researcher_cache
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("researcher.txt")),
("human", (
"Search Results\n\n{research}"
"\n\nSEO Signals from Planner\n\n{seo_signals}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nTarget Length\n\n{target_length}"
"\n\nResearch Level\n\n{research_level}"
)),
])
from utilis.tracing import traceable
class ResearchAgent:
_MAX_RESULT_CHARS = 400
_MAX_TOTAL_CHARS = 3500
def _research_settings(self, level):
return {
"easy": {"max_results": 3, "search_depth": "basic"},
"basic": {"max_results": 3, "search_depth": "basic"},
"medium": {"max_results": 5, "search_depth": "advanced"},
"advanced": {"max_results": 8, "search_depth": "advanced"},
}.get(str(level).lower(), {"max_results": 5, "search_depth": "advanced"})
def _trim_results(self, results) -> str:
items = results.get("results", []) if isinstance(results, dict) else (results if isinstance(results, list) else [])
lines = []
for item in items:
content = item.get("content", "")
if len(content) > self._MAX_RESULT_CHARS:
content = content[:self._MAX_RESULT_CHARS].rsplit(" ", 1)[0] + "…"
lines.append(f"- {item.get('title', '')}\n {item.get('url', '')}\n {content}")
combined = "\n\n".join(lines)
if len(combined) > self._MAX_TOTAL_CHARS:
combined = combined[:self._MAX_TOTAL_CHARS].rsplit("\n", 1)[0] + "\n…[truncated]"
return combined
def _seo_signals(self, state: BlogState) -> str:
"""Extract keyword/heading signals from the planner so the researcher
reinforces them in the brief rather than inventing its own."""
p = state.planner_output
if not p:
return ""
lines = []
kw = p.get("primary_keyword", "")
if kw:
lines.append(f"Primary keyword: {kw}")
h1 = p.get("h1_title", "")
if h1:
lines.append(f"H1: {h1}")
h2s = p.get("h2_headings", [])
if h2s:
lines.append(f"H2 headings: {' | '.join(h2s[:6])}")
faqs = p.get("faq_questions", [])
if faqs:
lines.append(f"FAQ questions: {' | '.join(faqs[:6])}")
sec = p.get("secondary_keywords", [])
if sec:
lines.append(f"Secondary keywords: {', '.join(sec[:10])}")
return "\n".join(lines)
@traceable
def invoke(self, state: BlogState):
query = (
state.planner_output.get("research_query")
or f"{state.url} {state.current_year} latest statistics examples SEO GEO keywords"
)
if isinstance(query, list):
query = " ".join(query)
query = f"{query} {state.current_year}"
cache = get_researcher_cache()
cached = cache.get(query)
if cached:
state.research_output = cached
return state
results = search(query, **self._research_settings(state.research_level))
llm = make_llm(max_tokens=2000)
response = invoke_with_retry(prompt, llm, {
"research": self._trim_results(results),
"seo_signals": self._seo_signals(state),
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
"research_level": state.research_level,
})
state.research_output = response.content
cache.set(query, state.research_output)
return state
+40
View File
@@ -0,0 +1,40 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("seo.txt")),
("human", (
"Blog\n\n{blog}"
"\n\nSEO Research Brief\n\n{seo_research}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class SeoAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"seo_research": state._truncate(state.seo_research, 1200),
"current_date": state.current_date,
"current_year": state.current_year,
"target_length":state.target_length,
})
state.seo_output = response.content
return state
+40
View File
@@ -0,0 +1,40 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("structure.txt")),
("human", (
"Blog\n\n{blog}"
"\n\nStructure Research Brief\n\n{structure_research}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class StructureAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
# The supervisor's structure_brief already contains the full article
# skeleton (H1, H2s, FAQ questions, paragraph topics) aligned to the
# SEO plan — pass it in full so the structure agent refines rather
# than rebuilds from scratch.
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"structure_research":state._truncate(state.structure_research, 1200),
"target_length": state.target_length,
})
state.structure_output = response.content
return state
+159
View File
@@ -0,0 +1,159 @@
"""
supervisor.py — Research Supervisor Agent
Replaces the single ResearchAgent. One Tavily search call,
one LLM call → five focused research briefs, one per specialist:
language_brief → state.language_research
facts_brief → state.facts_research
structure_brief → state.structure_research
seo_brief → state.seo_research
geo_brief → state.geo_research
Each specialist agent then reads its own dedicated brief instead
of having to extract relevant pieces from a shared generic document.
Also writes state.research_output with the raw search results summary
so targeted_researcher and any legacy code still works.
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from config.tavily_search import search
from graph.state import BlogState
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.research_cache import get_researcher_cache
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("supervisor.txt")),
("human", (
"Search Results\n\n{search_results}"
"\n\nContent Plan\n\n{plan_summary}"
"\n\nPrimary Keyword: {primary_keyword}"
"\n\nH1 Title: {h1_title}"
"\n\nH2 Headings: {h2_headings}"
"\n\nFAQ Questions: {faq_questions}"
"\n\nSecondary Keywords: {secondary_keywords}"
"\n\nCurrent Date: {current_date}"
"\n\nCurrent Year: {current_year}"
"\n\nTarget Length: {target_length}"
)),
])
_MAX_RESULT_CHARS = 400
_MAX_TOTAL_CHARS = 4000 # slightly larger than old researcher — supervisor uses the full budget
def _trim_results(results) -> str:
items = (
results.get("results", []) if isinstance(results, dict)
else results if isinstance(results, list)
else []
)
lines = []
for item in items:
content = item.get("content", "")
if len(content) > _MAX_RESULT_CHARS:
content = content[:_MAX_RESULT_CHARS].rsplit(" ", 1)[0] + "…"
lines.append(f"- {item.get('title', '')}\n {item.get('url', '')}\n {content}")
combined = "\n\n".join(lines)
if len(combined) > _MAX_TOTAL_CHARS:
combined = combined[:_MAX_TOTAL_CHARS].rsplit("\n", 1)[0] + "\n…[truncated]"
return combined
def _research_settings(level: str, results_override: int = 0) -> dict:
defaults = {
"easy": {"max_results": 3, "search_depth": "basic"},
"basic": {"max_results": 3, "search_depth": "basic"},
"medium": {"max_results": 5, "search_depth": "advanced"},
"advanced": {"max_results": 8, "search_depth": "advanced"},
}.get(str(level).lower(), {"max_results": 5, "search_depth": "advanced"})
# UI slider overrides the count but keeps the depth appropriate for the level
if results_override > 0:
defaults["max_results"] = results_override
return defaults
def _seo_fields(state: BlogState) -> dict:
"""Pull the keyword plan from planner_output into flat strings."""
p = state.planner_output
return {
"primary_keyword": p.get("primary_keyword", ""),
"h1_title": p.get("h1_title", ""),
"h2_headings": " | ".join(p.get("h2_headings", [])[:6]),
"faq_questions": " | ".join(p.get("faq_questions", [])[:6]),
"secondary_keywords":", ".join(p.get("secondary_keywords", [])[:10]),
}
from utilis.tracing import traceable
class SupervisorAgent:
@traceable
def invoke(self, state: BlogState) -> BlogState:
query = (
state.planner_output.get("research_query")
or f"{state.url} {state.current_year} latest statistics examples"
)
if isinstance(query, list):
query = " ".join(query)
query = f"{query} {state.current_year}"
# Cache check — skip search + LLM if a similar query was seen recently
cache = get_researcher_cache()
cached_json = cache.get(query)
if cached_json:
briefs = load_json(cached_json) if isinstance(cached_json, str) else cached_json
self._apply_briefs(state, briefs, cached_json if isinstance(cached_json, str) else "")
return state
raw_results = search(query, **_research_settings(state.research_level, state.research_results))
trimmed = _trim_results(raw_results)
# Keep a raw summary in research_output for targeted_researcher
state.research_output = trimmed
llm = make_llm(max_tokens=2000, force_groq=True) # supervisor = Groq (research synthesis)
seo = _seo_fields(state)
response = invoke_with_retry(prompt, llm, {
"search_results": trimmed,
"plan_summary": state.plan_summary(),
"primary_keyword": seo["primary_keyword"],
"h1_title": seo["h1_title"],
"h2_headings": seo["h2_headings"],
"faq_questions": seo["faq_questions"],
"secondary_keywords":seo["secondary_keywords"],
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
})
raw_output = response.content
briefs = load_json(raw_output)
cache.set(query, raw_output)
self._apply_briefs(state, briefs, raw_output)
return state
def _apply_briefs(self, state: BlogState, briefs: dict, raw: str) -> None:
"""Write each brief into its dedicated state field with a safe fallback."""
state.language_research = briefs.get("language_brief", raw)
state.facts_research = briefs.get("facts_brief", raw)
state.structure_research = briefs.get("structure_brief", raw)
state.seo_research = briefs.get("seo_brief", raw)
state.geo_research = briefs.get("geo_brief", raw)
# Also keep the raw content in research_output for backward compatibility
if not state.research_output:
state.research_output = raw
+172
View File
@@ -0,0 +1,172 @@
"""
targeted_researcher.py
Runs targeted web research for dimensions that scored below 70 after the
optimizer pass. Builds a per-dimension query, searches via Tavily, then
synthesises the results into a structured markdown brief that is stored in
state.targeted_research_output.
The optimizer will pick this up on its next pass and use it to fix the
specific failing sections.
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from config.tavily_search import search
from graph.state import BlogState
from utilis.prompt_loader import load_prompt
from utilis.research_cache import get_targeted_cache
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("targeted_researcher.txt")),
("human", (
"Search Results\n\n{search_results}"
)),
])
# Maps each dimension to a search query suffix that targets the exact gap
_DIMENSION_QUERY_SUFFIX = {
"language": "writing style examples tone engaging prose blog",
"facts": "latest statistics data named examples case studies verified sources",
"structure": "blog structure outline FAQ headings word count best practices",
"seo": "primary keywords LSI keywords search intent FAQ questions SEO",
"geo": "named entities definitions direct answers authoritative statements",
"freshness": f"latest current statistics trends updated data",
}
SCORE_THRESHOLD = 70
def _get_failing_dimensions(state: BlogState) -> list[tuple[str, int, str]]:
"""
Returns a list of (dimension_name, score, feedback) tuples
for every dimension that scored below SCORE_THRESHOLD.
"""
candidates = [
("language", state.language_score, state.language_feedback),
("facts", state.facts_score, state.facts_feedback),
("structure", state.structure_score, state.structure_feedback),
("seo", state.seo_score, state.seo_feedback),
("geo", state.geo_score, state.geo_feedback),
("freshness", state.freshness_score, state.freshness_feedback),
]
return [(name, score, fb) for name, score, fb in candidates if score < SCORE_THRESHOLD]
def _build_failing_brief(failing: list[tuple[str, int, str]]) -> str:
"""Formats the failing dimension info for the prompt."""
lines = []
for name, score, feedback in failing:
lines.append(f"### {name.upper()} (score: {score}/100)")
lines.append(f"Evaluator feedback: {feedback or 'No specific feedback provided.'}")
lines.append("")
return "\n".join(lines)
def _build_search_query(failing: list[tuple[str, int, str]], url: str, year: int) -> str:
"""
Builds a combined Tavily search query that covers all failing dimensions.
Pulls the topic from the URL slug and appends dimension-specific suffixes.
"""
# Extract a readable topic from the URL
slug = url.rstrip("/").split("/")[-1].replace("-", " ").replace("_", " ")
topic = slug if slug else url
suffixes = [_DIMENSION_QUERY_SUFFIX.get(name, "") for name, _, _ in failing]
combined_suffix = " ".join(dict.fromkeys(s for s in suffixes if s)) # deduplicate
return f"{topic} {combined_suffix} {year} latest"
from utilis.tracing import traceable
class TargetedResearchAgent:
_MAX_RESULT_CHARS = 400
_MAX_TOTAL_CHARS = 3500
def _research_settings(self, level: str) -> dict:
settings = {
"easy": {"max_results": 3, "search_depth": "basic"},
"basic": {"max_results": 3, "search_depth": "basic"},
"medium": {"max_results": 5, "search_depth": "advanced"},
"advanced": {"max_results": 8, "search_depth": "advanced"},
}
return settings.get(str(level).lower(), settings["medium"])
def _trim_results(self, results) -> str:
if isinstance(results, dict):
items = results.get("results", [])
elif isinstance(results, list):
items = results
else:
return str(results)[:self._MAX_TOTAL_CHARS]
lines = []
for item in items:
title = item.get("title", "")
url = item.get("url", "")
content = item.get("content", "")
if len(content) > self._MAX_RESULT_CHARS:
content = content[:self._MAX_RESULT_CHARS].rsplit(" ", 1)[0] + "…"
lines.append(f"- {title}\n {url}\n {content}")
combined = "\n\n".join(lines)
if len(combined) > self._MAX_TOTAL_CHARS:
combined = combined[:self._MAX_TOTAL_CHARS].rsplit("\n", 1)[0] + "\n…[truncated]"
return combined
@traceable
def invoke(self, state: BlogState) -> BlogState:
failing = _get_failing_dimensions(state)
if not failing:
# Nothing to do — scores all ≥ threshold, router shouldn't have
# sent us here, but be safe.
return state
failing_names = [name for name, _, _ in failing]
failing_brief = _build_failing_brief(failing)
query = _build_search_query(failing, state.url, state.current_year)
# ── Cache check ──────────────────────────────────────────────────────
cache = get_targeted_cache()
cached = cache.get(query)
if cached:
state.targeted_research_output = (
f"## Targeted Research for: {', '.join(failing_names)}\n\n"
+ cached
)
return state
# Run the search
search_results = search(query, **self._research_settings(state.research_level))
# Synthesise targeted research brief via LLM
llm = make_llm(size="medium", force_groq=True) # targeted research = Groq always
response = invoke_with_retry(prompt, llm, {
"failing_dimensions_brief": failing_brief,
"url": state.url,
"current_date": state.current_date,
"current_year": state.current_year,
"search_results": self._trim_results(search_results),
})
result_text = response.content
cache.set(query, result_text)
# Store in dedicated field so it doesn't overwrite the original research
state.targeted_research_output = (
f"## Targeted Research for: {', '.join(failing_names)}\n\n"
+ result_text
)
return state