Spaces:
Running
Running
File size: 19,102 Bytes
cfd3735 |
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 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 |
{
"cells": [
{
"cell_type": "markdown",
"id": "683953b3",
"metadata": {},
"source": [
"# Annoy\n",
"\n",
"> \"Annoy (Approximate Nearest Neighbors Oh Yeah) is a C++ library with Python bindings to search for points in space that are close to a given query point. It also creates large read-only file-based data structures that are mmapped into memory so that many processes may share the same data.\"\n",
"\n",
"This notebook shows how to use functionality related to the `Annoy` vector database.\n",
"\n",
"via [Annoy](https://github.com/spotify/annoy) \n"
]
},
{
"cell_type": "markdown",
"id": "3b450bdc",
"metadata": {},
"source": [
"```{note}\n",
"NOTE: Annoy is read-only - once the index is built you cannot add any more emebddings!\n",
"If you want to progressively add new entries to your VectorStore then better choose an alternative!\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "6613d222",
"metadata": {},
"source": [
"## Create VectorStore from texts"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "dc7351b5",
"metadata": {},
"outputs": [],
"source": [
"from langchain.embeddings import HuggingFaceEmbeddings\n",
"from langchain.vectorstores import Annoy\n",
"\n",
"embeddings_func = HuggingFaceEmbeddings()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "d2cb5f7d",
"metadata": {},
"outputs": [],
"source": [
"texts = [\"pizza is great\", \"I love salad\", \"my car\", \"a dog\"]\n",
"\n",
"# default metric is angular\n",
"vector_store = Annoy.from_texts(texts, embeddings_func)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "a856b2d1",
"metadata": {},
"outputs": [],
"source": [
"# allows for custom annoy parameters, defaults are n_trees=100, n_jobs=-1, metric=\"angular\"\n",
"vector_store_v2 = Annoy.from_texts(\n",
" texts, embeddings_func, metric=\"dot\", n_trees=100, n_jobs=1\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "8ada534a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='pizza is great', metadata={}),\n",
" Document(page_content='I love salad', metadata={}),\n",
" Document(page_content='my car', metadata={})]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vector_store.similarity_search(\"food\", k=3)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "0470c5c8",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(Document(page_content='pizza is great', metadata={}), 1.0944390296936035),\n",
" (Document(page_content='I love salad', metadata={}), 1.1273186206817627),\n",
" (Document(page_content='my car', metadata={}), 1.1580758094787598)]"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# the score is a distance metric, so lower is better\n",
"vector_store.similarity_search_with_score(\"food\", k=3)"
]
},
{
"cell_type": "markdown",
"id": "4583b231",
"metadata": {},
"source": [
"## Create VectorStore from docs"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "fbe898a8",
"metadata": {},
"outputs": [],
"source": [
"from langchain.document_loaders import TextLoader\n",
"from langchain.text_splitter import CharacterTextSplitter\n",
"\n",
"loader = TextLoader(\"../../../state_of_the_union.txt\")\n",
"documents = loader.load()\n",
"text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
"docs = text_splitter.split_documents(documents)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "51ea6b5c",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. \\n\\nLast year COVID-19 kept us apart. This year we are finally together again. \\n\\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. \\n\\nWith a duty to one another to the American people to the Constitution. \\n\\nAnd with an unwavering resolve that freedom will always triumph over tyranny. \\n\\nSix days ago, Russia’s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. \\n\\nHe thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. \\n\\nHe met the Ukrainian people. \\n\\nFrom President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world.', metadata={'source': '../../../state_of_the_union.txt'}),\n",
" Document(page_content='Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. \\n\\nIn this struggle as President Zelenskyy said in his speech to the European Parliament “Light will win over darkness.” The Ukrainian Ambassador to the United States is here tonight. \\n\\nLet each of us here tonight in this Chamber send an unmistakable signal to Ukraine and to the world. \\n\\nPlease rise if you are able and show that, Yes, we the United States of America stand with the Ukrainian people. \\n\\nThroughout our history we’ve learned this lesson when dictators do not pay a price for their aggression they cause more chaos. \\n\\nThey keep moving. \\n\\nAnd the costs and the threats to America and the world keep rising. \\n\\nThat’s why the NATO Alliance was created to secure peace and stability in Europe after World War 2. \\n\\nThe United States is a member along with 29 other nations. \\n\\nIt matters. American diplomacy matters. American resolve matters.', metadata={'source': '../../../state_of_the_union.txt'}),\n",
" Document(page_content='Putin’s latest attack on Ukraine was premeditated and unprovoked. \\n\\nHe rejected repeated efforts at diplomacy. \\n\\nHe thought the West and NATO wouldn’t respond. And he thought he could divide us at home. Putin was wrong. We were ready. Here is what we did. \\n\\nWe prepared extensively and carefully. \\n\\nWe spent months building a coalition of other freedom-loving nations from Europe and the Americas to Asia and Africa to confront Putin. \\n\\nI spent countless hours unifying our European allies. We shared with the world in advance what we knew Putin was planning and precisely how he would try to falsely justify his aggression. \\n\\nWe countered Russia’s lies with truth. \\n\\nAnd now that he has acted the free world is holding him accountable. \\n\\nAlong with twenty-seven members of the European Union including France, Germany, Italy, as well as countries like the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzerland.', metadata={'source': '../../../state_of_the_union.txt'}),\n",
" Document(page_content='We are inflicting pain on Russia and supporting the people of Ukraine. Putin is now isolated from the world more than ever. \\n\\nTogether with our allies –we are right now enforcing powerful economic sanctions. \\n\\nWe are cutting off Russia’s largest banks from the international financial system. \\n\\nPreventing Russia’s central bank from defending the Russian Ruble making Putin’s $630 Billion “war fund” worthless. \\n\\nWe are choking off Russia’s access to technology that will sap its economic strength and weaken its military for years to come. \\n\\nTonight I say to the Russian oligarchs and corrupt leaders who have bilked billions of dollars off this violent regime no more. \\n\\nThe U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs. \\n\\nWe are joining with our European allies to find and seize your yachts your luxury apartments your private jets. We are coming for your ill-begotten gains.', metadata={'source': '../../../state_of_the_union.txt'}),\n",
" Document(page_content='And tonight I am announcing that we will join our allies in closing off American air space to all Russian flights – further isolating Russia – and adding an additional squeeze –on their economy. The Ruble has lost 30% of its value. \\n\\nThe Russian stock market has lost 40% of its value and trading remains suspended. Russia’s economy is reeling and Putin alone is to blame. \\n\\nTogether with our allies we are providing support to the Ukrainians in their fight for freedom. Military assistance. Economic assistance. Humanitarian assistance. \\n\\nWe are giving more than $1 Billion in direct assistance to Ukraine. \\n\\nAnd we will continue to aid the Ukrainian people as they defend their country and to help ease their suffering. \\n\\nLet me be clear, our forces are not engaged and will not engage in conflict with Russian forces in Ukraine. \\n\\nOur forces are not going to Europe to fight in Ukraine, but to defend our NATO Allies – in the event that Putin decides to keep moving west.', metadata={'source': '../../../state_of_the_union.txt'})]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"docs[:5]"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "d080985b",
"metadata": {},
"outputs": [],
"source": [
"vector_store_from_docs = Annoy.from_documents(docs, embeddings_func)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "4931cb99",
"metadata": {},
"outputs": [],
"source": [
"query = \"What did the president say about Ketanji Brown Jackson\"\n",
"docs = vector_store_from_docs.similarity_search(query)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "97969d5b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Ac\n"
]
}
],
"source": [
"print(docs[0].page_content[:100])"
]
},
{
"cell_type": "markdown",
"id": "79628542",
"metadata": {},
"source": [
"## Create VectorStore via existing embeddings"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "3432eddb",
"metadata": {},
"outputs": [],
"source": [
"embs = embeddings_func.embed_documents(texts)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "b69f8408",
"metadata": {},
"outputs": [],
"source": [
"data = list(zip(texts, embs))\n",
"\n",
"vector_store_from_embeddings = Annoy.from_embeddings(data, embeddings_func)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "e260758d",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(Document(page_content='pizza is great', metadata={}), 1.0944390296936035),\n",
" (Document(page_content='I love salad', metadata={}), 1.1273186206817627),\n",
" (Document(page_content='my car', metadata={}), 1.1580758094787598)]"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vector_store_from_embeddings.similarity_search_with_score(\"food\", k=3)"
]
},
{
"cell_type": "markdown",
"id": "341390c2",
"metadata": {},
"source": [
"## Search via embeddings"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "b9bce06d",
"metadata": {},
"outputs": [],
"source": [
"motorbike_emb = embeddings_func.embed_query(\"motorbike\")"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "af2552c9",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='my car', metadata={}),\n",
" Document(page_content='a dog', metadata={}),\n",
" Document(page_content='pizza is great', metadata={})]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vector_store.similarity_search_by_vector(motorbike_emb, k=3)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "c7a1a924",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(Document(page_content='my car', metadata={}), 1.0870471000671387),\n",
" (Document(page_content='a dog', metadata={}), 1.2095637321472168),\n",
" (Document(page_content='pizza is great', metadata={}), 1.3254905939102173)]"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vector_store.similarity_search_with_score_by_vector(motorbike_emb, k=3)"
]
},
{
"cell_type": "markdown",
"id": "4b77be77",
"metadata": {},
"source": [
"## Search via docstore id"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "bbd971f0",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{0: '2d1498a8-a37c-4798-acb9-0016504ed798',\n",
" 1: '2d30aecc-88e0-4469-9d51-0ef7e9858e6d',\n",
" 2: '927f1120-985b-4691-b577-ad5cb42e011c',\n",
" 3: '3056ddcf-a62f-48c8-bd98-b9e57a3dfcae'}"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vector_store.index_to_docstore_id"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "6dbf3365",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Document(page_content='pizza is great', metadata={})"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"some_docstore_id = 0 # texts[0]\n",
"\n",
"vector_store.docstore._dict[vector_store.index_to_docstore_id[some_docstore_id]]"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "98b27172",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(Document(page_content='pizza is great', metadata={}), 0.0),\n",
" (Document(page_content='I love salad', metadata={}), 1.0734446048736572),\n",
" (Document(page_content='my car', metadata={}), 1.2895267009735107)]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# same document has distance 0\n",
"vector_store.similarity_search_with_score_by_index(some_docstore_id, k=3)"
]
},
{
"cell_type": "markdown",
"id": "6f570f69",
"metadata": {},
"source": [
"## Save and load"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "ef91cc69",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"saving config\n"
]
}
],
"source": [
"vector_store.save_local(\"my_annoy_index_and_docstore\")"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "7a9d2fce",
"metadata": {},
"outputs": [],
"source": [
"loaded_vector_store = Annoy.load_local(\n",
" \"my_annoy_index_and_docstore\", embeddings=embeddings_func\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "bba77cae",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(Document(page_content='pizza is great', metadata={}), 0.0),\n",
" (Document(page_content='I love salad', metadata={}), 1.0734446048736572),\n",
" (Document(page_content='my car', metadata={}), 1.2895267009735107)]"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# same document has distance 0\n",
"loaded_vector_store.similarity_search_with_score_by_index(some_docstore_id, k=3)"
]
},
{
"cell_type": "markdown",
"id": "df4beb83",
"metadata": {},
"source": [
"## Construct from scratch"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "26fcf742",
"metadata": {},
"outputs": [],
"source": [
"import uuid\n",
"from annoy import AnnoyIndex\n",
"from langchain.docstore.document import Document\n",
"from langchain.docstore.in_memory import InMemoryDocstore\n",
"\n",
"metadatas = [{\"x\": \"food\"}, {\"x\": \"food\"}, {\"x\": \"stuff\"}, {\"x\": \"animal\"}]\n",
"\n",
"# embeddings\n",
"embeddings = embeddings_func.embed_documents(texts)\n",
"\n",
"# embedding dim\n",
"f = len(embeddings[0])\n",
"\n",
"# index\n",
"metric = \"angular\"\n",
"index = AnnoyIndex(f, metric=metric)\n",
"for i, emb in enumerate(embeddings):\n",
" index.add_item(i, emb)\n",
"index.build(10)\n",
"\n",
"# docstore\n",
"documents = []\n",
"for i, text in enumerate(texts):\n",
" metadata = metadatas[i] if metadatas else {}\n",
" documents.append(Document(page_content=text, metadata=metadata))\n",
"index_to_docstore_id = {i: str(uuid.uuid4()) for i in range(len(documents))}\n",
"docstore = InMemoryDocstore(\n",
" {index_to_docstore_id[i]: doc for i, doc in enumerate(documents)}\n",
")\n",
"\n",
"db_manually = Annoy(\n",
" embeddings_func.embed_query, index, metric, docstore, index_to_docstore_id\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "2b3f6f5c",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(Document(page_content='pizza is great', metadata={'x': 'food'}),\n",
" 1.1314140558242798),\n",
" (Document(page_content='I love salad', metadata={'x': 'food'}),\n",
" 1.1668788194656372),\n",
" (Document(page_content='my car', metadata={'x': 'stuff'}), 1.226445198059082)]"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"db_manually.similarity_search_with_score(\"eating!\", k=3)"
]
}
],
"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.10.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|