DrishtiSharma commited on
Commit
89143e2
·
verified ·
1 Parent(s): 904e7c3

Create temp_app.py

Browse files
Files changed (1) hide show
  1. temp_app.py +299 -0
temp_app.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Define section allocations dynamically based on length
104
+ if length <= 300:
105
+ intro_limit = length // 5 # Shorter intro
106
+ body_limit = length // 2 # 2-3 key sections only
107
+ conclusion_limit = length // 5 # Brief closing
108
+ num_sections = 2 # Fewer key points
109
+ else:
110
+ intro_limit = length // 6 # Slightly shorter intro
111
+ body_limit = length // 1.8 # Allows more depth
112
+ conclusion_limit = length // 6 # Balanced closing
113
+ num_sections = 3 if length <= 400 else 4 # More sections for 400-500+ words
114
+
115
+ # Adjusted structured prompt
116
+ refined_prompt = f"""
117
+ Write a well-structured, engaging, and informative essay on "{topic}" with **EXACTLY {length} words**.
118
+ ### **Structure:**
119
+ - **Title**: A compelling, creative title (max 10 words).
120
+ - **Introduction** ({intro_limit} words max):
121
+ - Define the topic & its importance concisely.
122
+ - Provide a strong thesis statement.
123
+ - Briefly mention key themes.
124
+ - **Main Body** ({body_limit} words max):
125
+ - Cover **{num_sections} key aspects only**.
126
+ - Each section must have:
127
+ - A clear **subheading**.
128
+ - A **topic sentence** & supporting details.
129
+ - **Examples, statistics, or historical references** (if relevant).
130
+ - Ensure logical transitions between sections.
131
+ - **Conclusion** ({conclusion_limit} words max):
132
+ - Summarize key insights concisely.
133
+ - Reinforce thesis based on discussion.
134
+ - End with a **thought-provoking** final statement (question, reflection, or call to action).
135
+ ### **Important Rules:**
136
+ - DO NOT exceed {length} words.
137
+ - Avoid redundancy & filler sentences.
138
+ - Merge similar ideas to keep flow natural.
139
+ - Use precise, impactful language.
140
+ - Ensure balanced coverage** (not too broad or too specific).
141
+ - STOP when {length} words are reached.
142
+ """
143
+
144
+ # Invoke AI model with a controlled word limit
145
+ response = app.graph.invoke(input={
146
+ "topic": topic,
147
+ "length": length,
148
+ "prompt": refined_prompt,
149
+ "max_tokens": length * 1.2 # Ensures generation doesn’t exceed limit
150
+ })
151
+
152
+ return response
153
+
154
+
155
+ # Define Tabs
156
+ tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Viz"])
157
+
158
+ # 📜 Tab 1: Essay Generation
159
+ with tab1:
160
+ # Display chat messages from the session
161
+ if "messages" not in st.session_state:
162
+ st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
163
+
164
+ for message in st.session_state["messages"]:
165
+ with st.chat_message(message["role"]):
166
+ st.markdown(message["content"], unsafe_allow_html=True)
167
+
168
+ # Input
169
+ topic = st.text_input("📝 Provide an essay topic:", value="Write an essay on the cultural diversity of India")
170
+
171
+ # Add spacing
172
+ st.write("")
173
+
174
+ # Generate button
175
+ if st.button("🚀 Generate Essay"):
176
+ if topic and topic.strip(): # Ensure it's not empty
177
+ # Store user message only if it's not already stored
178
+ if not any(msg["content"] == topic for msg in st.session_state["messages"]):
179
+ st.session_state["messages"].append({"role": "user", "content": topic})
180
+
181
+ with st.spinner("⏳ Generating your essay..."):
182
+ response = None
183
+ if app:
184
+ response = app.write_essay({"topic": topic})
185
+ else:
186
+ st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
187
+
188
+ # Store and display assistant response
189
+ if response and "essay" in response:
190
+ essay = response["essay"]
191
+
192
+ assistant_response = f"Here is your {essay_length}-word essay preview and the download link."
193
+ st.session_state["messages"].append({"role": "assistant", "content": assistant_response})
194
+
195
+ st.chat_message("assistant").markdown(assistant_response)
196
+
197
+ # Create Two-Column Layout
198
+ col1, col2 = st.columns(2)
199
+
200
+ with col1:
201
+ st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
202
+ st.markdown(f"#### {essay['header']}")
203
+ st.markdown(essay["entry"])
204
+
205
+ for para in essay["paragraphs"]:
206
+ st.markdown(f"**{para['sub_header']}**")
207
+ st.markdown(para["paragraph"])
208
+
209
+ st.markdown("**🖊️ Conclusion:**")
210
+ st.markdown(essay["conclusion"])
211
+
212
+ with col2:
213
+ st.markdown("### ✍️ Edit Your Essay:")
214
+
215
+ # Combine all parts of the essay into one editable text field
216
+ full_essay_text = f"## {essay['header']}\n\n{essay['entry']}\n\n"
217
+ for para in essay["paragraphs"]:
218
+ full_essay_text += f"### {para['sub_header']}\n{para['paragraph']}\n\n"
219
+ full_essay_text += f"**Conclusion:**\n{essay['conclusion']}"
220
+
221
+ # Editable text area for the user
222
+ edited_essay = st.text_area("Edit Here:", value=full_essay_text, height=300)
223
+
224
+ # Save and Download buttons
225
+ save_col1, save_col2 = st.columns(2)
226
+
227
+ with save_col1:
228
+ if st.button("💾 Save as TXT"):
229
+ with open("edited_essay.txt", "w", encoding="utf-8") as file:
230
+ file.write(edited_essay)
231
+ with open("edited_essay.txt", "rb") as file:
232
+ st.download_button(label="⬇️ Download TXT", data=file, file_name="edited_essay.txt", mime="text/plain")
233
+
234
+ with save_col2:
235
+ if st.button("📄 Save as PDF"):
236
+ from fpdf import FPDF
237
+
238
+ pdf = FPDF()
239
+ pdf.set_auto_page_break(auto=True, margin=15)
240
+ pdf.add_page()
241
+ pdf.set_font("Arial", size=12)
242
+
243
+ for line in edited_essay.split("\n"):
244
+ pdf.cell(200, 10, txt=line, ln=True, align='L')
245
+
246
+ pdf.output("edited_essay.pdf")
247
+
248
+ with open("edited_essay.pdf", "rb") as file:
249
+ st.download_button(label="⬇️ Download PDF", data=file, file_name="edited_essay.pdf", mime="application/pdf")
250
+
251
+ # Provide download link for the original PDF
252
+ pdf_name = response.get("pdf_name")
253
+ if pdf_name and os.path.exists(pdf_name):
254
+ with open(pdf_name, "rb") as pdf_file:
255
+ b64 = base64.b64encode(pdf_file.read()).decode()
256
+ href = f"<a href='data:application/octet-stream;base64,{b64}' download='{pdf_name}'>📄 Click here to download the original PDF</a>"
257
+ st.markdown(href, unsafe_allow_html=True)
258
+
259
+ # Save response in session state
260
+ st.session_state["messages"].append(
261
+ {"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
262
+ )
263
+ elif response:
264
+ st.markdown(response["response"])
265
+ st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
266
+ else:
267
+ st.error("⚠️ No response received. Please try again.")
268
+
269
+
270
+
271
+ # 📊 Tab 2: Workflow Visualization
272
+ with tab2:
273
+ #st.subheader("📊 Multi-Agent Essay Writer Workflow Viz")
274
+
275
+ try:
276
+ graph_path = "/tmp/graph.png"
277
+ if os.path.exists(graph_path):
278
+ st.image(graph_path, caption="Multi-Agent Essay Writer Workflow Visualization", use_container_width=True)
279
+ else:
280
+ st.warning("⚠️ Workflow graph not found. Please run `graph.py` to regenerate `graph.png`.")
281
+
282
+ except Exception as e:
283
+ st.error("❌ An error occurred while generating the workflow visualization.")
284
+ st.text_area("Error Details:", traceback.format_exc(), height=500)
285
+
286
+
287
+ # Acknowledgement Section
288
+ st.markdown(
289
+ """
290
+ <div style="text-align: center; font-size: 14px; color: #555; padding-top: 200px; margin-top: 200px;">
291
+ <strong>Acknowledgement:</strong> This app is based on Mesut Duman's work:
292
+ <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
293
+ target="_blank" style="color: #007BFF; text-decoration: none;">
294
+ CrewAI Essay Writer
295
+ </a>
296
+ </div>
297
+ """,
298
+ unsafe_allow_html=True,
299
+ )