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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from graph import EssayWriter, RouteQuery, GraphState
|
3 |
+
from crew import *
|
4 |
+
import os
|
5 |
+
import traceback
|
6 |
+
import base64
|
7 |
+
|
8 |
+
# Install Graphviz if not found
|
9 |
+
if os.system("which dot") != 0:
|
10 |
+
os.system("apt-get update && apt-get install -y graphviz")
|
11 |
+
|
12 |
+
st.markdown(
|
13 |
+
"""
|
14 |
+
<h1 style="text-align: center; white-space: nowrap; font-size: 2.5em;">
|
15 |
+
Multi-Agent Essay Writing Assistant
|
16 |
+
</h1>
|
17 |
+
""",
|
18 |
+
unsafe_allow_html=True
|
19 |
+
)
|
20 |
+
|
21 |
+
# Ensure session state variables are initialized properly
|
22 |
+
if "messages" not in st.session_state:
|
23 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
24 |
+
|
25 |
+
if "app" not in st.session_state:
|
26 |
+
st.session_state["app"] = None
|
27 |
+
|
28 |
+
if "chat_active" not in st.session_state:
|
29 |
+
st.session_state["chat_active"] = True
|
30 |
+
|
31 |
+
# Sidebar with essay settings and user-defined length
|
32 |
+
with st.sidebar:
|
33 |
+
st.subheader("About:")
|
34 |
+
st.info(
|
35 |
+
"\n\n 1. This app uses the 'gpt-4o-mini-2024-07-18' model."
|
36 |
+
"\n\n 2. Writing essays may take some time, approximately 1-2 minutes."
|
37 |
+
)
|
38 |
+
|
39 |
+
# API Key Retrieval
|
40 |
+
openai_key = st.secrets.get("OPENAI_API_KEY", "")
|
41 |
+
|
42 |
+
st.divider()
|
43 |
+
|
44 |
+
# User-defined essay length selection
|
45 |
+
st.subheader("📝 Configure Essay Settings:")
|
46 |
+
essay_length = st.number_input(
|
47 |
+
"Select Essay Length (words):",
|
48 |
+
min_value=150,
|
49 |
+
max_value=500,
|
50 |
+
value=250,
|
51 |
+
step=50
|
52 |
+
)
|
53 |
+
|
54 |
+
st.divider()
|
55 |
+
|
56 |
+
# Reference section
|
57 |
+
st.subheader("📖 References:")
|
58 |
+
st.markdown(
|
59 |
+
"[1. Multi-Agent System with CrewAI and LangChain](https://discuss.streamlit.io/t/new-project-i-have-build-a-multi-agent-system-with-crewai-and-langchain/84002)",
|
60 |
+
unsafe_allow_html=True
|
61 |
+
)
|
62 |
+
|
63 |
+
# Initialize agents function
|
64 |
+
def initialize_agents():
|
65 |
+
if not openai_key:
|
66 |
+
st.error("⚠️ OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets.")
|
67 |
+
st.session_state["chat_active"] = True
|
68 |
+
return None
|
69 |
+
|
70 |
+
os.environ["OPENAI_API_KEY"] = openai_key
|
71 |
+
try:
|
72 |
+
# Prevent re-initialization
|
73 |
+
if "app" in st.session_state and st.session_state["app"] is not None:
|
74 |
+
return st.session_state["app"]
|
75 |
+
|
76 |
+
# Initialize the full EssayWriter instance
|
77 |
+
essay_writer = EssayWriter() # Store the full instance
|
78 |
+
st.session_state["app"] = essay_writer # Now contains `graph`
|
79 |
+
st.session_state["chat_active"] = False # Enable chat after successful initialization
|
80 |
+
|
81 |
+
return essay_writer
|
82 |
+
except Exception as e:
|
83 |
+
st.error(f"❌ Error initializing agents: {e}")
|
84 |
+
st.session_state["chat_active"] = True
|
85 |
+
return None
|
86 |
+
|
87 |
+
|
88 |
+
# Automatically initialize agents on app load
|
89 |
+
if st.session_state["app"] is None:
|
90 |
+
st.session_state["app"] = initialize_agents()
|
91 |
+
|
92 |
+
if st.session_state["app"] is None:
|
93 |
+
st.error("⚠️ Failed to initialize agents. Please check your API key and restart the app.")
|
94 |
+
|
95 |
+
app = st.session_state["app"]
|
96 |
+
|
97 |
+
# Function to invoke the agent and generate a response
|
98 |
+
def generate_response(topic, length):
|
99 |
+
if not app or not hasattr(app, "graph"):
|
100 |
+
st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
|
101 |
+
return {"response": "Error: Agents not initialized."}
|
102 |
+
|
103 |
+
# Refined prompt for better essay generation
|
104 |
+
refined_prompt = f"""
|
105 |
+
Write a well-structured, engaging, and informative essay on "{topic}". The essay should be approximately {length} words and follow this structured format:
|
106 |
+
## 1. Title
|
107 |
+
- Generate a compelling, creative, and relevant title that encapsulates the theme of the essay.
|
108 |
+
## 2. Introduction (100-150 words)
|
109 |
+
- Clearly define the topic and its importance in the broader context.
|
110 |
+
- Provide a strong **thesis statement** that outlines the essay’s key argument.
|
111 |
+
- Briefly mention the **key themes** that will be explored in the body.
|
112 |
+
- Engage the reader with a thought-provoking fact, quote, or question.
|
113 |
+
## 3. Main Body (Ensure clear organization and logical transitions)
|
114 |
+
Each section should:
|
115 |
+
- **Have a distinct, engaging subheading**.
|
116 |
+
- **Begin with a topic sentence** introducing the section’s main idea.
|
117 |
+
- **Include real-world examples, historical references, or statistical data**.
|
118 |
+
- **Maintain smooth transitions** between sections for cohesive reading.
|
119 |
+
### Suggested Sections (Modify as Needed)
|
120 |
+
- **Historical Context**: Trace the origins and evolution of the topic over time.
|
121 |
+
- **Key Aspects**: Break down essential components (e.g., cultural, political, economic influences).
|
122 |
+
- **Modern Challenges & Debates**: Discuss **contemporary issues** and **conflicting viewpoints**.
|
123 |
+
- **Impact & Future Trends**: Examine how the topic influences the present and future.
|
124 |
+
## 4. Conclusion (100-150 words)
|
125 |
+
- Concisely summarize key insights and arguments.
|
126 |
+
- Reinforce the essay’s thesis in light of the discussion.
|
127 |
+
- End with a **thought-provoking final statement**, such as:
|
128 |
+
- A **rhetorical question**.
|
129 |
+
- A **call to action**.
|
130 |
+
- A **broader reflection** on the topic’s long-term significance.
|
131 |
+
## 5. Writing & Formatting Guidelines
|
132 |
+
- Maintain **formal, engaging, and precise** language.
|
133 |
+
- Ensure **clear paragraph structure and logical progression**.
|
134 |
+
- Avoid redundancy; keep insights sharp and impactful.
|
135 |
+
- Use **examples, expert opinions, or historical events** to strengthen arguments.
|
136 |
+
- Provide **citations or references** when possible.
|
137 |
+
"""
|
138 |
+
|
139 |
+
response = app.graph.invoke(input={"topic": topic, "length": length, "prompt": refined_prompt})
|
140 |
+
|
141 |
+
return response
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
# Define Tabs
|
146 |
+
tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Viz"])
|
147 |
+
|
148 |
+
# 📜 Tab 1: Essay Generation
|
149 |
+
with tab1:
|
150 |
+
# Display chat messages from the session
|
151 |
+
if "messages" not in st.session_state:
|
152 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
153 |
+
|
154 |
+
for message in st.session_state["messages"]:
|
155 |
+
with st.chat_message(message["role"]):
|
156 |
+
st.markdown(message["content"], unsafe_allow_html=True)
|
157 |
+
|
158 |
+
# Use text_input to allow a default value, but do not trigger generation immediately
|
159 |
+
topic = st.text_input("📝 Provide an essay topic:", value="Write an essay on the cultural diversity of India")
|
160 |
+
|
161 |
+
# Add a button to trigger essay generation
|
162 |
+
if st.button("Generate Essay"):
|
163 |
+
if topic:
|
164 |
+
# Store user message in the chat
|
165 |
+
st.chat_message("user").markdown(topic)
|
166 |
+
st.session_state["messages"].append({"role": "user", "content": topic})
|
167 |
+
|
168 |
+
with st.spinner("⏳ Generating your essay..."):
|
169 |
+
response = None
|
170 |
+
if app:
|
171 |
+
response = app.write_essay({"topic": topic})
|
172 |
+
else:
|
173 |
+
st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
|
174 |
+
|
175 |
+
# Store assistant response and display it
|
176 |
+
with st.chat_message("assistant"):
|
177 |
+
if response and "essay" in response: # Display essay preview and allow editing
|
178 |
+
essay = response["essay"]
|
179 |
+
|
180 |
+
# Store response in session state
|
181 |
+
assistant_response = f"Here is your {essay_length}-word essay preview and the download link."
|
182 |
+
st.session_state["messages"].append({"role": "assistant", "content": assistant_response})
|
183 |
+
|
184 |
+
# Create Two-Column Layout
|
185 |
+
col1, col2 = st.columns(2)
|
186 |
+
|
187 |
+
with col1:
|
188 |
+
st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
|
189 |
+
st.markdown(f"#### {essay['header']}")
|
190 |
+
st.markdown(essay["entry"])
|
191 |
+
|
192 |
+
for para in essay["paragraphs"]:
|
193 |
+
st.markdown(f"**{para['sub_header']}**")
|
194 |
+
st.markdown(para["paragraph"])
|
195 |
+
|
196 |
+
st.markdown("**🖊️ Conclusion:**")
|
197 |
+
st.markdown(essay["conclusion"])
|
198 |
+
|
199 |
+
with col2:
|
200 |
+
st.markdown("### ✍️ Edit Your Essay:")
|
201 |
+
|
202 |
+
# Combine all parts of the essay into one editable text field
|
203 |
+
full_essay_text = f"## {essay['header']}\n\n{essay['entry']}\n\n"
|
204 |
+
for para in essay["paragraphs"]:
|
205 |
+
full_essay_text += f"### {para['sub_header']}\n{para['paragraph']}\n\n"
|
206 |
+
full_essay_text += f"**Conclusion:**\n{essay['conclusion']}"
|
207 |
+
|
208 |
+
# Editable text area for the user
|
209 |
+
edited_essay = st.text_area("Edit Here:", value=full_essay_text, height=300)
|
210 |
+
|
211 |
+
# Save and Download buttons
|
212 |
+
save_col1, save_col2 = st.columns(2)
|
213 |
+
|
214 |
+
with save_col1:
|
215 |
+
if st.button("💾 Save as TXT"):
|
216 |
+
with open("edited_essay.txt", "w", encoding="utf-8") as file:
|
217 |
+
file.write(edited_essay)
|
218 |
+
with open("edited_essay.txt", "rb") as file:
|
219 |
+
st.download_button(label="⬇️ Download TXT", data=file, file_name="edited_essay.txt", mime="text/plain")
|
220 |
+
|
221 |
+
with save_col2:
|
222 |
+
if st.button("📄 Save as PDF"):
|
223 |
+
from fpdf import FPDF
|
224 |
+
|
225 |
+
pdf = FPDF()
|
226 |
+
pdf.set_auto_page_break(auto=True, margin=15)
|
227 |
+
pdf.add_page()
|
228 |
+
pdf.set_font("Arial", size=12)
|
229 |
+
|
230 |
+
for line in edited_essay.split("\n"):
|
231 |
+
pdf.cell(200, 10, txt=line, ln=True, align='L')
|
232 |
+
|
233 |
+
pdf.output("edited_essay.pdf")
|
234 |
+
|
235 |
+
with open("edited_essay.pdf", "rb") as file:
|
236 |
+
st.download_button(label="⬇️ Download PDF", data=file, file_name="edited_essay.pdf", mime="application/pdf")
|
237 |
+
|
238 |
+
# Provide download link for the original PDF
|
239 |
+
pdf_name = response.get("pdf_name")
|
240 |
+
if pdf_name and os.path.exists(pdf_name):
|
241 |
+
with open(pdf_name, "rb") as pdf_file:
|
242 |
+
b64 = base64.b64encode(pdf_file.read()).decode()
|
243 |
+
href = f"<a href='data:application/octet-stream;base64,{b64}' download='{pdf_name}'>📄 Click here to download the original PDF</a>"
|
244 |
+
st.markdown(href, unsafe_allow_html=True)
|
245 |
+
|
246 |
+
# Save response in session state
|
247 |
+
st.session_state["messages"].append(
|
248 |
+
{"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
|
249 |
+
)
|
250 |
+
elif response:
|
251 |
+
st.markdown(response["response"])
|
252 |
+
st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
|
253 |
+
else:
|
254 |
+
st.error("⚠️ No response received. Please try again.")
|
255 |
+
|
256 |
+
|
257 |
+
|
258 |
+
# 📊 Tab 2: Workflow Visualization
|
259 |
+
with tab2:
|
260 |
+
#st.subheader("📊 Multi-Agent Essay Writer Workflow Viz")
|
261 |
+
|
262 |
+
try:
|
263 |
+
graph_path = "/tmp/graph.png"
|
264 |
+
if os.path.exists(graph_path):
|
265 |
+
st.image(graph_path, caption="Multi-Agent Essay Writer Workflow Visualization", use_container_width=True)
|
266 |
+
else:
|
267 |
+
st.warning("⚠️ Workflow graph not found. Please run `graph.py` to regenerate `graph.png`.")
|
268 |
+
|
269 |
+
except Exception as e:
|
270 |
+
st.error("❌ An error occurred while generating the workflow visualization.")
|
271 |
+
st.text_area("Error Details:", traceback.format_exc(), height=200)
|
272 |
+
|
273 |
+
|
274 |
+
# Acknowledgement Section
|
275 |
+
st.markdown(
|
276 |
+
"""
|
277 |
+
<div style="text-align: center; font-size: 14px; color: #555; padding-top: 200px; margin-top: 200px;">
|
278 |
+
<strong>Acknowledgement:</strong> This app is based on Mesut Duman's work:
|
279 |
+
<a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
|
280 |
+
target="_blank" style="color: #007BFF; text-decoration: none;">
|
281 |
+
CrewAI Essay Writer
|
282 |
+
</a>
|
283 |
+
</div>
|
284 |
+
""",
|
285 |
+
unsafe_allow_html=True,
|
286 |
+
)
|