DrishtiSharma commited on
Commit
e0fa0d7
·
verified ·
1 Parent(s): 9c95c37

Update test_app.py

Browse files
Files changed (1) hide show
  1. test_app.py +80 -67
test_app.py CHANGED
@@ -1,126 +1,139 @@
1
  import streamlit as st
2
- from graph import EssayWriter
 
3
  import os
4
  import base64
5
 
6
- st.set_page_config(page_title="Multi-Agent Essay Writer", page_icon="🤖")
7
-
8
- # Button HTML (if needed for external links)
9
- button_html = f'''
10
- <div style="display: flex; justify-content: center;">
11
- <a href=" " target="_blank">
12
- <button style="
13
- background-color: #FFDD00;
14
- border: none;
15
- color: black;
16
- padding: 10px 20px;
17
- text-align: center;
18
- text-decoration: none;
19
- display: inline-block;
20
- font-size: 16px;
21
- margin: 4px 2px;
22
- cursor: pointer;
23
- border-radius: 10px;
24
- box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2);
25
- ">
26
- </button>
27
- </a>
28
- </div>
29
- '''
30
 
31
- # Initialize session state
32
  if "messages" not in st.session_state:
33
- st.session_state.messages = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
34
- st.session_state.app = None
35
- st.session_state.chat_active = True
 
36
 
37
- # Sidebar with instructions and API key input
 
 
 
38
  with st.sidebar:
 
39
  st.info(
40
- "* ⚠️ Initialize the agents to start using the application."
41
  "\n\n* This app uses the 'gpt-4o-mini-2024-07-18' model."
42
  "\n\n* Writing essays may take some time, approximately 1-2 minutes."
43
  )
44
- developer_mode = st.checkbox("Developer Mode", value=False)
45
- openai_key = st.secrets.get("OPENAI_API_KEY", "") if not developer_mode else st.text_input("OpenAI API Key (Developer Mode)", type="password")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  # Initialize agents function
48
  def initialize_agents():
49
  if not openai_key:
50
- st.error("OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets or Developer Mode.")
51
- st.session_state.chat_active = True
52
  return None
53
 
54
  os.environ["OPENAI_API_KEY"] = openai_key
55
  try:
 
 
 
56
  essay_writer = EssayWriter().graph
57
- st.success("Agents successfully initialized!")
58
- st.session_state.chat_active = False
 
 
59
  return essay_writer
60
  except Exception as e:
61
- st.error(f"Error initializing agents: {e}")
62
- st.session_state.chat_active = True
63
  return None
64
 
65
- # Sidebar button for initializing agents
66
- with st.sidebar:
67
- if st.button("Initialize Agents", type="primary"):
68
- st.session_state.app = initialize_agents()
69
- st.divider()
70
- st.markdown(button_html, unsafe_allow_html=True)
71
 
72
- # Access the initialized app
73
- app = st.session_state.app
 
 
74
 
75
  # Function to invoke the agent and generate a response
76
- def generate_response(topic):
77
- return app.invoke(input={"topic": topic}) if app else {"response": "Error: Agents not initialized."}
 
 
 
 
78
 
79
  # Display chat messages from the session
80
- for message in st.session_state.messages:
81
- with st.chat_message(message["role"]):
82
- st.markdown(message["content"], unsafe_allow_html=True)
 
83
 
84
  # Handle user input
85
- if topic := st.chat_input(placeholder="Ask a question or provide an essay topic...", disabled=st.session_state.chat_active):
86
  st.chat_message("user").markdown(topic)
87
- st.session_state.messages.append({"role": "user", "content": topic})
88
 
89
- with st.spinner("Thinking..."):
90
- response = generate_response(topic)
91
 
92
  # Handle the assistant's response
93
  with st.chat_message("assistant"):
94
  if "essay" in response: # Display essay preview and download link
95
- st.markdown("### Essay Preview:")
96
  st.markdown(f"#### {response['essay']['header']}")
97
  st.markdown(response["essay"]["entry"])
98
  for para in response["essay"]["paragraphs"]:
99
  st.markdown(f"**{para['sub_header']}**")
100
  st.markdown(para["paragraph"])
101
- st.markdown("**Conclusion:**")
102
  st.markdown(response["essay"]["conclusion"])
103
 
104
  # Provide download link for the PDF
105
  with open(response["pdf_name"], "rb") as pdf_file:
106
  b64 = base64.b64encode(pdf_file.read()).decode()
107
- href = f"<a href='data:application/octet-stream;base64,{b64}' download='{response['pdf_name']}'>Click here to download the PDF</a>"
108
  st.markdown(href, unsafe_allow_html=True)
109
 
110
  # Save the assistant's message to session state
111
- st.session_state.messages.append(
112
- {"role": "assistant", "content": "Here is your essay preview and the download link."}
113
  )
114
  else: # For other responses (e.g., general answers)
115
  st.markdown(response["response"])
116
- st.session_state.messages.append({"role": "assistant", "content": response["response"]})
117
 
118
- # Add acknowledgment at the bottom
119
- st.markdown("---")
120
  st.markdown(
121
  """
122
- <div style="text-align: center; font-size: 14px; color: #555;">
123
- <strong>Acknowledgment:</strong> This project is based on Mesut Duman's work:
124
  <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
125
  target="_blank" style="color: #007BFF; text-decoration: none;">
126
  CrewAI Essay Writer
@@ -128,4 +141,4 @@ st.markdown(
128
  </div>
129
  """,
130
  unsafe_allow_html=True,
131
- )
 
1
  import streamlit as st
2
+ from graph import EssayWriter, RouteQuery, GraphState
3
+ from crew import *
4
  import os
5
  import base64
6
 
7
+ #st.title("Multi-Agent Essay Writing Assistant")
8
+ st.set_page_config(page_title="Multi-Agent Essay Writing Assistant", page_icon="🤖🤖🤖✍️", layout = "centered")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # Ensure session state variables are initialized properly
11
  if "messages" not in st.session_state:
12
+ st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
13
+
14
+ if "app" not in st.session_state:
15
+ st.session_state["app"] = None
16
 
17
+ if "chat_active" not in st.session_state:
18
+ st.session_state["chat_active"] = True
19
+
20
+ # Sidebar with essay settings and user-defined length
21
  with st.sidebar:
22
+ st.subheader("About:")
23
  st.info(
 
24
  "\n\n* This app uses the 'gpt-4o-mini-2024-07-18' model."
25
  "\n\n* Writing essays may take some time, approximately 1-2 minutes."
26
  )
27
+
28
+ # API Key Retrieval
29
+ openai_key = st.secrets.get("OPENAI_API_KEY", "")
30
+
31
+ st.divider()
32
+
33
+ # User-defined essay length selection
34
+ st.subheader("📝 Configure Essay Settings:")
35
+ essay_length = st.number_input(
36
+ "Select Essay Length (words):",
37
+ min_value=150,
38
+ max_value=400,
39
+ value=250,
40
+ step=50
41
+ )
42
+
43
+ st.divider()
44
+
45
+ # Reference section
46
+ st.subheader("📖 References:")
47
+ st.markdown(
48
+ "[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)",
49
+ unsafe_allow_html=True
50
+ )
51
 
52
  # Initialize agents function
53
  def initialize_agents():
54
  if not openai_key:
55
+ st.error("⚠️ OpenAI API key is missing! Please provide a valid key through Hugging Face Secrets.")
56
+ st.session_state["chat_active"] = True
57
  return None
58
 
59
  os.environ["OPENAI_API_KEY"] = openai_key
60
  try:
61
+ if st.session_state["app"] is not None:
62
+ return st.session_state["app"] # Prevent re-initialization
63
+
64
  essay_writer = EssayWriter().graph
65
+ st.session_state["chat_active"] = False
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()
 
 
 
78
 
79
+ if st.session_state["app"] is None:
80
+ st.error("⚠️ Failed to initialize agents. Please check your API key and restart the app.")
81
+
82
+ 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
  # Display chat messages from the session
93
+ if "messages" in st.session_state:
94
+ for message in st.session_state["messages"]:
95
+ with st.chat_message(message["role"]):
96
+ st.markdown(message["content"], unsafe_allow_html=True)
97
 
98
  # Handle user input
99
+ if topic := st.chat_input(placeholder="📝 Ask a question or provide an essay topic...", disabled=st.session_state["chat_active"]):
100
  st.chat_message("user").markdown(topic)
101
+ st.session_state["messages"].append({"role": "user", "content": topic})
102
 
103
+ with st.spinner("⏳ Generating your essay..."):
104
+ response = generate_response(topic, essay_length)
105
 
106
  # Handle the assistant's response
107
  with st.chat_message("assistant"):
108
  if "essay" in response: # Display essay preview and download link
109
+ st.markdown(f"### 📝 Essay Preview ({essay_length} words)")
110
  st.markdown(f"#### {response['essay']['header']}")
111
  st.markdown(response["essay"]["entry"])
112
  for para in response["essay"]["paragraphs"]:
113
  st.markdown(f"**{para['sub_header']}**")
114
  st.markdown(para["paragraph"])
115
+ st.markdown("**🖊️ Conclusion:**")
116
  st.markdown(response["essay"]["conclusion"])
117
 
118
  # Provide download link for the PDF
119
  with open(response["pdf_name"], "rb") as pdf_file:
120
  b64 = base64.b64encode(pdf_file.read()).decode()
121
+ href = f"<a href='data:application/octet-stream;base64,{b64}' download='{response['pdf_name']}'>📄 Click here to download the PDF</a>"
122
  st.markdown(href, unsafe_allow_html=True)
123
 
124
  # Save the assistant's message to session state
125
+ st.session_state["messages"].append(
126
+ {"role": "assistant", "content": f"Here is your {essay_length}-word essay preview and the download link."}
127
  )
128
  else: # For other responses (e.g., general answers)
129
  st.markdown(response["response"])
130
+ st.session_state["messages"].append({"role": "assistant", "content": response["response"]})
131
 
132
+ # Acknowledgment Section
 
133
  st.markdown(
134
  """
135
+ <div style="text-align: center; font-size: 14px; color: #555; padding-top: 250px; margin-top: 250px;">
136
+ <strong>Acknowledgment:</strong> This app is based on Mesut Duman's work:
137
  <a href="https://github.com/mesutdmn/Autonomous-Multi-Agent-Systems-with-CrewAI-Essay-Writer/tree/main"
138
  target="_blank" style="color: #007BFF; text-decoration: none;">
139
  CrewAI Essay Writer
 
141
  </div>
142
  """,
143
  unsafe_allow_html=True,
144
+ )