feat: initial commit for Blog Expert multi-agent system
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
def __getattr__(name):
|
||||
if name == "graph":
|
||||
from .graph import graph
|
||||
|
||||
return graph
|
||||
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
"""
|
||||
Compiled LangGraph workflow for the blog optimizer.
|
||||
|
||||
Flow:
|
||||
prepare → learner → planner → supervisor
|
||||
→ language → facts → structure → image → seo → geo
|
||||
→ aggregator → evaluator ─(evaluation_router)─┐
|
||||
├→ supervisor/language/facts/structure/seo/geo (re-brief)
|
||||
└→ optimizer
|
||||
│
|
||||
evaluator_post ─(optimizer_router)─┐
|
||||
├→ targeted_researcher → optimizer
|
||||
├→ optimizer (scores 70-89, loop, max 5)
|
||||
└→ END
|
||||
|
||||
Architecture change — Supervisor replaces the single Researcher:
|
||||
Old: one researcher → one generic brief → all 5 specialists
|
||||
New: supervisor → one Tavily search → one LLM call → 5 focused briefs
|
||||
Each specialist reads its own dedicated brief:
|
||||
language_research, facts_research, structure_research,
|
||||
seo_research, geo_research
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
if __package__ is None or __package__ == "":
|
||||
sys.path.append(str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from langgraph.graph import END, StateGraph
|
||||
|
||||
from agents.aggregator import AggregatorAgent
|
||||
from agents.baseline_evaluator import BaselineEvaluatorAgent
|
||||
from agents.evaluator import EvaluatorAgent
|
||||
from agents.facts_agent import FactsAgent
|
||||
from agents.geo_agent import GeoAgent
|
||||
from agents.image_agent import ImageAgent
|
||||
from agents.language_agent import LanguageAgent
|
||||
from agents.learner import LearnerAgent
|
||||
from agents.optimizer import OptimizerAgent
|
||||
from agents.planner import PlannerAgent
|
||||
from agents.supervisor import SupervisorAgent
|
||||
from agents.seo_agent import SeoAgent
|
||||
from agents.structure_agent import StructureAgent
|
||||
from agents.targeted_researcher import TargetedResearchAgent
|
||||
from config.llm_registry import set_provider
|
||||
from graph.router import evaluation_router, optimizer_router
|
||||
from graph.state import BlogState
|
||||
from rag.chunker import create_chunks
|
||||
from rag.html_cleaner import clean_html
|
||||
from rag.ingestion import ingest_blog
|
||||
from rag.markdown_converter import html_to_markdown
|
||||
from rag.scraper import scrape_blog
|
||||
|
||||
|
||||
from utilis.tracing import traceable
|
||||
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import threading
|
||||
|
||||
@traceable
|
||||
def prepare_blog(state: BlogState):
|
||||
if getattr(state, "job_id", 0):
|
||||
from db.database import BlogDatabase
|
||||
if BlogDatabase().is_cancel_requested(state.job_id):
|
||||
raise RuntimeError("Cancelled by user.")
|
||||
|
||||
set_provider(state.llm_provider)
|
||||
if state.llm_provider == "custom":
|
||||
from config.llm_registry import set_custom_llm_settings
|
||||
set_custom_llm_settings(state.custom_model_name, state.custom_api_key, state.custom_base_url)
|
||||
|
||||
from config.llm_registry import set_execution_mode
|
||||
set_execution_mode(
|
||||
mode=getattr(state, "execution_mode", "online"),
|
||||
local_engine=getattr(state, "local_engine", "ollama"),
|
||||
local_model_name=getattr(state, "local_model_name", "qwen2.5:7b"),
|
||||
local_base_url=getattr(state, "local_base_url", "http://localhost:11434/v1"),
|
||||
local_api_key=getattr(state, "local_api_key", "ollama"),
|
||||
)
|
||||
|
||||
state.active_agent = "prepare"
|
||||
if hasattr(state, "active_agent_callback") and state.active_agent_callback:
|
||||
try:
|
||||
state.active_agent_callback("prepare")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if getattr(state, "resume_node", None) and state.resume_node != "prepare":
|
||||
return state
|
||||
|
||||
if getattr(state, "mode", "enhance") == "generate":
|
||||
from agents.prompt_generator import PromptGeneratorAgent
|
||||
pga = PromptGeneratorAgent()
|
||||
state = pga.invoke(state)
|
||||
state.chunks = []
|
||||
state.url = state.url or f"topic:{state.topic_idea}"
|
||||
return state
|
||||
|
||||
scraped = scrape_blog(state.url)
|
||||
state.title = scraped.get("title") or ""
|
||||
state.raw_blog = scraped["html"]
|
||||
state.cleaned_blog = html_to_markdown(clean_html(state.raw_blog))
|
||||
state.chunks = create_chunks(state.cleaned_blog)
|
||||
|
||||
# Asynchronous Pinecone indexing in background so the pipeline advances immediately
|
||||
threading.Thread(target=ingest_blog, args=(state.chunks, state.url), daemon=True).start()
|
||||
return state
|
||||
|
||||
|
||||
@traceable
|
||||
def specialists_parallel(state: BlogState) -> BlogState:
|
||||
"""
|
||||
Executes Language, Facts, Structure, Image, SEO, and GEO specialist agents
|
||||
simultaneously in a thread pool for 5-7x faster turnaround.
|
||||
"""
|
||||
state.active_agent = "specialists_parallel"
|
||||
if hasattr(state, "active_agent_callback") and state.active_agent_callback:
|
||||
try:
|
||||
state.active_agent_callback("specialists_parallel")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if getattr(state, "job_id", 0):
|
||||
from db.database import BlogDatabase
|
||||
if BlogDatabase().is_cancel_requested(state.job_id):
|
||||
raise RuntimeError("Cancelled by user.")
|
||||
LAST_ACTIVE_STATE[state.job_id] = state.copy()
|
||||
|
||||
lang_agent = LanguageAgent()
|
||||
facts_agent = FactsAgent()
|
||||
struct_agent = StructureAgent()
|
||||
img_agent = ImageAgent()
|
||||
seo_agent = SeoAgent()
|
||||
geo_agent = GeoAgent()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=6) as executor:
|
||||
f_lang = executor.submit(lang_agent.invoke, state.copy())
|
||||
f_facts = executor.submit(facts_agent.invoke, state.copy())
|
||||
f_struct = executor.submit(struct_agent.invoke, state.copy())
|
||||
f_img = executor.submit(img_agent.invoke, state.copy())
|
||||
f_seo = executor.submit(seo_agent.invoke, state.copy())
|
||||
f_geo = executor.submit(geo_agent.invoke, state.copy())
|
||||
|
||||
r_lang = f_lang.result()
|
||||
r_facts = f_facts.result()
|
||||
r_struct = f_struct.result()
|
||||
r_img = f_img.result()
|
||||
r_seo = f_seo.result()
|
||||
r_geo = f_geo.result()
|
||||
|
||||
state.language_output = r_lang.language_output
|
||||
state.facts_output = r_facts.facts_output
|
||||
state.structure_output = r_struct.structure_output
|
||||
state.image_output = r_img.image_output
|
||||
state.seo_output = r_seo.seo_output
|
||||
state.geo_output = r_geo.geo_output
|
||||
|
||||
return state
|
||||
|
||||
|
||||
LAST_ACTIVE_STATE = {}
|
||||
|
||||
def _wrap(agent_name: str, agent_class):
|
||||
_instance = {}
|
||||
|
||||
def _inner(state: BlogState):
|
||||
state.active_agent = agent_name
|
||||
if hasattr(state, "active_agent_callback") and state.active_agent_callback:
|
||||
try:
|
||||
state.active_agent_callback(agent_name)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if getattr(state, "job_id", 0):
|
||||
from db.database import BlogDatabase
|
||||
if BlogDatabase().is_cancel_requested(state.job_id):
|
||||
raise RuntimeError("Cancelled by user.")
|
||||
LAST_ACTIVE_STATE[state.job_id] = state.copy()
|
||||
|
||||
if "obj" not in _instance:
|
||||
_instance["obj"] = agent_class()
|
||||
return _instance["obj"].invoke(state)
|
||||
|
||||
_inner.__name__ = agent_name
|
||||
return _inner
|
||||
|
||||
|
||||
def prepare_router(state: BlogState):
|
||||
# if getattr(state, "resume_node", None) and state.resume_node != "prepare":
|
||||
# return state.resume_node
|
||||
if getattr(state, "mode", "enhance") == "generate":
|
||||
return "learner"
|
||||
return "baseline_evaluator"
|
||||
|
||||
|
||||
workflow = StateGraph(BlogState)
|
||||
|
||||
workflow.add_node("prepare", prepare_blog)
|
||||
workflow.add_node("baseline_evaluator", _wrap("baseline_evaluator", BaselineEvaluatorAgent))
|
||||
workflow.add_node("learner", _wrap("learner", LearnerAgent))
|
||||
workflow.add_node("planner", _wrap("planner", PlannerAgent))
|
||||
workflow.add_node("supervisor", _wrap("supervisor", SupervisorAgent))
|
||||
workflow.add_node("specialists_parallel", specialists_parallel)
|
||||
workflow.add_node("language", _wrap("language", LanguageAgent))
|
||||
workflow.add_node("facts", _wrap("facts", FactsAgent))
|
||||
workflow.add_node("structure", _wrap("structure", StructureAgent))
|
||||
workflow.add_node("image", _wrap("image", ImageAgent))
|
||||
workflow.add_node("seo", _wrap("seo", SeoAgent))
|
||||
workflow.add_node("geo", _wrap("geo", GeoAgent))
|
||||
workflow.add_node("aggregator", _wrap("aggregator", AggregatorAgent))
|
||||
workflow.add_node("evaluator", _wrap("evaluator", EvaluatorAgent))
|
||||
workflow.add_node("optimizer", _wrap("optimizer", OptimizerAgent))
|
||||
workflow.add_node("targeted_researcher", _wrap("targeted_researcher", TargetedResearchAgent))
|
||||
workflow.add_node("evaluator_post", _wrap("evaluator_post", EvaluatorAgent))
|
||||
|
||||
workflow.set_entry_point("prepare")
|
||||
|
||||
workflow.add_conditional_edges(
|
||||
"prepare",
|
||||
prepare_router,
|
||||
{
|
||||
"planner": "planner",
|
||||
"baseline_evaluator": "baseline_evaluator",
|
||||
"learner": "learner",
|
||||
"supervisor": "supervisor",
|
||||
"specialists_parallel": "specialists_parallel",
|
||||
"language": "language",
|
||||
"facts": "facts",
|
||||
"structure": "structure",
|
||||
"image": "image",
|
||||
"seo": "seo",
|
||||
"geo": "geo",
|
||||
"aggregator": "aggregator",
|
||||
"evaluator": "evaluator",
|
||||
"optimizer": "optimizer",
|
||||
"targeted_researcher": "targeted_researcher",
|
||||
"evaluator_post": "evaluator_post",
|
||||
}
|
||||
)
|
||||
workflow.add_edge("baseline_evaluator", "learner")
|
||||
workflow.add_edge("learner", "planner")
|
||||
workflow.add_edge("planner", "supervisor") # supervisor replaces researcher
|
||||
workflow.add_edge("supervisor", "specialists_parallel")
|
||||
workflow.add_edge("specialists_parallel", "aggregator")
|
||||
workflow.add_edge("aggregator", "evaluator")
|
||||
|
||||
|
||||
# evaluation_router re-runs supervisor (not researcher) when freshness < 70
|
||||
# so all 5 briefs get refreshed from new search results.
|
||||
workflow.add_conditional_edges(
|
||||
"evaluator",
|
||||
evaluation_router,
|
||||
{
|
||||
"researcher": "supervisor", # freshness re-run → full supervisor refresh
|
||||
"language": "language",
|
||||
"facts": "facts",
|
||||
"structure": "structure",
|
||||
"seo": "seo",
|
||||
"geo": "geo",
|
||||
"optimizer": "optimizer",
|
||||
},
|
||||
)
|
||||
|
||||
workflow.add_edge("optimizer", "evaluator_post")
|
||||
workflow.add_edge("targeted_researcher", "optimizer")
|
||||
|
||||
workflow.add_conditional_edges(
|
||||
"evaluator_post",
|
||||
optimizer_router,
|
||||
{
|
||||
"targeted_researcher": "targeted_researcher",
|
||||
"optimizer": "optimizer",
|
||||
"end": END,
|
||||
},
|
||||
)
|
||||
|
||||
graph = workflow.compile()
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
router.py — routing functions for the LangGraph workflow.
|
||||
|
||||
Two routers:
|
||||
|
||||
1. evaluation_router (after evaluator, first pass)
|
||||
Routes back to individual specialist agents when a dimension scores <70,
|
||||
so the specialist can redo its brief before aggregation.
|
||||
Once all dimensions are ≥70, routes to optimizer.
|
||||
Cap: MAX_SPECIALIST_ITERATIONS (3) — prevents infinite specialist loops.
|
||||
|
||||
2. optimizer_router (after optimizer)
|
||||
The optimizer has written/rewritten the article.
|
||||
Evaluator re-scores it.
|
||||
- If any dimension <70 → targeted_researcher (max MAX_TARGETED_ITERATIONS times)
|
||||
- If any dimension <90 and passes remaining → optimizer (polish pass)
|
||||
- All ≥90 or cap reached → end
|
||||
Cap: MAX_OPTIMIZER_ITERATIONS (8) — more passes = meaningfully better output.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
if __package__ is None or __package__ == "":
|
||||
sys.path.append(str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from graph.state import BlogState
|
||||
|
||||
# Pre-optimizer specialist re-brief loop.
|
||||
# 3 is enough — if a specialist is still failing after 3 re-runs with the
|
||||
# same inputs, more loops won't fix it; the optimizer will handle it.
|
||||
MAX_SPECIALIST_ITERATIONS = 3
|
||||
|
||||
# Optimizer → evaluator_post polish loop.
|
||||
# 8 passes gives the optimizer real room to reach 90+ across all dimensions
|
||||
# without burning through quota on every run.
|
||||
MAX_OPTIMIZER_ITERATIONS = 8
|
||||
|
||||
# Maximum number of targeted_researcher → optimizer cycles.
|
||||
# Each brings fresh Tavily data, so 3 is genuinely useful.
|
||||
MAX_TARGETED_ITERATIONS = 3
|
||||
|
||||
|
||||
def evaluation_router(state: BlogState) -> str:
|
||||
"""
|
||||
Called after the FIRST evaluator run (post-aggregator).
|
||||
Routes to optimizer to polish failing dimensions or to specialists if re-brief needed.
|
||||
"""
|
||||
mode = getattr(state, "speed_mode", "turbo")
|
||||
if mode in ("turbo", "balanced"):
|
||||
return "optimizer"
|
||||
|
||||
if state.iteration >= MAX_SPECIALIST_ITERATIONS:
|
||||
return "optimizer"
|
||||
|
||||
if state.freshness_score < 70:
|
||||
return "researcher"
|
||||
if state.language_score < 70:
|
||||
return "language"
|
||||
if state.facts_score < 70:
|
||||
return "facts"
|
||||
if state.structure_score < 70:
|
||||
return "structure"
|
||||
if state.seo_score < 70:
|
||||
return "seo"
|
||||
if state.geo_score < 70:
|
||||
return "geo"
|
||||
|
||||
return "optimizer"
|
||||
|
||||
|
||||
def optimizer_router(state: BlogState) -> str:
|
||||
"""
|
||||
Evaluates post-optimizer scores against the speed profile thresholds:
|
||||
- Turbo: Guarantees all parameters >= 70 (max 2 fast passes)
|
||||
- Balanced: Guarantees all parameters >= 85
|
||||
- Deep Analysis: Guarantees all parameters >= 95 no matter what
|
||||
"""
|
||||
scores = [
|
||||
state.language_score, state.facts_score, state.structure_score,
|
||||
state.seo_score, state.geo_score, state.freshness_score
|
||||
]
|
||||
min_score = min(scores) if scores else 0
|
||||
mode = getattr(state, "speed_mode", "turbo")
|
||||
|
||||
# 1. Turbo Mode: Guarantee minimum 70+ across all dimensions
|
||||
if mode == "turbo":
|
||||
if min_score >= 70 or state.optimizer_iteration >= 2:
|
||||
return "end"
|
||||
return "optimizer"
|
||||
|
||||
# 2. Deep Analysis Mode: Must stay above 95 in all parameters
|
||||
if mode == "deep":
|
||||
if all(s >= 95 for s in scores):
|
||||
return "end"
|
||||
|
||||
targeted_runs = getattr(state, "_targeted_runs", 0)
|
||||
if any(s < 75 for s in scores) and targeted_runs < MAX_TARGETED_ITERATIONS:
|
||||
object.__setattr__(state, "_targeted_runs", targeted_runs + 1)
|
||||
return "targeted_researcher"
|
||||
|
||||
if state.optimizer_iteration >= state.max_optimizer_passes:
|
||||
return "end"
|
||||
return "optimizer"
|
||||
|
||||
# 3. Balanced Mode: Guarantee 85+
|
||||
if all(s >= 85 for s in scores) or state.optimizer_iteration >= max(1, min(state.max_optimizer_passes, 3)):
|
||||
return "end"
|
||||
|
||||
return "optimizer"
|
||||
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
from datetime import date
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class BlogState(BaseModel):
|
||||
|
||||
url: str
|
||||
|
||||
title: str = ""
|
||||
|
||||
raw_blog: str = ""
|
||||
|
||||
cleaned_blog: str = ""
|
||||
|
||||
chunks: list[str] = Field(default_factory=list)
|
||||
|
||||
retrieved_context: str = ""
|
||||
|
||||
target_length: str = "approximately 5 web pages, or 2000-3000 words"
|
||||
|
||||
max_pages: int = 5
|
||||
|
||||
language_quality: str = "medium"
|
||||
|
||||
research_level: str = "medium"
|
||||
|
||||
# Number of Tavily search results to fetch (overrides research_level default).
|
||||
# Set from UI slider. 0 = use research_level default.
|
||||
research_results: int = 0
|
||||
|
||||
image_count: int = 3
|
||||
|
||||
custom_images: list[dict] = Field(default_factory=list)
|
||||
|
||||
# Generation speed profile: "turbo" (<45s) | "balanced" (60-90s) | "deep" (2-3m)
|
||||
speed_mode: str = "turbo"
|
||||
|
||||
# Execution Mode: "online" | "offline" | "hybrid"
|
||||
execution_mode: str = "online"
|
||||
local_engine: str = "ollama" # "ollama" | "lmstudio" | "custom"
|
||||
local_model_name: str = "qwen2.5:7b"
|
||||
local_base_url: str = "http://localhost:11434/v1"
|
||||
local_api_key: str = "ollama"
|
||||
|
||||
current_date: str = Field(default_factory=lambda: date.today().isoformat())
|
||||
|
||||
current_year: int = Field(default_factory=lambda: date.today().year)
|
||||
|
||||
learner_output: dict = Field(default_factory=dict)
|
||||
|
||||
planner_output: dict = Field(default_factory=dict)
|
||||
|
||||
research_output: str = ""
|
||||
|
||||
# ── Baseline scores (original blog, evaluated before any enhancement) ──
|
||||
baseline_language_score: int = 0
|
||||
baseline_facts_score: int = 0
|
||||
baseline_structure_score: int = 0
|
||||
baseline_seo_score: int = 0
|
||||
baseline_geo_score: int = 0
|
||||
baseline_freshness_score: int = 0
|
||||
baseline_overall_score: int = 0
|
||||
|
||||
# Per-agent focused research briefs produced by the Supervisor.
|
||||
# Each specialist reads its own brief instead of the shared generic output.
|
||||
language_research: str = ""
|
||||
facts_research: str = ""
|
||||
structure_research: str = ""
|
||||
seo_research: str = ""
|
||||
geo_research: str = ""
|
||||
|
||||
language_output: str = ""
|
||||
|
||||
facts_output: str = ""
|
||||
|
||||
structure_output: str = ""
|
||||
|
||||
seo_output: str = ""
|
||||
|
||||
geo_output: str = ""
|
||||
|
||||
image_output: list[dict] = Field(default_factory=list)
|
||||
|
||||
aggregated_blog: str = ""
|
||||
|
||||
editorial_brief: str = ""
|
||||
|
||||
optimized_blog: str = ""
|
||||
|
||||
targeted_research_output: str = ""
|
||||
|
||||
language_score: int = 0
|
||||
|
||||
facts_score: int = 0
|
||||
|
||||
structure_score: int = 0
|
||||
|
||||
seo_score: int = 0
|
||||
|
||||
geo_score: int = 0
|
||||
|
||||
freshness_score: int = 0
|
||||
|
||||
overall_score: int = 0
|
||||
|
||||
language_feedback: str = ""
|
||||
|
||||
facts_feedback: str = ""
|
||||
|
||||
structure_feedback: str = ""
|
||||
|
||||
seo_feedback: str = ""
|
||||
|
||||
geo_feedback: str = ""
|
||||
|
||||
freshness_feedback: str = ""
|
||||
|
||||
iteration: int = 0
|
||||
|
||||
optimizer_iteration: int = 0
|
||||
|
||||
finished: bool = False
|
||||
|
||||
# User-configurable optimizer pass cap (set from UI slider).
|
||||
# Default 3 — good quality without burning quota.
|
||||
# Range: 1 (fast/cheap) to 8 (maximum quality).
|
||||
max_optimizer_passes: int = 3
|
||||
|
||||
# LLM provider: "groq" or "openai" — set from the UI before graph.invoke()
|
||||
llm_provider: str = "groq"
|
||||
|
||||
# Pathway & custom settings fields
|
||||
mode: str = "enhance"
|
||||
topic_idea: str = ""
|
||||
other_info: str = ""
|
||||
custom_model_name: str = ""
|
||||
custom_api_key: str = ""
|
||||
custom_base_url: str = ""
|
||||
job_id: int = 0
|
||||
parent_run_id: Optional[int] = None
|
||||
resume_node: Optional[str] = None
|
||||
|
||||
# Active agent name written by each node so the UI can display live status
|
||||
active_agent: str = ""
|
||||
|
||||
# ── Streaming ────────────────────────────────────────────────────────────
|
||||
# Queue populated by aggregator/optimizer during streaming LLM output.
|
||||
# The UI polls this every 0.15 s and appends chunks to the live preview.
|
||||
# None when streaming is not in use (CLI / non-Streamlit runs).
|
||||
stream_queue: Optional[Any] = Field(default=None, exclude=True)
|
||||
|
||||
# Callback function to notify the monitoring thread/UI of active agent transitions
|
||||
active_agent_callback: Optional[Callable[[str], None]] = Field(default=None, exclude=True)
|
||||
|
||||
class Config:
|
||||
arbitrary_types_allowed = True
|
||||
|
||||
def stream_chunk(self, token: str) -> None:
|
||||
"""Push one token/chunk into the stream queue (no-op if queue is None)."""
|
||||
if getattr(self, "job_id", 0):
|
||||
from db.database import BlogDatabase
|
||||
if BlogDatabase().is_cancel_requested(self.job_id):
|
||||
raise RuntimeError("Cancelled by user.")
|
||||
if self.stream_queue is not None:
|
||||
try:
|
||||
self.stream_queue.put_nowait(token)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def stream_done(self) -> None:
|
||||
"""Signal to the UI that streaming is finished for this agent pass."""
|
||||
if self.stream_queue is not None:
|
||||
try:
|
||||
self.stream_queue.put_nowait(None) # None = sentinel
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def plan_summary(self) -> str:
|
||||
"""Compact text summary of planner_output for agent prompts."""
|
||||
p = self.planner_output
|
||||
if not p:
|
||||
return ""
|
||||
|
||||
parts: list[str] = []
|
||||
|
||||
def _list(label: str, key: str) -> None:
|
||||
val = p.get(key)
|
||||
if val and isinstance(val, list):
|
||||
parts.append(f"{label}: {'; '.join(str(v) for v in val[:8])}")
|
||||
elif val and isinstance(val, str):
|
||||
parts.append(f"{label}: {val}")
|
||||
|
||||
_list("Missing topics", "missing_topics")
|
||||
_list("Missing keywords", "missing_keywords")
|
||||
_list("Missing entities", "missing_entities")
|
||||
_list("Missing FAQs", "missing_faqs")
|
||||
_list("Missing stats", "missing_statistics")
|
||||
_list("Missing examples", "missing_examples")
|
||||
_list("Weak sections", "weak_sections")
|
||||
_list("SEO plan", "seo_plan")
|
||||
_list("GEO plan", "geo_plan")
|
||||
|
||||
outline = p.get("target_outline")
|
||||
if outline and isinstance(outline, list):
|
||||
parts.append("Target outline: " + " > ".join(str(h) for h in outline[:10]))
|
||||
|
||||
return "\n".join(parts)
|
||||
|
||||
def research_snippet(self, max_chars: int = 1200) -> str:
|
||||
text = self.research_output
|
||||
if len(text) <= max_chars:
|
||||
return text
|
||||
return text[:max_chars].rsplit("\n", 1)[0] + "\n…[truncated]"
|
||||
|
||||
def blog_snippet(self, max_chars: int = 2500) -> str:
|
||||
if getattr(self, "mode", "enhance") == "generate":
|
||||
return "(No existing blog; we are generating a brand new blog from scratch. Plan and outline content from the provided topic and guidelines.)"
|
||||
text = self.cleaned_blog
|
||||
if len(text) <= max_chars:
|
||||
return text
|
||||
return text[:max_chars].rsplit("\n", 1)[0] + "\n…[truncated for brevity]"
|
||||
|
||||
def _truncate(self, text: str, max_chars: int) -> str:
|
||||
if not text or len(text) <= max_chars:
|
||||
return text or ""
|
||||
return text[:max_chars].rsplit("\n", 1)[0] + "\n…[truncated]"
|
||||
|
||||
def specialist_outputs_brief(self, max_chars_each: int = 700) -> dict:
|
||||
"""
|
||||
Truncated specialist outputs for the aggregator.
|
||||
Structure and SEO get a larger window so the aggregator receives
|
||||
the full keyword list, H2 headings, FAQ questions, and skeleton.
|
||||
"""
|
||||
return {
|
||||
"language": self._truncate(self.language_output, max_chars_each),
|
||||
"facts": self._truncate(self.facts_output, max_chars_each),
|
||||
"structure":self._truncate(self.structure_output, 1400),
|
||||
"seo": self._truncate(self.seo_output, 1400),
|
||||
"geo": self._truncate(self.geo_output, max_chars_each),
|
||||
}
|
||||
Reference in New Issue
Block a user