Update app.py
Browse files
app.py
CHANGED
@@ -58,20 +58,22 @@ def initialize_agents():
|
|
58 |
|
59 |
os.environ["OPENAI_API_KEY"] = openai_key
|
60 |
try:
|
61 |
-
|
62 |
-
|
|
|
63 |
|
64 |
-
|
65 |
-
|
|
|
|
|
66 |
|
67 |
-
# Success message
|
68 |
-
#st.success("✅ Agents successfully initialized!")
|
69 |
return essay_writer
|
70 |
except Exception as e:
|
71 |
st.error(f"❌ Error initializing agents: {e}")
|
72 |
st.session_state["chat_active"] = True
|
73 |
return None
|
74 |
|
|
|
75 |
# Automatically initialize agents on app load
|
76 |
if st.session_state["app"] is None:
|
77 |
st.session_state["app"] = initialize_agents()
|
@@ -83,11 +85,12 @@ app = st.session_state["app"]
|
|
83 |
|
84 |
# Function to invoke the agent and generate a response
|
85 |
def generate_response(topic, length):
|
86 |
-
if not app:
|
87 |
st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
|
88 |
return {"response": "Error: Agents not initialized."}
|
89 |
|
90 |
-
return app.invoke(input={"topic": topic, "length": length})
|
|
|
91 |
|
92 |
# Define Tabs
|
93 |
tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Visualization"])
|
@@ -97,10 +100,12 @@ with tab1:
|
|
97 |
st.subheader("📝 Generate an Essay")
|
98 |
|
99 |
# Display chat messages from the session
|
100 |
-
if "messages" in st.session_state:
|
101 |
-
|
102 |
-
|
103 |
-
|
|
|
|
|
104 |
|
105 |
# Handle user input
|
106 |
if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state["chat_active"]):
|
@@ -108,33 +113,45 @@ with tab1:
|
|
108 |
st.session_state["messages"].append({"role": "user", "content": topic})
|
109 |
|
110 |
with st.spinner("⏳ Generating your essay..."):
|
111 |
-
response =
|
|
|
|
|
|
|
|
|
112 |
|
113 |
# Handle the assistant's response
|
114 |
with st.chat_message("assistant"):
|
115 |
-
if "essay" in response: # Display essay preview and download link
|
|
|
116 |
st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
|
117 |
-
st.markdown(f"#### {
|
118 |
-
st.markdown(
|
119 |
-
|
|
|
120 |
st.markdown(f"**{para['sub_header']}**")
|
121 |
st.markdown(para["paragraph"])
|
|
|
122 |
st.markdown("**🖊️ Conclusion:**")
|
123 |
-
st.markdown(
|
124 |
|
125 |
-
# Provide download link for the PDF
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
|
|
|
|
130 |
|
131 |
-
# Save
|
132 |
st.session_state["messages"].append(
|
133 |
{"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
|
134 |
)
|
135 |
-
|
136 |
st.markdown(response["response"])
|
137 |
st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
|
|
|
|
|
|
|
138 |
|
139 |
# 📊 Tab 2: Workflow Visualization
|
140 |
with tab2:
|
|
|
58 |
|
59 |
os.environ["OPENAI_API_KEY"] = openai_key
|
60 |
try:
|
61 |
+
# Prevent re-initialization
|
62 |
+
if "app" in st.session_state and st.session_state["app"] is not None:
|
63 |
+
return st.session_state["app"]
|
64 |
|
65 |
+
# Initialize the full EssayWriter instance
|
66 |
+
essay_writer = EssayWriter() # ✅ Store the full instance
|
67 |
+
st.session_state["app"] = essay_writer # ✅ Now contains `graph`
|
68 |
+
st.session_state["chat_active"] = False # ✅ Enable chat after successful initialization
|
69 |
|
|
|
|
|
70 |
return essay_writer
|
71 |
except Exception as e:
|
72 |
st.error(f"❌ Error initializing agents: {e}")
|
73 |
st.session_state["chat_active"] = True
|
74 |
return None
|
75 |
|
76 |
+
|
77 |
# Automatically initialize agents on app load
|
78 |
if st.session_state["app"] is None:
|
79 |
st.session_state["app"] = initialize_agents()
|
|
|
85 |
|
86 |
# Function to invoke the agent and generate a response
|
87 |
def generate_response(topic, length):
|
88 |
+
if not app or not hasattr(app, "graph"):
|
89 |
st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
|
90 |
return {"response": "Error: Agents not initialized."}
|
91 |
|
92 |
+
return app.graph.invoke(input={"topic": topic, "length": length}) # Ensure `graph` is invoked
|
93 |
+
|
94 |
|
95 |
# Define Tabs
|
96 |
tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Visualization"])
|
|
|
100 |
st.subheader("📝 Generate an Essay")
|
101 |
|
102 |
# Display chat messages from the session
|
103 |
+
if "messages" not in st.session_state:
|
104 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
105 |
+
|
106 |
+
for message in st.session_state["messages"]:
|
107 |
+
with st.chat_message(message["role"]):
|
108 |
+
st.markdown(message["content"], unsafe_allow_html=True)
|
109 |
|
110 |
# Handle user input
|
111 |
if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state["chat_active"]):
|
|
|
113 |
st.session_state["messages"].append({"role": "user", "content": topic})
|
114 |
|
115 |
with st.spinner("⏳ Generating your essay..."):
|
116 |
+
response = None
|
117 |
+
if app:
|
118 |
+
response = app.write_essay({"topic": topic})
|
119 |
+
else:
|
120 |
+
st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
|
121 |
|
122 |
# Handle the assistant's response
|
123 |
with st.chat_message("assistant"):
|
124 |
+
if response and "essay" in response: # Display essay preview and download link
|
125 |
+
essay = response["essay"]
|
126 |
st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
|
127 |
+
st.markdown(f"#### {essay['header']}")
|
128 |
+
st.markdown(essay["entry"])
|
129 |
+
|
130 |
+
for para in essay["paragraphs"]:
|
131 |
st.markdown(f"**{para['sub_header']}**")
|
132 |
st.markdown(para["paragraph"])
|
133 |
+
|
134 |
st.markdown("**🖊️ Conclusion:**")
|
135 |
+
st.markdown(essay["conclusion"])
|
136 |
|
137 |
+
# Provide download link for the PDF (only if available)
|
138 |
+
pdf_name = response.get("pdf_name")
|
139 |
+
if pdf_name and os.path.exists(pdf_name):
|
140 |
+
with open(pdf_name, "rb") as pdf_file:
|
141 |
+
b64 = base64.b64encode(pdf_file.read()).decode()
|
142 |
+
href = f"<a href='data:application/octet-stream;base64,{b64}' download='{pdf_name}'>📄 Click here to download the PDF</a>"
|
143 |
+
st.markdown(href, unsafe_allow_html=True)
|
144 |
|
145 |
+
# Save response in session state
|
146 |
st.session_state["messages"].append(
|
147 |
{"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
|
148 |
)
|
149 |
+
elif response: # Other responses (fallback)
|
150 |
st.markdown(response["response"])
|
151 |
st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
|
152 |
+
else:
|
153 |
+
st.error("⚠️ No response received. Please try again.")
|
154 |
+
|
155 |
|
156 |
# 📊 Tab 2: Workflow Visualization
|
157 |
with tab2:
|