Spaces:
Sleeping
Sleeping
File size: 14,627 Bytes
b38c914 |
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 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 231,
"id": "3895c0bb",
"metadata": {},
"outputs": [],
"source": [
"from sentence_transformers import SentenceTransformer\n",
"from openai import OpenAI\n",
"import os\n",
"from dotenv import load_dotenv\n",
"load_dotenv(override=True)\n",
"\n",
"import json"
]
},
{
"cell_type": "code",
"execution_count": 232,
"id": "25b603fe",
"metadata": {},
"outputs": [],
"source": [
"def push(message):\n",
" print(message)"
]
},
{
"cell_type": "code",
"execution_count": 233,
"id": "418dbe4c",
"metadata": {},
"outputs": [],
"source": [
"def record_user_details(email, name=\"Name not provided\", notes=\"not provided\"):\n",
" push(f\"Recording interest from {name} with email {email} and notes {notes}\")\n",
" return {\"recorded\": \"ok\"}\n",
"\n",
"record_user_details_json = {\n",
" \"name\": \"record_user_details\",\n",
" \"description\": \"Use this tool to record that a user is interested in being in touch and provided an email address\",\n",
" \"parameters\": {\n",
" \"type\":\"object\",\n",
" \"properties\":{\n",
" \"email\":{\n",
" \"type\":\"string\",\n",
" \"description\":\"The email address of this user\"\n",
" },\n",
" \"name\":{\n",
" \"type\":\"string\",\n",
" \"description\":\"The user's name, if they provided it\"\n",
" },\n",
" \"nodes\":{\n",
" \"type\":\"string\",\n",
" \"description\":\"Any additional information about the conversation that's worth recording to give context\"\n",
" }\n",
" },\n",
" \"required\":[\"email\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 234,
"id": "aa638360",
"metadata": {},
"outputs": [],
"source": [
"def record_unknown_question(question):\n",
" push(f\"Recording {question} asked that I couldn't answer\")\n",
" return {\"recorded\":\"ok\"}\n",
"\n",
"record_unknown_question_json = {\n",
" \"name\": \"record_unknown_question\",\n",
" \"description\":\"Always use this tool to record any question that couldn't be answered as you didn't know the answer\",\n",
" \"parameters\":{\n",
" \"type\":\"object\",\n",
" \"properties\":{\n",
" \"question\":{\n",
" \"type\":\"string\",\n",
" \"description\":\"The question that couldn't be answered\"\n",
" }\n",
" },\n",
" \"required\":[\"question\"],\n",
" \"additionalProperties\": False\n",
" }\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 235,
"id": "00bd8d59",
"metadata": {},
"outputs": [],
"source": [
"tools = [\n",
" {\"type\":\"function\", \"function\":record_user_details_json},\n",
" {\"type\":\"function\", \"function\":record_unknown_question_json}\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 236,
"id": "21bc1809",
"metadata": {},
"outputs": [],
"source": [
"def handle_tool_calls(tool_calls):\n",
" results = []\n",
" for tool_call in tool_calls:\n",
" tool_name = tool_call.function.name\n",
" arguments = json.loads(tool_call.function.arguments)\n",
" print(f\"tool called {tool_name}\", flush=True)\n",
" tool = globals().get(tool_name)\n",
" result = tool(**arguments) if tool else {}\n",
" results.append({\"role\":\"tool\", \"content\":json.dumps(result),\"tool_call_id\":tool_call.id})\n",
"\n",
" return results\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 237,
"id": "ff9ed790",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Ignoring wrong pointing object 8 0 (offset 0)\n",
"Ignoring wrong pointing object 13 0 (offset 0)\n",
"Ignoring wrong pointing object 22 0 (offset 0)\n",
"Ignoring wrong pointing object 92 0 (offset 0)\n",
"Ignoring wrong pointing object 93 0 (offset 0)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Deleted collection: profile\n"
]
}
],
"source": [
"from pypdf import PdfReader\n",
"import chromadb\n",
"\n",
"collection_name = \"profile\"\n",
"chroma_client = chromadb.Client()\n",
"try:\n",
" chroma_client.delete_collection(name=collection_name)\n",
" print(f\"Deleted collection: {collection_name}\")\n",
"except Exception as e:\n",
" print(f\"No existing collection found: {collection_name}\")\n",
"collection = chroma_client.create_collection(collection_name)\n",
"\n",
"\n",
"resume_txt = ''\n",
"resume_reader = PdfReader('me/Jongkook Kim - Resume.pdf')\n",
"for page in resume_reader.pages:\n",
" text = page.extract_text()\n",
" if text:\n",
" resume_txt += text\n",
"\n",
"def chunk_text(text, chunk_size=500, overlap=50):\n",
" words = text.split()\n",
" chunks = []\n",
" start = 0\n",
" while start < len(words):\n",
" end = min(start + chunk_size, len(words))\n",
" chunk = \" \".join(words[start:end])\n",
" chunks.append(chunk)\n",
" start += chunk_size - overlap\n",
" return chunks\n",
"\n",
"resume_chunks = chunk_text(text=resume_txt, chunk_size=250, overlap=25)\n",
"\n",
"embedding_model = SentenceTransformer(\"sentence-transformers/all-MiniLM-L6-v2\")\n",
"\n",
"for index, chunk in enumerate(resume_chunks):\n",
" embedding = embedding_model.encode(chunk).tolist()\n",
" collection.add(ids=[str(index)], documents=[chunk], embeddings=[embedding])\n",
"\n",
"\n",
"linkedin = ''\n",
"linkedin_profile = PdfReader('me/Profile.pdf')\n",
"for page in linkedin_profile.pages:\n",
" text = page.extract_text()\n",
" if text:\n",
" linkedin += text\n"
]
},
{
"cell_type": "code",
"execution_count": 238,
"id": "3152c2ed",
"metadata": {},
"outputs": [],
"source": [
"\n",
"name = 'Jongkook Kim'\n",
"\n",
"from pydantic import BaseModel\n",
"\n",
"class Evaluation(BaseModel):\n",
" is_acceptable: bool\n",
" feedback: str\n",
" avator_response: str "
]
},
{
"cell_type": "code",
"execution_count": 239,
"id": "a930fd87",
"metadata": {},
"outputs": [],
"source": [
"avator_system_prompt = f\"\"\"You are acting as {name}. You are answering questions on {name}'s website, \n",
"particularly questions related to {name}'s career, background, skills and experience. \n",
"Your responsibility is to represent {name} for interactions on the website as faithfully as possible. \n",
"You are given a Resume of {name}'s background which you can use to answer questions. \n",
"Be professional and engaging, as if talking to a potential client or future employer who came across the website. \n",
"If you don't know the answer, say so.\n",
"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. \\\n",
"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. \"\"\"\n",
"\n",
"\n",
"def avator(message, history, evaluation: Evaluation):\n",
" message_embedding = embedding_model.encode(message).tolist()\n",
" similarity_search = collection.query(query_embeddings=message_embedding, n_results=3)\n",
"\n",
" system_prompt = avator_system_prompt\n",
" system_prompt += f\"\\n\\n## Resume:\\n{similarity_search[\"documents\"]} {linkedin}\\n\\n\"\n",
" system_prompt += f\"With this context, please chat with the user, always staying in character as {name}.\"\n",
"\n",
"\n",
" if evaluation and not evaluation.is_acceptable:\n",
" print(f\"{evaluation.avator_response} is not acceptable. Retry\")\n",
" system_prompt += \"\\n\\n## Previous answer rejected\\nYou just tried to reply, but the quality control rejected your reply\\n\"\n",
" system_prompt += f\"## Your attempted answer:\\n{evaluation.avator_response}\\n\\n\"\n",
" system_prompt += f\"## Reason for rejection:\\n{evaluation.feedback}\\n\\n\" \n",
"\n",
" messages = [{\"role\":\"system\", \"content\": system_prompt}] + history + [{\"role\":\"user\", \"content\": message}] \n",
"\n",
" done = False\n",
" while not done:\n",
" llm_client = OpenAI().chat.completions.create(model=\"gpt-4o-mini\", messages=messages, tools=tools)\n",
" print('get response from llm')\n",
" finish_reason = llm_client.choices[0].finish_reason\n",
" if finish_reason == \"tool_calls\":\n",
" print('this is tool calls')\n",
" llm_response = llm_client.choices[0].message\n",
" tool_calls = llm_response.tool_calls\n",
" tool_response = handle_tool_calls(tool_calls)\n",
" messages.append(llm_response)\n",
" messages.extend(tool_response)\n",
" else:\n",
" print('this is message response')\n",
" done = True\n",
"\n",
" return llm_client.choices[0].message.content"
]
},
{
"cell_type": "code",
"execution_count": 240,
"id": "8e99a0f4",
"metadata": {},
"outputs": [],
"source": [
"evaluator_system_prompt = f\"You are an evaluator that decides whether a response to a question is acceptable. \\\n",
"You are provided with a conversation between a User and an Agent. Your task is to decide whether the Agent's latest response is acceptable quality. \\\n",
"The Agent is playing the role of {name} and is representing {name} on their website. \\\n",
"The Agent has been instructed to be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n",
"The Agent has been provided with context on {name} in the form of their Resume details. Here's the information:\"\n",
"\n",
"def evaluator_user_prompt(question, avator_response, history):\n",
" user_prompt = f\"Here's the conversation between the User and the Agent: \\n\\n{history}\\n\\n\"\n",
" user_prompt += f\"Here's the latest message from the User: \\n\\n{question}\\n\\n\"\n",
" user_prompt += f\"Here's the latest response from the Agent: \\n\\n{avator_response}\\n\\n\"\n",
" user_prompt += \"Please evaluate the response, replying with whether it is acceptable and your feedback.\"\n",
" return user_prompt\n",
"\n",
"def evaluator(question, avator_response, history) -> Evaluation:\n",
" message_embedding = embedding_model.encode(question).tolist()\n",
" similarity_search = collection.query(query_embeddings=message_embedding, n_results=3)\n",
"\n",
" system_prompt = evaluator_system_prompt + f\"## Resume:\\n{similarity_search[\"documents\"]} {linkedin}\\n\\n\"\n",
" system_prompt += f\"With this context, please evaluate the latest response, replying with whether the response is acceptable and your feedback.\"\n",
"\n",
" messages = [{\"role\":\"system\", \"content\":system_prompt}] + [{\"role\":\"user\", \"content\":evaluator_user_prompt(question, avator_response, history)}]\n",
" llm_client = OpenAI(api_key=os.getenv('GOOGLE_API_KEY'), base_url='https://generativelanguage.googleapis.com/v1beta/openai/')\n",
" evaluation = llm_client.beta.chat.completions.parse(\n",
" model=\"gemini-2.0-flash\",\n",
" messages=messages,\n",
" response_format=Evaluation\n",
" )\n",
"\n",
" evaluation = evaluation.choices[0].message.parsed\n",
" evaluation.avator_response = avator_response\n",
" return evaluation"
]
},
{
"cell_type": "code",
"execution_count": 241,
"id": "66e3b39d",
"metadata": {},
"outputs": [],
"source": [
"max_attempt = 2\n",
"\n",
"def orchestrator(message, history):\n",
" avator_response = avator(message, history, None)\n",
" print('get response from avator')\n",
"\n",
" for attempt in range(1, max_attempt + 1):\n",
" print(f'try {attempt} times')\n",
"\n",
" evaluation = evaluator(message, avator_response, history)\n",
" print('get response from evaluation')\n",
"\n",
" if not evaluation.is_acceptable:\n",
" print('reponse from avator is not acceptable')\n",
" message_with_feedback = evaluation.feedback + message\n",
" avator_response = avator(message_with_feedback, history, evaluation)\n",
" else:\n",
" print('response from avator is acceptable')\n",
" break\n",
"\n",
" return avator_response"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "613c4504",
"metadata": {},
"outputs": [],
"source": [
"import gradio\n",
"gradio.ChatInterface(orchestrator, type=\"messages\").launch()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|