DrishtiSharma commited on
Commit
c43aa42
·
verified ·
1 Parent(s): a39afe6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -21
app.py CHANGED
@@ -6,7 +6,7 @@ import base64
6
 
7
  st.set_page_config(page_title="Multi-Agent Essay Writer", page_icon="🤖🤖🤖✍️")
8
 
9
- # Button HTML
10
  button_html = f'''
11
  <div style="display: flex; justify-content: center;">
12
  <a href=" " target="_blank">
@@ -37,10 +37,10 @@ if "messages" not in st.session_state:
37
 
38
  # Sidebar with instructions and API key input
39
  with st.sidebar:
40
- st.subheader("About:")
41
  st.info(
42
- "\n\n* This app uses the 'gpt-4o-mini-2024-07-18' model."
43
- "\n\n* Writing essays may take some time, approximately 1-2 minutes."
44
  )
45
 
46
  openai_key = st.secrets.get("OPENAI_API_KEY", "")
@@ -48,16 +48,16 @@ with st.sidebar:
48
  st.divider()
49
 
50
  # Reference section
51
- st.subheader("References:")
52
  st.markdown(
53
- '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)',
54
  unsafe_allow_html=True
55
  )
56
 
57
  # Initialize agents function
58
  def initialize_agents():
59
  if not openai_key:
60
- st.error("OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets.")
61
  st.session_state.chat_active = True
62
  return None
63
 
@@ -68,10 +68,17 @@ def initialize_agents():
68
 
69
  essay_writer = EssayWriter().graph
70
  st.session_state.chat_active = False
71
- st.success("Agents successfully initialized!")
 
 
 
 
 
 
 
72
  return essay_writer
73
  except Exception as e:
74
- st.error(f"Error initializing agents: {e}")
75
  st.session_state.chat_active = True
76
  return None
77
 
@@ -80,22 +87,36 @@ if "app" not in st.session_state or st.session_state.app is None:
80
  st.session_state.app = initialize_agents()
81
 
82
  if st.session_state.app is None:
83
- st.error("Failed to initialize agents. Please check your API key and restart the app.")
84
 
85
  app = st.session_state.app
86
 
87
  # Function to invoke the agent and generate a response
88
  def generate_response(topic, length):
89
  if not app:
90
- st.error("Agents are not initialized. Please check the system or restart the app.")
91
  return {"response": "Error: Agents not initialized."}
92
 
93
  return app.invoke(input={"topic": topic, "length": length})
94
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- # Add user input for essay length
97
- st.subheader("Set Essay Length:")
98
- essay_length = st.number_input("Enter the word count for the essay:", min_value=150, max_value=350, value=250, step=50)
 
 
 
 
99
 
100
  # Display chat messages from the session
101
  for message in st.session_state.messages:
@@ -103,29 +124,29 @@ for message in st.session_state.messages:
103
  st.markdown(message["content"], unsafe_allow_html=True)
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):
107
  st.chat_message("user").markdown(topic)
108
  st.session_state.messages.append({"role": "user", "content": topic})
109
 
110
- with st.spinner("Thinking..."):
111
  response = generate_response(topic, essay_length) # **Pass user-defined length**
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"#### {response['essay']['header']}")
118
  st.markdown(response["essay"]["entry"])
119
  for para in response["essay"]["paragraphs"]:
120
  st.markdown(f"**{para['sub_header']}**")
121
  st.markdown(para["paragraph"])
122
- st.markdown("**Conclusion:**")
123
  st.markdown(response["essay"]["conclusion"])
124
 
125
  # Provide download link for the PDF
126
  with open(response["pdf_name"], "rb") as pdf_file:
127
  b64 = base64.b64encode(pdf_file.read()).decode()
128
- href = f"<a href='data:application/octet-stream;base64,{b64}' download='{response['pdf_name']}'>Click here to download the PDF</a>"
129
  st.markdown(href, unsafe_allow_html=True)
130
 
131
  # Save the assistant's message to session state
@@ -140,8 +161,10 @@ if topic := st.chat_input(placeholder="Ask a question or provide an essay topic.
140
  st.markdown("---")
141
  st.markdown(
142
  """
143
- <div style="text-align: center; font-size: 14px; color: #555;">
144
- <strong>Acknowledgment:</strong> This project is based on Mesut Duman's work:
 
 
145
  <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
146
  target="_blank" style="color: #007BFF; text-decoration: none;">
147
  CrewAI Essay Writer
 
6
 
7
  st.set_page_config(page_title="Multi-Agent Essay Writer", page_icon="🤖🤖🤖✍️")
8
 
9
+ # Button HTML (If Needed)
10
  button_html = f'''
11
  <div style="display: flex; justify-content: center;">
12
  <a href=" " target="_blank">
 
37
 
38
  # Sidebar with instructions and API key input
39
  with st.sidebar:
40
+ st.subheader("📌 About:")
41
  st.info(
42
+ "🔹 This app uses the 'gpt-4o-mini-2024-07-18' model.\n"
43
+ "🔹 Writing essays may take some time, approximately 1-2 minutes."
44
  )
45
 
46
  openai_key = st.secrets.get("OPENAI_API_KEY", "")
 
48
  st.divider()
49
 
50
  # Reference section
51
+ st.subheader("📖 References:")
52
  st.markdown(
53
+ '[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)',
54
  unsafe_allow_html=True
55
  )
56
 
57
  # Initialize agents function
58
  def initialize_agents():
59
  if not openai_key:
60
+ st.error("⚠️ OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets.")
61
  st.session_state.chat_active = True
62
  return None
63
 
 
68
 
69
  essay_writer = EssayWriter().graph
70
  st.session_state.chat_active = False
71
+
72
+ st.markdown(
73
+ "<div style='text-align: center; padding: 10px; margin-bottom: 20px; "
74
+ "background-color: #d4edda; color: #155724; border-radius: 8px;'>"
75
+ "<b>✅ Agents successfully initialized!</b></div>",
76
+ unsafe_allow_html=True
77
+ )
78
+
79
  return essay_writer
80
  except Exception as e:
81
+ st.error(f"Error initializing agents: {e}")
82
  st.session_state.chat_active = True
83
  return None
84
 
 
87
  st.session_state.app = initialize_agents()
88
 
89
  if st.session_state.app is None:
90
+ st.error("⚠️ Failed to initialize agents. Please check your API key and restart the app.")
91
 
92
  app = st.session_state.app
93
 
94
  # Function to invoke the agent and generate a response
95
  def generate_response(topic, length):
96
  if not app:
97
+ st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
98
  return {"response": "Error: Agents not initialized."}
99
 
100
  return app.invoke(input={"topic": topic, "length": length})
101
 
102
+ # **NEW: UI Enhancement for Setting Essay Length**
103
+ st.markdown(
104
+ """
105
+ <div style="text-align: center; padding: 15px; background-color: #f8f9fa;
106
+ border-radius: 10px; box-shadow: 2px 2px 10px rgba(0,0,0,0.1);">
107
+ <h3 style="color: #333;">✍️ Set Essay Length</h3>
108
+ </div>
109
+ """,
110
+ unsafe_allow_html=True
111
+ )
112
 
113
+ essay_length = st.number_input(
114
+ "Enter the word count for the essay:",
115
+ min_value=150,
116
+ max_value=350,
117
+ value=250,
118
+ step=50
119
+ )
120
 
121
  # Display chat messages from the session
122
  for message in st.session_state.messages:
 
124
  st.markdown(message["content"], unsafe_allow_html=True)
125
 
126
  # Handle user input
127
+ if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state.chat_active):
128
  st.chat_message("user").markdown(topic)
129
  st.session_state.messages.append({"role": "user", "content": topic})
130
 
131
+ with st.spinner("Thinking..."):
132
  response = generate_response(topic, essay_length) # **Pass user-defined length**
133
 
134
  # Handle the assistant's response
135
  with st.chat_message("assistant"):
136
  if "essay" in response: # Display essay preview and download link
137
+ st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
138
  st.markdown(f"#### {response['essay']['header']}")
139
  st.markdown(response["essay"]["entry"])
140
  for para in response["essay"]["paragraphs"]:
141
  st.markdown(f"**{para['sub_header']}**")
142
  st.markdown(para["paragraph"])
143
+ st.markdown("**🖊️ Conclusion:**")
144
  st.markdown(response["essay"]["conclusion"])
145
 
146
  # Provide download link for the PDF
147
  with open(response["pdf_name"], "rb") as pdf_file:
148
  b64 = base64.b64encode(pdf_file.read()).decode()
149
+ href = f"<a href='data:application/octet-stream;base64,{b64}' download='{response['pdf_name']}'>📄 Click here to download the PDF</a>"
150
  st.markdown(href, unsafe_allow_html=True)
151
 
152
  # Save the assistant's message to session state
 
161
  st.markdown("---")
162
  st.markdown(
163
  """
164
+ <div style="text-align: center; padding: 15px; background-color: #f8f9fa;
165
+ border-radius: 10px; box-shadow: 2px 2px 10px rgba(0,0,0,0.1);">
166
+ <strong>📌 Acknowledgment:</strong> This project is based on Mesut Duman's work.
167
+ <br><br> 🛠️ Source:
168
  <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
169
  target="_blank" style="color: #007BFF; text-decoration: none;">
170
  CrewAI Essay Writer