DrishtiSharma commited on
Commit
03d4ea0
·
verified ·
1 Parent(s): f13921d

Create app.py

Browse files
Files changed (1) hide show
  1. lab/app.py +131 -0
lab/app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
+ </a>
128
+ </div>
129
+ """,
130
+ unsafe_allow_html=True,
131
+ )