File size: 21,590 Bytes
b73cea4 |
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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
{
"cells": [
{
"cell_type": "markdown",
"id": "84dd193e",
"metadata": {},
"source": [
"## 5. Prompting with Python"
]
},
{
"cell_type": "markdown",
"id": "862b8218",
"metadata": {},
"source": [
"First, we’ll install the libraries we need. The `huggingface_hub` package is the official client for Hugging Face’s API. The `rich` and `ipywidgets` packages are helper libraries that will improve how your outputs look in Jupyter notebooks."
]
},
{
"cell_type": "markdown",
"id": "c09f0b15",
"metadata": {},
"source": [
"A common way to install packages from inside your JupyterLab Desktop notebook is to use the `%pip command`. Hit the play button in the top toolbar after selecting the cell below."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e728c5fe",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"%pip install rich ipywidgets huggingface_hub"
]
},
{
"cell_type": "markdown",
"id": "79f96b1a",
"metadata": {},
"source": [
"If the `%pip command` doesn’t work on your computer, try substituting the `!pip command` instead. Or you can install the packages from the command line on your computer and restart your notebook."
]
},
{
"cell_type": "markdown",
"id": "75f1366a",
"metadata": {},
"source": [
"Now let's import them in the cell that appears below the installation output. Hit play again."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "8013a72c-670e-48ab-8619-99a337fd5392",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from rich import print\n",
"from huggingface_hub import InferenceClient"
]
},
{
"cell_type": "markdown",
"id": "fdd7b199",
"metadata": {},
"source": [
"With `api_key = os.getenv(\"HF_TOKEN\")`, we're calling the free Hugging Face Inference API, using an authentication token stored in the \"Secrets\" of this Space. If you'd like to duplicate this Space, you'll need to create a token with your account [here](https://huggingface.co/settings/tokens).\n",
"\n",
"You should continue adding new cells as you need throughout the rest of the class."
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "a5ec5ea4-5bd1-4ba7-b4cb-3f0a98505f29",
"metadata": {},
"outputs": [],
"source": [
"api_key = os.getenv(\"HF_TOKEN\")"
]
},
{
"cell_type": "markdown",
"id": "b9e81187",
"metadata": {},
"source": [
"Let’s make our first prompt. To do that, we submit a dictionary to Hugging Face’s `chat.completions.create` method. The dictionary has a `messages` key that contains a list of dictionaries. Each dictionary in the list represents a message in the conversation. When the role is \"user\" it is roughly the same as asking a question to a chatbot."
]
},
{
"cell_type": "markdown",
"id": "e83c5390",
"metadata": {},
"source": [
"We also need to pick a model from among the choices Hugging Face gives us. We’re picking Llama 3.3, the latest from Meta."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "54a5befd-0c64-4039-9b26-14733c9f007e",
"metadata": {},
"outputs": [],
"source": [
"client = InferenceClient(\n",
" model=\"meta-llama/Llama-3.3-70B-Instruct\",\n",
" token=api_key,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "38abe6e0",
"metadata": {},
"outputs": [],
"source": [
"response = client.chat.completions.create(\n",
" messages=[\n",
" {\n",
" \"role\": \"user\",\n",
" \"content\": \"Explain the importance of data journalism in a concise sentence\"\n",
" }\n",
" ],\n",
")"
]
},
{
"cell_type": "markdown",
"id": "3156058c",
"metadata": {},
"source": [
"Our client saves the response as a variable. Print that Python object to see what it contains."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "49bf29f5",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionOutput</span><span style=\"font-weight: bold\">(</span><span style=\"color: #808000; text-decoration-color: #808000\">choices</span>=<span style=\"font-weight: bold\">[</span><span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionOutputComplete</span><span style=\"font-weight: bold\">(</span><span style=\"color: #808000; text-decoration-color: #808000\">finish_reason</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'stop'</span>, <span style=\"color: #808000; text-decoration-color: #808000\">index</span>=<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">0</span>, \n",
"<span style=\"color: #808000; text-decoration-color: #808000\">message</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionOutputMessage</span><span style=\"font-weight: bold\">(</span><span style=\"color: #808000; text-decoration-color: #808000\">role</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'assistant'</span>, <span style=\"color: #808000; text-decoration-color: #808000\">content</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'Data journalism plays a crucial role in holding </span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000\">institutions accountable and informing the public by analyzing and interpreting complex data to uncover trends, </span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000\">patterns, and insights that can lead to more informed decision-making and a deeper understanding of social </span>\n",
"<span style=\"color: #008000; text-decoration-color: #008000\">issues.'</span>, <span style=\"color: #808000; text-decoration-color: #808000\">tool_calls</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span><span style=\"font-weight: bold\">)</span>, <span style=\"color: #808000; text-decoration-color: #808000\">logprobs</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-style: italic\">None</span><span style=\"font-weight: bold\">)]</span>, <span style=\"color: #808000; text-decoration-color: #808000\">created</span>=<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">1742869712</span>, <span style=\"color: #808000; text-decoration-color: #808000\">id</span>=<span style=\"color: #008000; text-decoration-color: #008000\">''</span>, <span style=\"color: #808000; text-decoration-color: #808000\">model</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'meta-llama/Llama-3.3-70B-Instruct'</span>, \n",
"<span style=\"color: #808000; text-decoration-color: #808000\">system_fingerprint</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'3.0.1-sha-bb9095a'</span>, <span style=\"color: #808000; text-decoration-color: #808000\">usage</span>=<span style=\"color: #800080; text-decoration-color: #800080; font-weight: bold\">ChatCompletionOutputUsage</span><span style=\"font-weight: bold\">(</span><span style=\"color: #808000; text-decoration-color: #808000\">completion_tokens</span>=<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">45</span>, <span style=\"color: #808000; text-decoration-color: #808000\">prompt_tokens</span>=<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">46</span>, \n",
"<span style=\"color: #808000; text-decoration-color: #808000\">total_tokens</span>=<span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">91</span><span style=\"font-weight: bold\">)</span>, <span style=\"color: #808000; text-decoration-color: #808000\">object</span>=<span style=\"color: #008000; text-decoration-color: #008000\">'chat.completion'</span><span style=\"font-weight: bold\">)</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[1;35mChatCompletionOutput\u001b[0m\u001b[1m(\u001b[0m\u001b[33mchoices\u001b[0m=\u001b[1m[\u001b[0m\u001b[1;35mChatCompletionOutputComplete\u001b[0m\u001b[1m(\u001b[0m\u001b[33mfinish_reason\u001b[0m=\u001b[32m'stop'\u001b[0m, \u001b[33mindex\u001b[0m=\u001b[1;36m0\u001b[0m, \n",
"\u001b[33mmessage\u001b[0m=\u001b[1;35mChatCompletionOutputMessage\u001b[0m\u001b[1m(\u001b[0m\u001b[33mrole\u001b[0m=\u001b[32m'assistant'\u001b[0m, \u001b[33mcontent\u001b[0m=\u001b[32m'Data journalism plays a crucial role in holding \u001b[0m\n",
"\u001b[32minstitutions accountable and informing the public by analyzing and interpreting complex data to uncover trends, \u001b[0m\n",
"\u001b[32mpatterns, and insights that can lead to more informed decision-making and a deeper understanding of social \u001b[0m\n",
"\u001b[32missues.'\u001b[0m, \u001b[33mtool_calls\u001b[0m=\u001b[3;35mNone\u001b[0m\u001b[1m)\u001b[0m, \u001b[33mlogprobs\u001b[0m=\u001b[3;35mNone\u001b[0m\u001b[1m)\u001b[0m\u001b[1m]\u001b[0m, \u001b[33mcreated\u001b[0m=\u001b[1;36m1742869712\u001b[0m, \u001b[33mid\u001b[0m=\u001b[32m''\u001b[0m, \u001b[33mmodel\u001b[0m=\u001b[32m'meta-llama/Llama-3.3-70B-Instruct'\u001b[0m, \n",
"\u001b[33msystem_fingerprint\u001b[0m=\u001b[32m'3.0.1-sha-bb9095a'\u001b[0m, \u001b[33musage\u001b[0m=\u001b[1;35mChatCompletionOutputUsage\u001b[0m\u001b[1m(\u001b[0m\u001b[33mcompletion_tokens\u001b[0m=\u001b[1;36m45\u001b[0m, \u001b[33mprompt_tokens\u001b[0m=\u001b[1;36m46\u001b[0m, \n",
"\u001b[33mtotal_tokens\u001b[0m=\u001b[1;36m91\u001b[0m\u001b[1m)\u001b[0m, \u001b[33mobject\u001b[0m=\u001b[32m'chat.completion'\u001b[0m\u001b[1m)\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"print(response)"
]
},
{
"cell_type": "markdown",
"id": "d9f86d8e",
"metadata": {},
"source": [
"You should see something like:"
]
},
{
"cell_type": "markdown",
"id": "cdf08e93-a6cc-4245-9fa3-2cc456208bcf",
"metadata": {},
"source": [
"```\n",
"ChatCompletionOutput(\n",
" choices=[\n",
" ChatCompletionOutputComplete(\n",
" finish_reason='stop',\n",
" index=0,\n",
" message=ChatCompletionOutputMessage(\n",
" role='assistant',\n",
" content='Data journalism plays a crucial role in holding those in power accountable by using data analysis and visualization to uncover insights, trends, and patterns that inform and engage the public on important issues.',\n",
" tool_calls=None\n",
" ),\n",
" logprobs=None\n",
" )\n",
" ],\n",
" created=1742592105,\n",
" id='',\n",
" model='meta-llama/Llama-3.3-70B-Instruct',\n",
" system_fingerprint='3.2.1-native',\n",
" usage=ChatCompletionOutputUsage(\n",
" completion_tokens=37,\n",
" prompt_tokens=46,\n",
" total_tokens=83\n",
" ),\n",
" object='chat.completion'\n",
")\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "ff414bab",
"metadata": {},
"source": [
"There’s a lot here, but the `message` has the actual response from the LLM. Let’s just print the content from that message. Note that your response probably varies from this guide. That’s because LLMs mostly are probablistic prediction machines. Every response can be a little different."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "0f291693",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Data journalism plays a crucial role in holding institutions accountable and informing the public by analyzing and \n",
"interpreting complex data to uncover trends, patterns, and insights that can lead to more informed decision-making \n",
"and a deeper understanding of social issues.\n",
"</pre>\n"
],
"text/plain": [
"Data journalism plays a crucial role in holding institutions accountable and informing the public by analyzing and \n",
"interpreting complex data to uncover trends, patterns, and insights that can lead to more informed decision-making \n",
"and a deeper understanding of social issues.\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"print(response.choices[0].message.content)"
]
},
{
"cell_type": "markdown",
"id": "0c1e292a",
"metadata": {},
"source": [
"Let’s pick a different model from amongthe choices that Hugging Face offers. One we could try is Gemma2, an open model from Google. Rather than add a new cell, lets revise the code we already have and rerun it."
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "9fb3f9b8",
"metadata": {},
"outputs": [],
"source": [
"response = client.chat.completions.create(\n",
" messages=[\n",
" {\n",
" \"role\": \"user\",\n",
" \"content\": \"Explain the importance of data journalism in a concise sentence\",\n",
" }\n",
" ],\n",
" model=\"google/gemma-2-9b-it\", # NEW\n",
")"
]
},
{
"cell_type": "markdown",
"id": "aa6662ed",
"metadata": {},
"source": [
"Again, your response might vary from what’s here. Let’s find out."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "0f036c66",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Data journalism plays a crucial role in holding those in power accountable by uncovering hidden trends, patterns, \n",
"and insights through the analysis and visualization of data, enabling informed decision-making and promoting \n",
"transparency.\n",
"</pre>\n"
],
"text/plain": [
"Data journalism plays a crucial role in holding those in power accountable by uncovering hidden trends, patterns, \n",
"and insights through the analysis and visualization of data, enabling informed decision-making and promoting \n",
"transparency.\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"print(response.choices[0].message.content)"
]
},
{
"cell_type": "markdown",
"id": "12802cac",
"metadata": {},
"source": [
"---\n",
"### Sidenote:\n",
"Hugging Face’s Python library is very similar to the ones offered by OpenAI, Anthropic and other LLM providers. If you prefer to use those tools, the techniques you learn here should be easily transferable."
]
},
{
"cell_type": "markdown",
"id": "e7668bd3",
"metadata": {},
"source": [
"For instance, here’s how you’d make this same call with Anthropic’s Python library:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "11e567e3",
"metadata": {},
"outputs": [],
"source": [
"from anthropic import Anthropic\n",
"\n",
"client = Anthropic(api_key=api_key)\n",
"\n",
"response = client.messages.create(\n",
" messages=[\n",
" {\"role\": \"user\", \"content\": \"Explain the importance of data journalism in a concise sentence\"},\n",
" ],\n",
" model=\"claude-3-5-sonnet-20240620\",\n",
")\n",
"\n",
"print(response.content[0].text)"
]
},
{
"cell_type": "markdown",
"id": "182e8e6b",
"metadata": {},
"source": [
"---\n",
"A well-structured prompt helps the LLM provide more accurate and useful responses."
]
},
{
"cell_type": "markdown",
"id": "da211bea",
"metadata": {},
"source": [
"One common technique for improving results is to open with a “system” prompt to establish the model’s tone and role. Let’s switch back to Llama 3.3 and provide a `system` message that provides a specific motivation for the LLM’s responses."
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "a5660ed5",
"metadata": {},
"outputs": [],
"source": [
"response = client.chat.completions.create(\n",
" messages=[\n",
" ### <-- NEW\n",
" {\n",
" \"role\": \"system\",\n",
" \"content\": \"you are an enthusiastic nerd who believes data journalism is the future.\"\n",
" },\n",
" ### -->\n",
" {\n",
" \"role\": \"user\",\n",
" \"content\": \"Explain the importance of data journalism in a concise sentence\",\n",
" }\n",
" ],\n",
" model=\"meta-llama/Llama-3.3-70B-Instruct\", # NEW\n",
")"
]
},
{
"cell_type": "markdown",
"id": "598dd139",
"metadata": {},
"source": [
"Check out the results."
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "a5c74d22",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Data journalism is revolutionizing the way we consume news by using statistical analysis and visualizations to \n",
"uncover hidden truths, provide fact-based evidence, and hold those in power accountable, thereby fostering a more \n",
"informed and engaged citizenry!\n",
"</pre>\n"
],
"text/plain": [
"Data journalism is revolutionizing the way we consume news by using statistical analysis and visualizations to \n",
"uncover hidden truths, provide fact-based evidence, and hold those in power accountable, thereby fostering a more \n",
"informed and engaged citizenry!\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"print(response.choices[0].message.content)"
]
},
{
"cell_type": "markdown",
"id": "304bbabc",
"metadata": {},
"source": [
"Want to see how tone affects the response? Change the system prompt to something old-school."
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "3123cd0b",
"metadata": {},
"outputs": [],
"source": [
"response = client.chat.completions.create(\n",
" messages=[\n",
" {\n",
" \"role\": \"system\",\n",
" \"content\": \"you are a crusty, ill-tempered editor who hates math and thinks data journalism is a waste of time and resources.\" # NEW\n",
" },\n",
" {\n",
" \"role\": \"user\",\n",
" \"content\": \"Explain the importance of data journalism in a concise sentence\",\n",
" }\n",
" ],\n",
" model=\"meta-llama/Llama-3.3-70B-Instruct\",\n",
")"
]
},
{
"cell_type": "markdown",
"id": "b90dd487",
"metadata": {},
"source": [
"Then re-run the code and summon J. Jonah Jameson."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "3defdc9c",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">If I must, data journalism is supposedly important because it allows reporters to use numbers and statistics to \n",
"fact-check claims, identify trends, and hold those in power accountable, but frankly, I've seen better storytelling\n",
"in a spreadsheet.\n",
"</pre>\n"
],
"text/plain": [
"If I must, data journalism is supposedly important because it allows reporters to use numbers and statistics to \n",
"fact-check claims, identify trends, and hold those in power accountable, but frankly, I've seen better storytelling\n",
"in a spreadsheet.\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"print(response.choices[0].message.content)"
]
},
{
"cell_type": "markdown",
"id": "957517fa-e69b-42bb-88b5-3a71b680972f",
"metadata": {},
"source": [
"**[6. Structured responses →](ch6-structured-responses.ipynb)**"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0e45220f-a77c-4463-8211-96dd79b09840",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|