aznelite89's picture
updated initial message
b207e89
Raw History Blame Contribute Delete
10.3 kB
from dotenv import load_dotenv
from openai import OpenAI
import json
import os
import requests
from pypdf import PdfReader
import gradio as gr
import re
import uuid
load_dotenv(override=True)
def push(text: str):
requests.post(
"https://api.pushover.net/1/messages.json",
data={
"token": os.getenv("PUSHOVER_TOKEN"),
"user": os.getenv("PUSHOVER_USER"),
"message": text,
},
timeout=10,
)
def record_user_details(email, name="Name not provided", notes="not provided"):
# push(f"[Lead]\nEmail: {email}\nName: {name}\nNotes: {notes}")
return {"recorded": "ok"}
def record_unknown_question(question, email="unknown"):
push(
f"[⚠️ UNKNOWN QUESTION]\n"
f"Email: {email}\n"
f"Question: {question}"
)
return {"recorded": "ok"}
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,
},
}
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",
},
"email": {
"type": "string",
"description": "User email if known",
},
},
"required": ["question"],
"additionalProperties": False,
},
}
tools = [
{"type": "function", "function": record_user_details_json},
{"type": "function", "function": record_unknown_question_json},
]
class Me:
def __init__(self):
self.openai = OpenAI()
self.name = "Chan Thai Thong"
# lightweight session state (so push notifications include context)
self.session_id = str(uuid.uuid4())[:8]
self.user_email = None
self.last_user_message = None
reader = PdfReader("me/linkedin.pdf")
self.linkedin = ""
for page in reader.pages:
text = page.extract_text()
if text:
self.linkedin += text
with open("me/summary.txt", "r", encoding="utf-8") as f:
self.summary = f.read()
def handle_tool_call(self, tool_calls):
results = []
for tool_call in tool_calls:
tool_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments or "{}")
print(f"Tool called: {tool_name}", flush=True)
# Inject useful context automatically for push notifications..
if tool_name == "record_unknown_question":
arguments.setdefault("email", self.user_email or "unknown")
if tool_name == "record_user_details":
# If model did nott include notes, still attach context
notes = arguments.get("notes", "")
extra = f"(session={self.session_id}, last_user_message={self.last_user_message})"
arguments["notes"] = (notes + " " + extra).strip()
tool = globals().get(tool_name)
result = tool(**arguments) if tool else {}
results.append(
{
"role": "tool",
"content": json.dumps(result),
"tool_call_id": tool_call.id,
}
)
return results
def system_prompt(self):
system_prompt = (
f"You are acting as {self.name}. You are answering questions on {self.name}'s website, "
f"particularly questions related to {self.name}'s career, background, skills and experience. "
f"Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. "
f"You are given a summary of {self.name}'s background and Resume profile which you can use to answer questions. "
f"Be professional and engaging, as if talking to a potential client or future employer who came across the website. "
f"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, "
f"even if it's about something trivial or unrelated to career. "
f"If the user is engaging in discussion, try to steer them towards getting in touch via email; "
f"ask for their email and record it using your record_user_details tool.\n\n"
f"IMPORTANT BEHAVIOR:\n"
f"- Ask for the user's email ONCE early (e.g., after your first helpful answer) so they can contact you.\n"
f"- If the user already provided an email, do NOT ask again.\n"
f"- Keep the email request short and natural (one sentence).\n"
)
system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## Resume 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):
from types import SimpleNamespace
# Track last message for better tool notifications
self.last_user_message = message
# Capture email if user typed one so tool notifications include it..
m = re.search(r"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}", message, re.I)
if m:
self.user_email = m.group(0)
messages = [{"role": "system", "content": self.system_prompt()}] + history + [
{"role": "user", "content": message}
]
# Keep re-asking the model until it finishes without tool calls
while True:
# Accumulators for streaming content + tool call chunks
content_so_far = ""
tool_calls_acc = {} # index -> {"id":..., "function":{"name":..., "arguments":...}}
stream = self.openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
stream=True,
)
finish_reason = None
for chunk in stream:
choice = chunk.choices[0]
finish_reason = choice.finish_reason
delta = choice.delta
# Stream normal assistant text
if delta and delta.content:
content_so_far += delta.content
yield content_so_far
# Collect tool calls (they arrive in pieces)
if delta and delta.tool_calls:
for tc in delta.tool_calls:
idx = tc.index
acc = tool_calls_acc.setdefault(
idx,
{
"id": tc.id,
"type": "function",
"function": {"name": "", "arguments": ""},
},
)
if tc.id:
acc["id"] = tc.id
if tc.function and tc.function.name:
acc["function"]["name"] = tc.function.name
if tc.function and tc.function.arguments:
acc["function"]["arguments"] += tc.function.arguments
# If model asked for tools, execute them and continue the loop
if finish_reason == "tool_calls":
tool_calls_payload = []
tool_calls_objs = []
# Preserve order by index
for idx in sorted(tool_calls_acc.keys()):
acc = tool_calls_acc[idx]
tool_calls_payload.append(
{
"id": acc["id"],
"type": "function",
"function": {
"name": acc["function"]["name"],
"arguments": acc["function"]["arguments"],
},
}
)
# Build objects compatible with your existing handle_tool_call()
fn = SimpleNamespace(
name=acc["function"]["name"],
arguments=acc["function"]["arguments"],
)
tool_calls_objs.append(SimpleNamespace(id=acc["id"], function=fn))
# Append assistant tool-call message (per OpenAI chat format)
messages.append(
{
"role": "assistant",
"content": None,
"tool_calls": tool_calls_payload,
}
)
# Run tools and append tool results
results = self.handle_tool_call(tool_calls_objs)
messages.extend(results)
# Then loop again (model continues after tool outputs)
continue
# Otherwise we’re done (we already streamed the full content)
break
if __name__ == "__main__":
me = Me()
chatbot = gr.Chatbot(
value=[{"role": "assistant", "content": "👋 Ask me anything regarding my career. Drop me an email if you want to get in touch. 😎💌"}],
type="messages",
label="Chan Thai Thong's Personal Career AI Agent (able to answer, email, push notification to me directly if necessary)",
)
gr.ChatInterface(me.chat, chatbot=chatbot, type="messages").launch()