Zalaid commited on
Commit
b06feb4
·
verified ·
1 Parent(s): 548c54d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -58
app.py CHANGED
@@ -1,70 +1,141 @@
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
 
 
 
 
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
20
 
21
- messages.extend(history)
 
 
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
24
 
25
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
 
38
 
39
- response += token
40
- yield response
41
 
 
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
68
-
69
- if __name__ == "__main__":
70
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from openai import OpenAI
4
+ import json
5
  import gradio as gr
6
+ from pypdf import PdfReader
7
 
8
+ # ---------------------------
9
+ # Secrets from Hugging Face
10
+ # ---------------------------
11
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
12
+ PUSHOVER_USER = os.getenv("PUSHOVER_USER")
13
+ PUSHOVER_TOKEN = os.getenv("PUSHOVER_TOKEN")
14
+ PUSHOVER_URL = "https://api.pushover.net/1/messages.json"
15
 
16
+ # Initialize OpenAI client
17
+ openai = OpenAI(api_key=OPENAI_API_KEY)
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ # ---------------------------
20
+ # Push notification helper
21
+ # ---------------------------
22
+ def push(message):
23
+ print(f"Push: {message}")
24
+ payload = {"user": PUSHOVER_USER, "token": PUSHOVER_TOKEN, "message": message}
25
+ requests.post(PUSHOVER_URL, data=payload)
26
 
27
+ # ---------------------------
28
+ # Tool functions
29
+ # ---------------------------
30
+ def connect(email, name="no name", notes="no notes"):
31
+ push(f'Someone wants to connect with email: {email}, name: {name}, notes: {notes}')
32
+ return {"recorded": "ok"}
33
 
34
+ def unknown(message):
35
+ push(f'The question I could not answer was: {message}')
36
+ return {"recorded": "ok"}
37
 
38
+ # JSON schema for tools
39
+ connect_json = {
40
+ "name": "connect",
41
+ "description": "Use this tool when someone wants to connect",
42
+ "parameters": {
43
+ "type": "object",
44
+ "properties": {
45
+ "email": {"type": "string", "description": "Email of person wanting to connect"},
46
+ "name": {"type": "string", "description": "Name of person wanting to connect"},
47
+ "notes": {"type": "string", "description": "Additional notes"}
48
+ },
49
+ "required": ["email"],
50
+ "additionalProperties": False
51
+ }
52
+ }
53
 
54
+ unknown_json = {
55
+ "name": "unknown",
56
+ "description": "Use this tool when you don't know the answer to a question",
57
+ "parameters": {
58
+ "type": "object",
59
+ "properties": {
60
+ "message": {"type": "string", "description": "The question asked by the user"}
61
+ },
62
+ "required": ["message"],
63
+ "additionalProperties": False
64
+ }
65
+ }
66
 
67
+ tools = [{"type": "function", "function": connect_json}, {"type": "function", "function": unknown_json}]
 
68
 
69
+ def handle_tool_calls(tool_calls):
70
+ results = []
71
+ for tool_call in tool_calls:
72
+ name = tool_call.function.name
73
+ print(f'Tool called: {name}')
74
+ arguments = json.loads(tool_call.function.arguments)
75
 
76
+ if name == "unknown":
77
+ result = unknown(**arguments)
78
+ elif name == "connect":
79
+ result = connect(**arguments)
80
+
81
+ results.append({"role": "tool", "content": json.dumps(result), "tool_call_id": tool_call.id})
82
+ return results
83
+
84
+ # ---------------------------
85
+ # Load PDF & summary
86
+ # ---------------------------
87
+ reader = PdfReader("me/Profile.pdf")
88
+ linkedin = "".join([page.extract_text() or "" for page in reader.pages])
89
+
90
+ with open("me/summary.txt", "r", encoding="utf-8") as f:
91
+ summary = f.read()
92
+
93
+ # ---------------------------
94
+ # System prompt
95
+ # ---------------------------
96
+ name = "Zalaid Butt"
97
+ system_prompt = f"""
98
+ If you don't know the answer, just say you don't know.
99
+ You are acting as {name}. You are answering questions on {name}'s website,
100
+ particularly related to {name}'s career, background, skills and experience.
101
+ Be professional and engaging, as if talking to a potential client or future employer.
102
+ If you don't know the answer, use the record_unknown_question tool.
103
+ If the user wants to connect, use the record_user_details tool.
104
  """
105
+
106
+ system_prompt += f"\n\n## Summary:\n{summary}\n\n## LinkedIn Profile:\n{linkedin}\n\n"
107
+ system_prompt += f"With this context, please chat with the user, always staying in character as {name}. "
108
+ system_prompt += "Always be concise; do not give any additional information if not asked. " \
109
+ "If you don't know the answer, use the tool but don't give wrong/fake answers."
110
+
111
+ # ---------------------------
112
+ # Chat function
113
+ # ---------------------------
114
+ def chat(message, history):
115
+ messages = [{"role": "system", "content": system_prompt}] + history + [{"role": "user", "content": message}]
116
+ done = False
117
+ while not done:
118
+ response = openai.chat.completions.create(
119
+ model="gpt-3.5-turbo",
120
+ messages=messages,
121
+ tools=tools
122
+ )
123
+
124
+ finish_reason = response.choices[0].finish_reason
125
+
126
+ if finish_reason == "tool_calls":
127
+ message_obj = response.choices[0].message
128
+ tool_calls = message_obj.tool_calls
129
+ result = handle_tool_calls(tool_calls)
130
+
131
+ messages.append(message_obj)
132
+ messages.extend(result)
133
+ else:
134
+ done = True
135
+
136
+ return response.choices[0].message.content
137
+
138
+ # ---------------------------
139
+ # Launch Gradio
140
+ # ---------------------------
141
+ gr.ChatInterface(chat, type="messages").launch()