Update lab/app3.py
Browse files- lab/app3.py +198 -0
lab/app3.py
CHANGED
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
22 |
+
#st.set_page_config(page_title="Multi-Agent Essay Writing Assistant", page_icon="🤖🤖🤖✍️", layout = "centered")
|
23 |
+
|
24 |
+
# Ensure session state variables are initialized properly
|
25 |
+
if "messages" not in st.session_state:
|
26 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
27 |
+
|
28 |
+
if "app" not in st.session_state:
|
29 |
+
st.session_state["app"] = None
|
30 |
+
|
31 |
+
if "chat_active" not in st.session_state:
|
32 |
+
st.session_state["chat_active"] = True
|
33 |
+
|
34 |
+
# Sidebar with essay settings and user-defined length
|
35 |
+
with st.sidebar:
|
36 |
+
st.subheader("About:")
|
37 |
+
st.info(
|
38 |
+
"\n\n 1. This app uses the 'gpt-4o-mini-2024-07-18' model."
|
39 |
+
"\n\n 2. Writing essays may take some time, approximately 2-3 minutes."
|
40 |
+
)
|
41 |
+
|
42 |
+
# API Key Retrieval
|
43 |
+
openai_key = st.secrets.get("OPENAI_API_KEY", "")
|
44 |
+
|
45 |
+
st.divider()
|
46 |
+
|
47 |
+
# User-defined essay length selection
|
48 |
+
st.subheader("📝 Configure Essay Settings:")
|
49 |
+
essay_length = st.number_input(
|
50 |
+
"Select Essay Length (words):",
|
51 |
+
min_value=150,
|
52 |
+
max_value=400,
|
53 |
+
value=250,
|
54 |
+
step=50
|
55 |
+
)
|
56 |
+
|
57 |
+
st.divider()
|
58 |
+
|
59 |
+
# Reference section
|
60 |
+
st.subheader("📖 References:")
|
61 |
+
st.markdown(
|
62 |
+
"[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)",
|
63 |
+
unsafe_allow_html=True
|
64 |
+
)
|
65 |
+
|
66 |
+
# Initialize agents function
|
67 |
+
def initialize_agents():
|
68 |
+
if not openai_key:
|
69 |
+
st.error("⚠️ OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets.")
|
70 |
+
st.session_state["chat_active"] = True
|
71 |
+
return None
|
72 |
+
|
73 |
+
os.environ["OPENAI_API_KEY"] = openai_key
|
74 |
+
try:
|
75 |
+
# Prevent re-initialization
|
76 |
+
if "app" in st.session_state and st.session_state["app"] is not None:
|
77 |
+
return st.session_state["app"]
|
78 |
+
|
79 |
+
# Initialize the full EssayWriter instance
|
80 |
+
essay_writer = EssayWriter() # ✅ Store the full instance
|
81 |
+
st.session_state["app"] = essay_writer # ✅ Now contains `graph`
|
82 |
+
st.session_state["chat_active"] = False # ✅ Enable chat after successful initialization
|
83 |
+
|
84 |
+
return essay_writer
|
85 |
+
except Exception as e:
|
86 |
+
st.error(f"❌ Error initializing agents: {e}")
|
87 |
+
st.session_state["chat_active"] = True
|
88 |
+
return None
|
89 |
+
|
90 |
+
|
91 |
+
# Automatically initialize agents on app load
|
92 |
+
if st.session_state["app"] is None:
|
93 |
+
st.session_state["app"] = initialize_agents()
|
94 |
+
|
95 |
+
if st.session_state["app"] is None:
|
96 |
+
st.error("⚠️ Failed to initialize agents. Please check your API key and restart the app.")
|
97 |
+
|
98 |
+
app = st.session_state["app"]
|
99 |
+
|
100 |
+
# Function to invoke the agent and generate a response
|
101 |
+
def generate_response(topic, length):
|
102 |
+
if not app or not hasattr(app, "graph"):
|
103 |
+
st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
|
104 |
+
return {"response": "Error: Agents not initialized."}
|
105 |
+
|
106 |
+
return app.graph.invoke(input={"topic": topic, "length": length}) # Ensure `graph` is invoked
|
107 |
+
|
108 |
+
|
109 |
+
# Define Tabs
|
110 |
+
tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Viz"])
|
111 |
+
|
112 |
+
# 📜 Tab 1: Essay Generation
|
113 |
+
with tab1:
|
114 |
+
#st.subheader("📝 Generate an Essay")
|
115 |
+
|
116 |
+
# Display chat messages from the session
|
117 |
+
if "messages" not in st.session_state:
|
118 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
119 |
+
|
120 |
+
for message in st.session_state["messages"]:
|
121 |
+
with st.chat_message(message["role"]):
|
122 |
+
st.markdown(message["content"], unsafe_allow_html=True)
|
123 |
+
|
124 |
+
# Handle user input
|
125 |
+
if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state["chat_active"]):
|
126 |
+
st.chat_message("user").markdown(topic)
|
127 |
+
st.session_state["messages"].append({"role": "user", "content": topic})
|
128 |
+
|
129 |
+
with st.spinner("⏳ Generating your essay..."):
|
130 |
+
response = None
|
131 |
+
if app:
|
132 |
+
response = app.write_essay({"topic": topic})
|
133 |
+
else:
|
134 |
+
st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
|
135 |
+
|
136 |
+
# Handle the assistant's response
|
137 |
+
with st.chat_message("assistant"):
|
138 |
+
if response and "essay" in response: # Display essay preview and download link
|
139 |
+
essay = response["essay"]
|
140 |
+
st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
|
141 |
+
st.markdown(f"#### {essay['header']}")
|
142 |
+
st.markdown(essay["entry"])
|
143 |
+
|
144 |
+
for para in essay["paragraphs"]:
|
145 |
+
st.markdown(f"**{para['sub_header']}**")
|
146 |
+
st.markdown(para["paragraph"])
|
147 |
+
|
148 |
+
st.markdown("**🖊️ Conclusion:**")
|
149 |
+
st.markdown(essay["conclusion"])
|
150 |
+
|
151 |
+
# Provide download link for the PDF (only if available)
|
152 |
+
pdf_name = response.get("pdf_name")
|
153 |
+
if pdf_name and os.path.exists(pdf_name):
|
154 |
+
with open(pdf_name, "rb") as pdf_file:
|
155 |
+
b64 = base64.b64encode(pdf_file.read()).decode()
|
156 |
+
href = f"<a href='data:application/octet-stream;base64,{b64}' download='{pdf_name}'>📄 Click here to download the PDF</a>"
|
157 |
+
st.markdown(href, unsafe_allow_html=True)
|
158 |
+
|
159 |
+
# Save response in session state
|
160 |
+
st.session_state["messages"].append(
|
161 |
+
{"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
|
162 |
+
)
|
163 |
+
elif response: # Other responses (fallback)
|
164 |
+
st.markdown(response["response"])
|
165 |
+
st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
|
166 |
+
else:
|
167 |
+
st.error("⚠️ No response received. Please try again.")
|
168 |
+
|
169 |
+
|
170 |
+
# 📊 Tab 2: Workflow Visualization
|
171 |
+
with tab2:
|
172 |
+
st.subheader("📊 Multi-Agent Workflow Visualization")
|
173 |
+
|
174 |
+
try:
|
175 |
+
graph_path = "/tmp/graph.png"
|
176 |
+
if os.path.exists(graph_path):
|
177 |
+
st.image(graph_path, caption="Multi-Agent Workflow", use_container_width=True)
|
178 |
+
else:
|
179 |
+
st.warning("⚠️ Workflow graph not found. Please run `graph.py` to regenerate `graph.png`.")
|
180 |
+
|
181 |
+
except Exception as e:
|
182 |
+
st.error("❌ An error occurred while generating the workflow visualization.")
|
183 |
+
st.text_area("Error Details:", traceback.format_exc(), height=200)
|
184 |
+
|
185 |
+
|
186 |
+
# Acknowledgment Section
|
187 |
+
st.markdown(
|
188 |
+
"""
|
189 |
+
<div style="text-align: center; font-size: 14px; color: #555; padding-top: 200px; margin-top: 200px;">
|
190 |
+
<strong>Acknowledgment:</strong> This app is based on Mesut Duman's work:
|
191 |
+
<a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
|
192 |
+
target="_blank" style="color: #007BFF; text-decoration: none;">
|
193 |
+
CrewAI Essay Writer
|
194 |
+
</a>
|
195 |
+
</div>
|
196 |
+
""",
|
197 |
+
unsafe_allow_html=True,
|
198 |
+
)
|