forked from amanv1906/GENAI-CareerAssistant-Multiagent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
270 lines (229 loc) · 9.93 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
from typing import Callable, TypeVar
import os
import inspect
import streamlit as st
import streamlit_analytics2 as streamlit_analytics
from dotenv import load_dotenv
from streamlit_chat import message
from streamlit_pills import pills
from streamlit.runtime.scriptrunner import add_script_run_ctx, get_script_run_ctx
from streamlit.delta_generator import DeltaGenerator
from langchain_community.chat_message_histories import StreamlitChatMessageHistory
from custom_callback_handler import CustomStreamlitCallbackHandler
from agents import define_graph
import shutil
load_dotenv()
# Set environment variables from Streamlit secrets or .env
os.environ["LINKEDIN_EMAIL"] = st.secrets.get("LINKEDIN_EMAIL", "")
os.environ["LINKEDIN_PASS"] = st.secrets.get("LINKEDIN_PASS", "")
os.environ["LANGCHAIN_API_KEY"] = st.secrets.get("LANGCHAIN_API_KEY", "")
os.environ["LANGCHAIN_TRACING_V2"] = os.getenv("LANGCHAIN_TRACING_V2") or st.secrets.get("LANGCHAIN_TRACING_V2", "")
os.environ["LANGCHAIN_PROJECT"] = st.secrets.get("LANGCHAIN_PROJECT", "")
os.environ["GROQ_API_KEY"] = st.secrets.get("GROQ_API_KEY", "")
os.environ["SERPER_API_KEY"] = st.secrets.get("SERPER_API_KEY", "")
os.environ["FIRECRAWL_API_KEY"] = st.secrets.get("FIRECRAWL_API_KEY", "")
os.environ["LINKEDIN_SEARCH"] = st.secrets.get("LINKEDIN_JOB_SEARCH", "")
# Page configuration
st.set_page_config(layout="wide")
st.title("GenAI Career Assistant - 👨💼")
st.markdown("[Connect with me on LinkedIn](https://www.linkedin.com/in/aman-varyani-885725181/)")
streamlit_analytics.start_tracking()
# Setup directories and paths
temp_dir = "temp"
dummy_resume_path = os.path.abspath("dummy_resume.pdf")
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
# Add dummy resume if it does not exist
if not os.path.exists(dummy_resume_path):
default_resume_path = "path/to/your/dummy_resume.pdf"
shutil.copy(default_resume_path, dummy_resume_path)
# Sidebar - File Upload
uploaded_document = st.sidebar.file_uploader("Upload Your Resume", type="pdf")
if not uploaded_document:
uploaded_document = open(dummy_resume_path, "rb")
st.sidebar.write("Using a dummy resume for demonstration purposes. ")
st.sidebar.markdown(f"[View Dummy Resume]({'https://drive.google.com/file/d/1vTdtIPXEjqGyVgUgCO6HLiG9TSPcJ5eM/view?usp=sharing'})", unsafe_allow_html=True)
bytes_data = uploaded_document.read()
filepath = os.path.join(temp_dir, "resume.pdf")
with open(filepath, "wb") as f:
f.write(bytes_data)
st.markdown("**Resume uploaded successfully!**")
# Sidebar - Service Provider Selection
service_provider = st.sidebar.selectbox(
"Service Provider",
("groq (llama-3.1-70b-versatile)", "openai"),
)
streamlit_analytics.stop_tracking()
# Not to track the key
if service_provider == "openai":
# Sidebar - OpenAI Configuration
api_key_openai = st.sidebar.text_input(
"OpenAI API Key",
st.session_state.get("OPENAI_API_KEY", ""),
type="password",
)
model_openai = st.sidebar.selectbox(
"OpenAI Model",
("gpt-4o-mini", "gpt-4o", "gpt-3.5-turbo"),
)
settings = {
"model": model_openai,
"model_provider": "openai",
"temperature": 0.3,
}
st.session_state["OPENAI_API_KEY"] = api_key_openai
os.environ["OPENAI_API_KEY"] = st.session_state["OPENAI_API_KEY"]
else:
# Toggle visibility for Groq API Key input
if "groq_key_visible" not in st.session_state:
st.session_state["groq_key_visible"] = False
if st.sidebar.button("Enter Groq API Key (optional)"):
st.session_state["groq_key_visible"] = True
if st.session_state["groq_key_visible"]:
api_key_groq = st.sidebar.text_input("Groq API Key", type="password")
st.session_state["GROQ_API_KEY"] = api_key_groq
os.environ["GROQ_API_KEY"] = api_key_groq
settings = {
"model": "llama-3.1-70b-versatile",
"model_provider": "groq",
"temperature": 0.3,
}
# Sidebar - Service Provider Note
st.sidebar.markdown(
"""
**Note:** \n
This multi-agent system works best with OpenAI. llama 3.1 may not always produce optimal results.\n
Any key provided will not be stored or shared it will be used only for the current session.
"""
)
st.sidebar.markdown(
"""
<div style="padding:10px 0;">
If you like the project, give a
<a href="https://github.com/amanv1906/GENAI-CareerAssistant-Multiagent" target="_blank" style="text-decoration:none;">
⭐ on GitHub
</a>
</div>
""",
unsafe_allow_html=True,
)
# Create the agent flow
flow_graph = define_graph()
message_history = StreamlitChatMessageHistory()
# Initialize session state variables
if "active_option_index" not in st.session_state:
st.session_state["active_option_index"] = None
if "interaction_history" not in st.session_state:
st.session_state["interaction_history"] = []
if "response_history" not in st.session_state:
st.session_state["response_history"] = ["Hello! How can I assist you today?"]
if "user_query_history" not in st.session_state:
st.session_state["user_query_history"] = ["Hi there! 👋"]
# Containers for the chat interface
conversation_container = st.container()
input_section = st.container()
# Define functions used above
def initialize_callback_handler(main_container: DeltaGenerator):
V = TypeVar("V")
def wrap_function(func: Callable[..., V]) -> Callable[..., V]:
context = get_script_run_ctx()
def wrapped(*args, **kwargs) -> V:
add_script_run_ctx(ctx=context)
return func(*args, **kwargs)
return wrapped
streamlit_callback_instance = CustomStreamlitCallbackHandler(
parent_container=main_container
)
for method_name, method in inspect.getmembers(
streamlit_callback_instance, predicate=inspect.ismethod
):
setattr(streamlit_callback_instance, method_name, wrap_function(method))
return streamlit_callback_instance
def execute_chat_conversation(user_input, graph):
callback_handler_instance = initialize_callback_handler(st.container())
callback_handler = callback_handler_instance
try:
output = graph.invoke(
{
"messages": list(message_history.messages) + [user_input],
"user_input": user_input,
"config": settings,
"callback": callback_handler,
},
{"recursion_limit": 100},
)
message_output = output.get("messages")[-1]
messages_list = output.get("messages")
message_history.clear()
message_history.add_messages(messages_list)
except Exception as exc:
return ":( Sorry, Some error occurred. Can you please try again?"
return message_output.content
# Clear Chat functionality
if st.button("Clear Chat"):
st.session_state["user_query_history"] = []
st.session_state["response_history"] = []
message_history.clear()
st.rerun() # Refresh the app to reflect the cleared chat
# for tracking the query.
streamlit_analytics.start_tracking()
# Display chat interface
with input_section:
options = [
"Identify top trends in the tech industry relevant to gen ai",
"Find emerging technologies and their potential impact on job opportunities",
"Summarize my resume",
"Create a career path visualization based on my skills and interests from my resume",
"GenAI Jobs at Microsoft",
"Job Search GenAI jobs in India.",
"Analyze my resume and suggest a suitable job role and search for relevant job listings",
"Generate a cover letter for my resume.",
]
icons = ["🔍", "🌐", "📝", "📈", "💼", "🌟", "✉️", "🧠 "]
selected_query = pills(
"Pick a question for query:",
options,
clearable=None, # type: ignore
icons=icons,
index=st.session_state["active_option_index"],
key="pills",
)
if selected_query:
st.session_state["active_option_index"] = options.index(selected_query)
# Display text input form
with st.form(key="query_form", clear_on_submit=True):
user_input_query = st.text_input(
"Query:",
value=(selected_query if selected_query else "Detail analysis of latest layoff news India?"),
placeholder="📝 Write your query or select from the above",
key="input",
)
submit_query_button = st.form_submit_button(label="Send")
if submit_query_button:
if not uploaded_document:
st.error("Please upload your resume before submitting a query.")
elif service_provider == "openai" and not st.session_state["OPENAI_API_KEY"]:
st.error("Please enter your OpenAI API key before submitting a query.")
elif user_input_query:
# Process the query as usual if resume is uploaded
chat_output = execute_chat_conversation(user_input_query, flow_graph)
st.session_state["user_query_history"].append(user_input_query)
st.session_state["response_history"].append(chat_output)
st.session_state["last_input"] = user_input_query # Save the latest input
st.session_state["active_option_index"] = None
# Display chat history
if st.session_state["response_history"]:
with conversation_container:
for i in range(len(st.session_state["response_history"])):
message(
st.session_state["user_query_history"][i],
is_user=True,
key=str(i) + "_user",
avatar_style="fun-emoji",
)
message(
st.session_state["response_history"][i],
key=str(i),
avatar_style="bottts",
)
streamlit_analytics.stop_tracking()