Spaces:
Paused
Paused
Commit Β·
fe5e069
1
Parent(s): 3c6db5c
Feat: Update research agent with multi-model support
Browse files- README.md +14 -4
- requirements.txt +7 -3
- src/RESEACH_AGENT.py +156 -0
- src/streamlit_app.py +187 -38
README.md
CHANGED
|
@@ -12,9 +12,19 @@ short_description: Reseach agent that converts the reseach into a fully fledged
|
|
| 12 |
license: mit
|
| 13 |
---
|
| 14 |
|
| 15 |
-
#
|
| 16 |
|
| 17 |
-
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
license: mit
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# Deep Math Research Agent πβοΈ
|
| 16 |
|
| 17 |
+
A LangGraph Multi-Agent system that researches a given topic extensively on the web and creates an intelligent outline. After confirmation/adjustment from the user through an interactive UI, it then generates a highly detailed Medium-styled technical article with deep mathematical formulas to support it!
|
| 18 |
|
| 19 |
+
## Features
|
| 20 |
+
|
| 21 |
+
- **Model Selection UI**: Choose between powerful LLM models directly in the sidebar!
|
| 22 |
+
- `Gemini 3 Flash`
|
| 23 |
+
- `Gemini 2.5 Flash`
|
| 24 |
+
- `Gemini 2.5 Flash Lite`
|
| 25 |
+
- `Gemini 3.1 Flash Lite`
|
| 26 |
+
- `Groq openai/gpt-oss-120b`
|
| 27 |
+
- **Dynamic API Key Input**: Securely insert your Google GenAI or Groq key depending on the model you want to run.
|
| 28 |
+
- **Deep Mathematical Emphasis**: Hard-prompts the AI to utilize LaTeX and Markdown to deeply explain formulas related to the research topic.
|
| 29 |
+
- **Human-in-the-Loop Outline Review**: You have complete control to add, edit, or remove sections from the planned outline before generation begins.
|
| 30 |
+
- **Downloadable Markdowns**: Safely compile your generation into a ready-to-go `.md` file!
|
requirements.txt
CHANGED
|
@@ -1,3 +1,7 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from typing import List, TypedDict, Dict, Any
|
| 4 |
+
from langgraph.graph import StateGraph, END
|
| 5 |
+
from langgraph.checkpoint.memory import MemorySaver
|
| 6 |
+
from langchain_groq import ChatGroq
|
| 7 |
+
from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper
|
| 8 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 9 |
+
|
| 10 |
+
def get_llm(model_name: str, temperature: float = 0.2):
|
| 11 |
+
if not model_name or "Groq" in model_name:
|
| 12 |
+
return ChatGroq(model="openai/gpt-oss-120b", temperature=temperature)
|
| 13 |
+
|
| 14 |
+
mapping = {
|
| 15 |
+
"Gemini 3 Flash": "gemini-3-flash-preview",
|
| 16 |
+
"Gemini 2.5 Flash": "gemini-2.5-flash",
|
| 17 |
+
"Gemini 2.5 Flash Lite": "gemini-2.5-flash-lite",
|
| 18 |
+
"Gemini 3.1 Flash Lite": "gemini-3.1-flash-lite-preview"
|
| 19 |
+
}
|
| 20 |
+
actual_model = mapping.get(model_name, "gemini-1.5-flash")
|
| 21 |
+
return ChatGoogleGenerativeAI(model=actual_model, temperature=temperature)
|
| 22 |
+
|
| 23 |
+
def extract_text(response) -> str:
|
| 24 |
+
content = response.content
|
| 25 |
+
if isinstance(content, list) and len(content) > 0:
|
| 26 |
+
if isinstance(content[0], dict) and "text" in content[0]:
|
| 27 |
+
return content[0]["text"]
|
| 28 |
+
return str(content[0])
|
| 29 |
+
return str(content)
|
| 30 |
+
|
| 31 |
+
# 1. Define the state for the graph
|
| 32 |
+
class AgentState(TypedDict):
|
| 33 |
+
topic: str
|
| 34 |
+
selected_model: str
|
| 35 |
+
research_queries: List[str]
|
| 36 |
+
gathered_info: List[str]
|
| 37 |
+
outline_sections: List[str]
|
| 38 |
+
current_section_idx: int
|
| 39 |
+
article_sections: List[str]
|
| 40 |
+
final_article: str
|
| 41 |
+
|
| 42 |
+
# 2. Add node functions
|
| 43 |
+
def generate_queries(state: AgentState):
|
| 44 |
+
topic = state['topic']
|
| 45 |
+
llm = get_llm(state.get("selected_model", ""), 0.2)
|
| 46 |
+
prompt = f"You are an expert researcher. Generate 5 distinct search queries to deeply research the topic: '{topic}'. Return only the queries separated by newlines, no numbers."
|
| 47 |
+
response = llm.invoke(prompt)
|
| 48 |
+
text = extract_text(response)
|
| 49 |
+
queries = [q.strip() for q in text.split('\n') if q.strip()]
|
| 50 |
+
return {"research_queries": queries}
|
| 51 |
+
|
| 52 |
+
def conduct_research(state: AgentState):
|
| 53 |
+
ddg = DuckDuckGoSearchAPIWrapper(max_results=5)
|
| 54 |
+
gathered = []
|
| 55 |
+
for query in state['research_queries']:
|
| 56 |
+
try:
|
| 57 |
+
results = ddg.run(query)
|
| 58 |
+
gathered.append(f"### Query: {query}\n{results}")
|
| 59 |
+
except Exception as e:
|
| 60 |
+
pass
|
| 61 |
+
return {"gathered_info": state.get('gathered_info', []) + gathered}
|
| 62 |
+
|
| 63 |
+
def create_outline(state: AgentState):
|
| 64 |
+
topic = state['topic']
|
| 65 |
+
info = "\n\n".join(state["gathered_info"])
|
| 66 |
+
llm = get_llm(state.get("selected_model", ""), 0.3)
|
| 67 |
+
|
| 68 |
+
prompt = f"""Based on the following research about '{topic}', create a comprehensive outline for a Medium article that takes 10+ minutes to read.
|
| 69 |
+
The article requires EXTREME technical and mathematical depth. Break it down into 6-8 comprehensive sections.
|
| 70 |
+
Include sections that explicitly dive into the underlying mathematical formulas, models, proofs, or complex implementations algorithmically where applicable.
|
| 71 |
+
|
| 72 |
+
Output the outline as a valid JSON list of strings. Example: ["Introduction", "Mathematical Foundations", "Algorithmic Implementation", "Conclusion"]
|
| 73 |
+
|
| 74 |
+
Research material:
|
| 75 |
+
{info[:15000]}
|
| 76 |
+
"""
|
| 77 |
+
response = llm.invoke(prompt)
|
| 78 |
+
text = extract_text(response)
|
| 79 |
+
try:
|
| 80 |
+
content = text.replace('```json', '').replace('```', '').strip()
|
| 81 |
+
sections = json.loads(content)
|
| 82 |
+
except Exception:
|
| 83 |
+
sections = [s for s in text.split('\n') if s.strip()]
|
| 84 |
+
return {"outline_sections": sections, "current_section_idx": 0, "article_sections": []}
|
| 85 |
+
|
| 86 |
+
def write_section(state: AgentState):
|
| 87 |
+
idx = state["current_section_idx"]
|
| 88 |
+
section_topic = state["outline_sections"][idx]
|
| 89 |
+
info = "\n\n".join(state["gathered_info"])
|
| 90 |
+
llm = get_llm(state.get("selected_model", ""), 0.4)
|
| 91 |
+
|
| 92 |
+
prompt = f"""You are an expert technical writer drafting a comprehensive Medium article piece by piece.
|
| 93 |
+
Topic of the whole article: {state['topic']}
|
| 94 |
+
Please write the complete content for the following section: "{section_topic}"
|
| 95 |
+
|
| 96 |
+
REQUIREMENTS:
|
| 97 |
+
- Make this section incredibly detailed, informative, and engaging (around 400-800 words).
|
| 98 |
+
- INCORPORATE DEEP MATHEMATICS: Where relevant, use mathematical formulas (format them using LaTeX/Markdown syntax like $$ formula $$ or inline $ formula $). Explain the math clearly in-depth.
|
| 99 |
+
- Dive into deep technical algorithmic implementations and complex theory if it applies to this section.
|
| 100 |
+
- Use clear markdown formatting (bolding, bullet points where necessary).
|
| 101 |
+
- Do not include main title header (H1) since this is just a section. Use H2 (##) for the section header.
|
| 102 |
+
|
| 103 |
+
Use the following research context to inform your writing:
|
| 104 |
+
{info[:20000]}
|
| 105 |
+
|
| 106 |
+
Output ONLY THE MARKDOWN CONTENT for this specific section, do not add introductory or concluding sentences unless it is the intro/conclusion section.
|
| 107 |
+
"""
|
| 108 |
+
response = llm.invoke(prompt)
|
| 109 |
+
text = extract_text(response)
|
| 110 |
+
new_sections = state.get("article_sections", []) + [text]
|
| 111 |
+
return {"article_sections": new_sections, "current_section_idx": idx + 1}
|
| 112 |
+
|
| 113 |
+
def should_continue_writing(state: AgentState):
|
| 114 |
+
if state["current_section_idx"] < len(state["outline_sections"]):
|
| 115 |
+
return "write_section"
|
| 116 |
+
return "compile_article"
|
| 117 |
+
|
| 118 |
+
def compile_article(state: AgentState):
|
| 119 |
+
topic = state["topic"]
|
| 120 |
+
title = f"# {topic.title()}\n\n"
|
| 121 |
+
full_article = title + "\n\n".join(state["article_sections"])
|
| 122 |
+
return {"final_article": full_article}
|
| 123 |
+
|
| 124 |
+
def review_outline(state: AgentState):
|
| 125 |
+
# This acts purely as a pause breakpoint for the human-in-the-loop to edit the outline
|
| 126 |
+
pass
|
| 127 |
+
|
| 128 |
+
# 3. Build Graph
|
| 129 |
+
def build_graph():
|
| 130 |
+
workflow = StateGraph(AgentState)
|
| 131 |
+
workflow.add_node("generate_queries", generate_queries)
|
| 132 |
+
workflow.add_node("conduct_research", conduct_research)
|
| 133 |
+
workflow.add_node("create_outline", create_outline)
|
| 134 |
+
workflow.add_node("review_outline", review_outline)
|
| 135 |
+
workflow.add_node("write_section", write_section)
|
| 136 |
+
workflow.add_node("compile_article", compile_article)
|
| 137 |
+
|
| 138 |
+
workflow.set_entry_point("generate_queries")
|
| 139 |
+
workflow.add_edge("generate_queries", "conduct_research")
|
| 140 |
+
workflow.add_edge("conduct_research", "create_outline")
|
| 141 |
+
workflow.add_edge("create_outline", "review_outline")
|
| 142 |
+
workflow.add_edge("review_outline", "write_section")
|
| 143 |
+
|
| 144 |
+
workflow.add_conditional_edges(
|
| 145 |
+
"write_section",
|
| 146 |
+
should_continue_writing,
|
| 147 |
+
{
|
| 148 |
+
"write_section": "write_section",
|
| 149 |
+
"compile_article": "compile_article"
|
| 150 |
+
}
|
| 151 |
+
)
|
| 152 |
+
workflow.add_edge("compile_article", END)
|
| 153 |
+
|
| 154 |
+
# Add checkpointer and interrupt before REVIEWING the outline, not writing!
|
| 155 |
+
memory = MemorySaver()
|
| 156 |
+
return workflow.compile(check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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
|
|
|
| 3 |
import streamlit as st
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from RESEACH_AGENT import build_graph
|
| 6 |
+
|
| 7 |
+
# --- Streamlit UI Build ---
|
| 8 |
+
st.set_page_config(page_title="Deep Math Research Agent", page_icon="π", layout="wide")
|
| 9 |
+
|
| 10 |
+
st.title("π Deep Math & Research Article Writer βοΈ")
|
| 11 |
+
st.markdown("Enter a topic and provide your **Groq API key** in the sidebar. The AI agent will thoroughly research the topic online, draft an outline (which you can review and edit), and iteratively write an in-depth article with **deep mathematical formula support**.")
|
| 12 |
+
|
| 13 |
+
# Initialize Session States
|
| 14 |
+
if "thread_id" not in st.session_state:
|
| 15 |
+
st.session_state.thread_id = str(uuid.uuid4())
|
| 16 |
+
if "agent_app" not in st.session_state:
|
| 17 |
+
st.session_state.agent_app = build_graph()
|
| 18 |
+
if "phase" not in st.session_state:
|
| 19 |
+
st.session_state.phase = "setup"
|
| 20 |
+
if "final_article" not in st.session_state:
|
| 21 |
+
st.session_state.final_article = ""
|
| 22 |
+
|
| 23 |
+
# Sidebar for configuration
|
| 24 |
+
with st.sidebar:
|
| 25 |
+
st.header("βοΈ Configuration")
|
| 26 |
+
|
| 27 |
+
selected_model = st.selectbox(
|
| 28 |
+
"Select Model",
|
| 29 |
+
[
|
| 30 |
+
"Gemini 3 Flash",
|
| 31 |
+
"Gemini 2.5 Flash",
|
| 32 |
+
"Gemini 2.5 Flash Lite",
|
| 33 |
+
"Gemini 3.1 Flash Lite",
|
| 34 |
+
"Groq openai gpt oss 120b"
|
| 35 |
+
]
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
api_key_label = "Groq API Key" if "Groq" in selected_model else "Gemini API Key"
|
| 39 |
+
user_api_key = st.text_input(api_key_label, type="password", help=f"Provide your {api_key_label}")
|
| 40 |
+
|
| 41 |
+
if user_api_key:
|
| 42 |
+
if "Groq" in selected_model:
|
| 43 |
+
os.environ["GROQ_API_KEY"] = user_api_key
|
| 44 |
+
else:
|
| 45 |
+
os.environ["GEMINI_API_KEY"] = user_api_key
|
| 46 |
+
os.environ["GOOGLE_API_KEY"] = user_api_key
|
| 47 |
+
|
| 48 |
+
st.session_state.selected_model = selected_model
|
| 49 |
+
|
| 50 |
+
st.markdown("---")
|
| 51 |
+
st.info("""
|
| 52 |
+
**How this Agent works:**
|
| 53 |
+
1. Generates 5 precise web search queries.
|
| 54 |
+
2. Browses the web (via DuckDuckGo) aggregating information.
|
| 55 |
+
3. Plans an extensive article outline.
|
| 56 |
+
4. **(Human-in-the-loop)** You review, edit, or add sections to the outline on an interactive board!
|
| 57 |
+
5. Iteratively writes each section using heavy mathematical depth and LaTeX formulas.
|
| 58 |
+
6. Compiles an exhaustive final article ready to download!
|
| 59 |
+
""")
|
| 60 |
+
if st.button("Reset Session π"):
|
| 61 |
+
st.session_state.clear()
|
| 62 |
+
st.rerun()
|
| 63 |
+
|
| 64 |
+
# --- App Logic based on Phase ---
|
| 65 |
+
|
| 66 |
+
if st.session_state.phase == "setup":
|
| 67 |
+
topic_input = st.text_input("What topic would you like the agent to research?", placeholder="e.g. The detailed mathematics of the transformers attention mechanism")
|
| 68 |
+
|
| 69 |
+
if st.button("Generate Outline π§ ", type="primary"):
|
| 70 |
+
if not user_api_key:
|
| 71 |
+
st.error("Please provide your API Key in the sidebar.")
|
| 72 |
+
elif not topic_input:
|
| 73 |
+
st.warning("Please enter a topic to research.")
|
| 74 |
+
else:
|
| 75 |
+
initial_state = {
|
| 76 |
+
"topic": topic_input,
|
| 77 |
+
"selected_model": st.session_state.selected_model,
|
| 78 |
+
"research_queries": [],
|
| 79 |
+
"gathered_info": [],
|
| 80 |
+
"outline_sections": [],
|
| 81 |
+
"current_section_idx": 0,
|
| 82 |
+
"article_sections": [],
|
| 83 |
+
"final_article": ""
|
| 84 |
+
}
|
| 85 |
+
config = {"configurable": {"thread_id": st.session_state.thread_id}}
|
| 86 |
+
|
| 87 |
+
with st.status("Agent Pipeline Running...", expanded=True) as status:
|
| 88 |
+
try:
|
| 89 |
+
# Stream until it hits the interrupt breakpoint (before write_section)
|
| 90 |
+
for step in st.session_state.agent_app.stream(initial_state, config):
|
| 91 |
+
for node_name, state_update in step.items():
|
| 92 |
+
if node_name == "generate_queries":
|
| 93 |
+
st.write(f"β
Generated {len(state_update.get('research_queries', []))} deep search queries.")
|
| 94 |
+
elif node_name == "conduct_research":
|
| 95 |
+
st.write("β
Conducted continuous web research and aggregated sources.")
|
| 96 |
+
elif node_name == "create_outline":
|
| 97 |
+
st.write(f"β
Planned extensive article outline based on math and context.")
|
| 98 |
+
|
| 99 |
+
status.update(label="Outline Ready for Review!", state="complete", expanded=False)
|
| 100 |
+
st.session_state.phase = "review"
|
| 101 |
+
st.rerun()
|
| 102 |
+
except Exception as e:
|
| 103 |
+
status.update(label=f"An error occurred: {e}", state="error")
|
| 104 |
+
st.error(f"Error Details: {e}")
|
| 105 |
+
|
| 106 |
+
elif st.session_state.phase == "review":
|
| 107 |
+
st.subheader("π Review and Edit Outline Board")
|
| 108 |
+
st.markdown("Below is the planned outline structure. You can **edit section names directly in the table**, **add completely new sections** by clicking the bottom row, or hover and **delete sections**.")
|
| 109 |
+
|
| 110 |
+
# Get current state from LangGraph
|
| 111 |
+
config = {"configurable": {"thread_id": st.session_state.thread_id}}
|
| 112 |
+
current_state = st.session_state.agent_app.get_state(config).values
|
| 113 |
+
current_outline = current_state.get("outline_sections", [])
|
| 114 |
+
|
| 115 |
+
# Render Interactive DataFrame
|
| 116 |
+
df = pd.DataFrame({"Section Title": current_outline})
|
| 117 |
+
|
| 118 |
+
edited_df = st.data_editor(
|
| 119 |
+
df,
|
| 120 |
+
num_rows="dynamic",
|
| 121 |
+
use_container_width=True,
|
| 122 |
+
hide_index=False
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if st.button("Approve & Start Writing Article π", type="primary"):
|
| 126 |
+
updated_outline = edited_df["Section Title"].dropna().tolist()
|
| 127 |
+
|
| 128 |
+
# Update the LangGraph state with user's modified outline!
|
| 129 |
+
st.session_state.agent_app.update_state(config, {"outline_sections": updated_outline})
|
| 130 |
+
st.session_state.phase = "writing"
|
| 131 |
+
st.rerun()
|
| 132 |
+
|
| 133 |
+
elif st.session_state.phase == "writing":
|
| 134 |
+
st.subheader("ποΈ Writing Article Sections...")
|
| 135 |
+
config = {"configurable": {"thread_id": st.session_state.thread_id}}
|
| 136 |
+
|
| 137 |
+
with st.status("Writing full mathematical article in depth...", expanded=True) as status:
|
| 138 |
+
try:
|
| 139 |
+
# Resume graph execution (streaming from none)
|
| 140 |
+
final_state_snapshot = None
|
| 141 |
+
for step in st.session_state.agent_app.stream(None, config):
|
| 142 |
+
for node_name, state_update in step.items():
|
| 143 |
+
if node_name == "write_section":
|
| 144 |
+
idx = state_update.get('current_section_idx', 1)
|
| 145 |
+
latest_state = st.session_state.agent_app.get_state(config).values
|
| 146 |
+
total = len(latest_state.get('outline_sections', []))
|
| 147 |
+
section_name = latest_state['outline_sections'][idx - 1]
|
| 148 |
+
st.write(f"βοΈ Wrote section {idx}/{total}: **{section_name}**")
|
| 149 |
+
elif node_name == "compile_article":
|
| 150 |
+
final_state_snapshot = state_update
|
| 151 |
+
st.write("π Article compiled successfully into full Markdown!")
|
| 152 |
+
|
| 153 |
+
if final_state_snapshot and "final_article" in final_state_snapshot:
|
| 154 |
+
st.session_state.final_article = final_state_snapshot["final_article"]
|
| 155 |
+
else:
|
| 156 |
+
latest_state = st.session_state.agent_app.get_state(config).values
|
| 157 |
+
st.session_state.final_article = latest_state.get("final_article", "")
|
| 158 |
+
|
| 159 |
+
st.session_state.phase = "done"
|
| 160 |
+
status.update(label="Article Generation Complete! π", state="complete", expanded=False)
|
| 161 |
+
st.rerun()
|
| 162 |
+
|
| 163 |
+
except Exception as e:
|
| 164 |
+
status.update(label=f"An error occurred: {e}", state="error")
|
| 165 |
+
st.error(f"Error Details: {e}")
|
| 166 |
+
|
| 167 |
+
elif st.session_state.phase == "done":
|
| 168 |
+
st.success("Your article is ready!")
|
| 169 |
+
st.markdown("---")
|
| 170 |
+
|
| 171 |
+
config = {"configurable": {"thread_id": st.session_state.thread_id}}
|
| 172 |
+
latest_state = st.session_state.agent_app.get_state(config).values
|
| 173 |
+
topic_input = latest_state.get("topic", "Generated_Article")
|
| 174 |
+
|
| 175 |
+
if st.button("Reset Session π"):
|
| 176 |
+
st.session_state.clear()
|
| 177 |
+
st.rerun()
|
| 178 |
+
|
| 179 |
+
# Download button
|
| 180 |
+
st.download_button(
|
| 181 |
+
label="π₯ Download Final Article as Markdown",
|
| 182 |
+
data=st.session_state.final_article,
|
| 183 |
+
file_name=f"{topic_input.replace(' ', '_')}_article.md",
|
| 184 |
+
mime="text/markdown"
|
| 185 |
+
)
|
| 186 |
|
| 187 |
+
# Display the preview below
|
| 188 |
+
st.markdown("### Preview")
|
| 189 |
+
st.markdown(st.session_state.final_article)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|