DrishtiSharma commited on
Commit
024cbe7
·
verified ·
1 Parent(s): d040e4c

Create app4.py

Browse files
Files changed (1) hide show
  1. lab/app4.py +195 -0
lab/app4.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 2-3 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=400,
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
+ return app.graph.invoke(input={"topic": topic, "length": length}) # Ensure `graph` is invoked
104
+
105
+
106
+ # Define Tabs
107
+ tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Viz"])
108
+
109
+ # 📜 Tab 1: Essay Generation
110
+ with tab1:
111
+ #st.subheader("📝 Generate an Essay")
112
+
113
+ # Display chat messages from the session
114
+ if "messages" not in st.session_state:
115
+ st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
116
+
117
+ for message in st.session_state["messages"]:
118
+ with st.chat_message(message["role"]):
119
+ st.markdown(message["content"], unsafe_allow_html=True)
120
+
121
+ # Handle user input
122
+ if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state["chat_active"]):
123
+ st.chat_message("user").markdown(topic)
124
+ st.session_state["messages"].append({"role": "user", "content": topic})
125
+
126
+ with st.spinner("⏳ Generating your essay..."):
127
+ response = None
128
+ if app:
129
+ response = app.write_essay({"topic": topic})
130
+ else:
131
+ st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
132
+
133
+ # Handle the assistant's response
134
+ with st.chat_message("assistant"):
135
+ if response and "essay" in response: # Display essay preview and download link
136
+ essay = response["essay"]
137
+ st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
138
+ st.markdown(f"#### {essay['header']}")
139
+ st.markdown(essay["entry"])
140
+
141
+ for para in essay["paragraphs"]:
142
+ st.markdown(f"**{para['sub_header']}**")
143
+ st.markdown(para["paragraph"])
144
+
145
+ st.markdown("**🖊️ Conclusion:**")
146
+ st.markdown(essay["conclusion"])
147
+
148
+ # Provide download link for the PDF (only if available)
149
+ pdf_name = response.get("pdf_name")
150
+ if pdf_name and os.path.exists(pdf_name):
151
+ with open(pdf_name, "rb") as pdf_file:
152
+ b64 = base64.b64encode(pdf_file.read()).decode()
153
+ href = f"<a href='data:application/octet-stream;base64,{b64}' download='{pdf_name}'>📄 Click here to download the PDF</a>"
154
+ st.markdown(href, unsafe_allow_html=True)
155
+
156
+ # Save response in session state
157
+ st.session_state["messages"].append(
158
+ {"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
159
+ )
160
+ elif response: # Other responses (fallback)
161
+ st.markdown(response["response"])
162
+ st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
163
+ else:
164
+ st.error("⚠️ No response received. Please try again.")
165
+
166
+
167
+ # 📊 Tab 2: Workflow Visualization
168
+ with tab2:
169
+ st.subheader("📊 Multi-Agent Workflow Visualization")
170
+
171
+ try:
172
+ graph_path = "/tmp/graph.png"
173
+ if os.path.exists(graph_path):
174
+ st.image(graph_path, caption="Multi-Agent Workflow", use_container_width=True)
175
+ else:
176
+ st.warning("⚠️ Workflow graph not found. Please run `graph.py` to regenerate `graph.png`.")
177
+
178
+ except Exception as e:
179
+ st.error("❌ An error occurred while generating the workflow visualization.")
180
+ st.text_area("Error Details:", traceback.format_exc(), height=200)
181
+
182
+
183
+ # Acknowledgment Section
184
+ st.markdown(
185
+ """
186
+ <div style="text-align: center; font-size: 14px; color: #555; padding-top: 200px; margin-top: 200px;">
187
+ <strong>Acknowledgment:</strong> This app is based on Mesut Duman's work:
188
+ <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
189
+ target="_blank" style="color: #007BFF; text-decoration: none;">
190
+ CrewAI Essay Writer
191
+ </a>
192
+ </div>
193
+ """,
194
+ unsafe_allow_html=True,
195
+ )