DrishtiSharma commited on
Commit
b358613
·
verified ·
1 Parent(s): 5f8acbb

Create layout2_v2.py

Browse files
Files changed (1) hide show
  1. lab/layout2_v2.py +281 -0
lab/layout2_v2.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
107
+ ## 1. Title
108
+ - Generate a compelling, creative, and relevant title that encapsulates the theme of the essay.
109
+
110
+ ## 2. Introduction (100-150 words)
111
+ - Clearly define the topic and its importance in the broader context.
112
+ - Provide a strong **thesis statement** that outlines the essay’s key argument.
113
+ - Briefly mention the **key themes** that will be explored in the body.
114
+ - Engage the reader with a thought-provoking fact, quote, or question.
115
+
116
+ ## 3. Main Body (Ensure clear organization and logical transitions)
117
+ Each section should:
118
+ - **Have a distinct, engaging subheading**.
119
+ - **Begin with a topic sentence** introducing the section’s main idea.
120
+ - **Include real-world examples, historical references, or statistical data**.
121
+ - **Maintain smooth transitions** between sections for cohesive reading.
122
+
123
+ ### Suggested Sections (Modify as Needed)
124
+ - **Historical Context**: Trace the origins and evolution of the topic over time.
125
+ - **Key Aspects**: Break down essential components (e.g., cultural, political, economic influences).
126
+ - **Modern Challenges & Debates**: Discuss **contemporary issues** and **conflicting viewpoints**.
127
+ - **Impact & Future Trends**: Examine how the topic influences the present and future.
128
+
129
+ ## 4. Conclusion (100-150 words)
130
+ - Concisely summarize key insights and arguments.
131
+ - Reinforce the essay��s thesis in light of the discussion.
132
+ - End with a **thought-provoking final statement**, such as:
133
+ - A **rhetorical question**.
134
+ - A **call to action**.
135
+ - A **broader reflection** on the topic’s long-term significance.
136
+
137
+ ## 5. Writing & Formatting Guidelines
138
+ - Maintain **formal, engaging, and precise** language.
139
+ - Ensure **clear paragraph structure and logical progression**.
140
+ - Avoid redundancy; keep insights sharp and impactful.
141
+ - Use **examples, expert opinions, or historical events** to strengthen arguments.
142
+ - Provide **citations or references** when possible.
143
+ """
144
+
145
+ response = app.graph.invoke(input={"topic": topic, "length": length, "prompt": refined_prompt})
146
+
147
+ return response
148
+
149
+
150
+
151
+ # Define Tabs
152
+ tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Viz"])
153
+
154
+ # 📜 Tab 1: Essay Generation
155
+ with tab1:
156
+ # Display chat messages from the session
157
+ if "messages" not in st.session_state:
158
+ st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
159
+
160
+ for message in st.session_state["messages"]:
161
+ with st.chat_message(message["role"]):
162
+ st.markdown(message["content"], unsafe_allow_html=True)
163
+
164
+ # Handle user input
165
+ if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state["chat_active"]):
166
+ st.chat_message("user").markdown(topic)
167
+ st.session_state["messages"].append({"role": "user", "content": topic})
168
+
169
+ with st.spinner("⏳ Generating your essay..."):
170
+ response = None
171
+ if app:
172
+ response = app.write_essay({"topic": topic})
173
+ else:
174
+ st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
175
+
176
+ # Handle the assistant's response
177
+ with st.chat_message("assistant"):
178
+ if response and "essay" in response: # Display essay preview and allow editing
179
+ essay = response["essay"]
180
+
181
+ # Create Two-Column Layout
182
+ col1, col2 = st.columns(2)
183
+
184
+ with col1:
185
+ st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
186
+ st.markdown(f"#### {essay['header']}")
187
+ st.markdown(essay["entry"])
188
+
189
+ for para in essay["paragraphs"]:
190
+ st.markdown(f"**{para['sub_header']}**")
191
+ st.markdown(para["paragraph"])
192
+
193
+ st.markdown("**🖊️ Conclusion:**")
194
+ st.markdown(essay["conclusion"])
195
+
196
+ with col2:
197
+ st.markdown("### ✍️ Edit Your Essay:")
198
+
199
+ # Combine all parts of the essay into one editable text field
200
+ full_essay_text = f"## {essay['header']}\n\n{essay['entry']}\n\n"
201
+ for para in essay["paragraphs"]:
202
+ full_essay_text += f"### {para['sub_header']}\n{para['paragraph']}\n\n"
203
+ full_essay_text += f"**Conclusion:**\n{essay['conclusion']}"
204
+
205
+ # Editable text area for the user
206
+ edited_essay = st.text_area("Edit Here:", value=full_essay_text, height=300)
207
+
208
+ # Save and Download buttons
209
+ save_col1, save_col2 = st.columns(2)
210
+
211
+ with save_col1:
212
+ if st.button("💾 Save as TXT"):
213
+ with open("edited_essay.txt", "w", encoding="utf-8") as file:
214
+ file.write(edited_essay)
215
+ with open("edited_essay.txt", "rb") as file:
216
+ st.download_button(label="⬇️ Download TXT", data=file, file_name="edited_essay.txt", mime="text/plain")
217
+
218
+ with save_col2:
219
+ if st.button("📄 Save as PDF"):
220
+ from fpdf import FPDF
221
+
222
+ pdf = FPDF()
223
+ pdf.set_auto_page_break(auto=True, margin=15)
224
+ pdf.add_page()
225
+ pdf.set_font("Arial", size=12)
226
+
227
+ for line in edited_essay.split("\n"):
228
+ pdf.cell(200, 10, txt=line, ln=True, align='L')
229
+
230
+ pdf.output("edited_essay.pdf")
231
+
232
+ with open("edited_essay.pdf", "rb") as file:
233
+ st.download_button(label="⬇️ Download PDF", data=file, file_name="edited_essay.pdf", mime="application/pdf")
234
+
235
+ # Provide download link for the original PDF
236
+ pdf_name = response.get("pdf_name")
237
+ if pdf_name and os.path.exists(pdf_name):
238
+ with open(pdf_name, "rb") as pdf_file:
239
+ b64 = base64.b64encode(pdf_file.read()).decode()
240
+ href = f"<a href='data:application/octet-stream;base64,{b64}' download='{pdf_name}'>📄 Click here to download the original PDF</a>"
241
+ st.markdown(href, unsafe_allow_html=True)
242
+
243
+ # Save response in session state
244
+ st.session_state["messages"].append(
245
+ {"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
246
+ )
247
+ elif response:
248
+ st.markdown(response["response"])
249
+ st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
250
+ else:
251
+ st.error("⚠️ No response received. Please try again.")
252
+
253
+ # 📊 Tab 2: Workflow Visualization
254
+ with tab2:
255
+ #st.subheader("📊 Multi-Agent Essay Writer Workflow Viz")
256
+
257
+ try:
258
+ graph_path = "/tmp/graph.png"
259
+ if os.path.exists(graph_path):
260
+ st.image(graph_path, caption="Multi-Agent Essay Writer Workflow Visualization", use_container_width=True)
261
+ else:
262
+ st.warning("⚠️ Workflow graph not found. Please run `graph.py` to regenerate `graph.png`.")
263
+
264
+ except Exception as e:
265
+ st.error("❌ An error occurred while generating the workflow visualization.")
266
+ st.text_area("Error Details:", traceback.format_exc(), height=200)
267
+
268
+
269
+ # Acknowledgement Section
270
+ st.markdown(
271
+ """
272
+ <div style="text-align: center; font-size: 14px; color: #555; padding-top: 200px; margin-top: 200px;">
273
+ <strong>Acknowledgement:</strong> This app is based on Mesut Duman's work:
274
+ <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
275
+ target="_blank" style="color: #007BFF; text-decoration: none;">
276
+ CrewAI Essay Writer
277
+ </a>
278
+ </div>
279
+ """,
280
+ unsafe_allow_html=True,
281
+ )