Spaces:
Sleeping
Sleeping
File size: 10,204 Bytes
73a80eb | 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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | """
Personal Website Chatbot Application
This application creates an AI-powered chatbot that impersonates the owner using their
LinkedIn profile and personal summary. It uses OpenAI's GPT model with function calling
to handle conversations and capture leads through Pushover notifications.
"""
# Import required libraries
from dotenv import load_dotenv # For loading environment variables
from openai import OpenAI # OpenAI API client
import json # JSON processing for function calls
import os # Operating system interface
import requests # HTTP requests for Pushover notifications
from pypdf import PdfReader # PDF text extraction
import gradio as gr # Web interface framework
# Load environment variables from .env file
load_dotenv(override=True)
# ================================
# NOTIFICATION FUNCTIONS
# ================================
def push(text):
"""
Send a notification via Pushover API.
Args:
text (str): The message text to send
"""
requests.post(
"https://api.pushover.net/1/messages.json",
data={
"token": os.getenv("PUSHOVER_TOKEN"),
"user": os.getenv("PUSHOVER_USER"),
"message": text,
}
)
# ================================
# TOOL FUNCTIONS FOR OPENAI
# ================================
def record_user_details(email, name="Name not provided", notes="not provided"):
"""
Record user contact details and send notification.
This function is called by OpenAI when a user provides their contact information.
Args:
email (str): User's email address (required)
name (str): User's name (optional)
notes (str): Additional conversation context (optional)
Returns:
dict: Success confirmation for OpenAI
"""
push(f"Recording {name} with email {email} and notes {notes}")
return {"recorded": "ok"}
def record_unknown_question(question):
"""
Record questions the chatbot couldn't answer.
This function is called by OpenAI when encountering unknown questions
to help improve the chatbot's knowledge base.
Args:
question (str): The question that couldn't be answered
Returns:
dict: Success confirmation for OpenAI
"""
push(f"Recording {question}")
return {"recorded": "ok"}
# ================================
# OPENAI FUNCTION SCHEMAS
# ================================
# Schema definition for the user details recording function
record_user_details_json = {
"name": "record_user_details",
"description": "Use this tool to record that a user is interested in being in touch and provided an email address",
"parameters": {
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "The email address of this user"
},
"name": {
"type": "string",
"description": "The user's name, if they provided it"
},
"notes": {
"type": "string",
"description": "Any additional information about the conversation that's worth recording to give context"
}
},
"required": ["email"],
"additionalProperties": False
}
}
# Schema definition for the unknown question recording function
record_unknown_question_json = {
"name": "record_unknown_question",
"description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer",
"parameters": {
"type": "object",
"properties": {
"question": {
"type": "string",
"description": "The question that couldn't be answered"
},
},
"required": ["question"],
"additionalProperties": False
}
}
# Combined tools list for OpenAI function calling
tools = [
{"type": "function", "function": record_user_details_json},
{"type": "function", "function": record_unknown_question_json}
]
# ================================
# MAIN CHATBOT CLASS
# ================================
class Me:
"""
Main chatbot class that handles conversations and impersonates the owner.
This class loads profile data, manages OpenAI interactions, and handles
function calling for lead capture and question tracking.
"""
def __init__(self):
"""
Initialize the chatbot with profile data and OpenAI client.
Loads LinkedIn PDF and summary text file to create the chatbot's
knowledge base about the owner.
"""
# Initialize OpenAI client
self.openai = OpenAI()
# Set the owner's name (hardcoded for now)
self.name = "Gowrisankar"
# Load LinkedIn profile from PDF
reader = PdfReader("documents/linkedin.pdf")
self.linkedin = ""
for page in reader.pages:
text = page.extract_text()
if text:
self.linkedin += text
# Load personal summary from text file
with open("documents/summary.txt", "r", encoding="utf-8") as f:
self.summary = f.read()
def handle_tool_call(self, tool_calls):
"""
Execute OpenAI function calls and return results.
This method processes tool calls from OpenAI, executes the corresponding
Python functions, and formats the results for the conversation.
Args:
tool_calls: List of tool calls from OpenAI response
Returns:
list: Formatted tool results for OpenAI conversation
"""
results = []
for tool_call in tool_calls:
# Extract tool name and arguments
tool_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f"Tool called: {tool_name}", flush=True)
# Get the corresponding Python function and execute it
tool = globals().get(tool_name)
result = tool(**arguments) if tool else {}
# Format result for OpenAI
results.append({
"role": "tool",
"content": json.dumps(result),
"tool_call_id": tool_call.id
})
return results
def system_prompt(self):
"""
Generate the system prompt with owner's profile data.
Creates a comprehensive system prompt that instructs the AI to impersonate
the owner using their LinkedIn profile and summary information.
Returns:
str: Complete system prompt for OpenAI
"""
system_prompt = f"""You are acting as {self.name}. You are answering questions on {self.name}'s website, \
particularly questions related to {self.name}'s career, background, skills and experience. \
Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. \
You are given a summary of {self.name}'s background and LinkedIn profile which you can use to answer questions. \
Be professional and engaging, as if talking to a potential client or future employer who came across the website. \
If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \
If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool."""
# Add profile data to the prompt
system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## LinkedIn Profile:\n{self.linkedin}\n\n"
system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}."
return system_prompt
def chat(self, message, history):
"""
Handle a chat message and return the AI response.
This method implements the conversation loop with OpenAI, handling
function calls and continuing the conversation until a final response.
Args:
message (str): User's input message
history (list): Previous conversation history
Returns:
str: AI's response message
"""
# Build complete message history including system prompt
messages = [
{"role": "system", "content": self.system_prompt()}
] + history + [
{"role": "user", "content": message}
]
# Continue conversation until no more function calls
done = False
while not done:
# Get response from OpenAI
response = self.openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools
)
# Check if OpenAI wants to call functions
if response.choices[0].finish_reason == "tool_calls":
# Extract and execute function calls
message_with_tools = response.choices[0].message
tool_calls = message_with_tools.tool_calls
tool_results = self.handle_tool_call(tool_calls)
# Add function call and results to conversation
messages.append(message_with_tools)
messages.extend(tool_results)
else:
# No more function calls, conversation is complete
done = True
return response.choices[0].message.content
# ================================
# APPLICATION ENTRY POINT
# ================================
if __name__ == "__main__":
# Initialize the chatbot
me = Me()
# Create and launch the Gradio web interface
# type="messages" enables proper conversation history handling
gr.ChatInterface(me.chat, type="messages", cache_examples=False).launch()
|