Spaces:
Running
Running
File size: 81,967 Bytes
bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf 022d1be bb9c2bf |
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 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "405bc169-e0b7-48e6-84b8-4e4a791cf61a",
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 06-07 22:36:36 [__init__.py:243] Automatically detected platform cuda.\n",
"INFO 06-07 22:36:40 [__init__.py:31] Available plugins for group vllm.general_plugins:\n",
"INFO 06-07 22:36:40 [__init__.py:33] - lora_filesystem_resolver -> vllm.plugins.lora_resolvers.filesystem_resolver:register_filesystem_resolver\n",
"INFO 06-07 22:36:40 [__init__.py:36] All plugins in this group will be loaded. Set `VLLM_PLUGINS` to control which plugins to load.\n",
"INFO 06-07 22:36:41 [api_server.py:1289] vLLM API server version 0.9.0.1\n",
"INFO 06-07 22:36:41 [cli_args.py:300] non-default args: {'host': '0.0.0.0', 'task': 'embed', 'trust_remote_code': True, 'enforce_eager': True, 'served_model_name': ['local'], 'tensor_parallel_size': 2, 'gpu_memory_utilization': 0.4}\n",
"WARNING 06-07 22:36:43 [config.py:3096] Your Quadro RTX 8000 device (with compute capability 7.5) doesn't support torch.bfloat16. Falling back to torch.float16 for compatibility.\n",
"WARNING 06-07 22:36:43 [config.py:3135] Casting torch.bfloat16 to torch.float16.\n",
"INFO 06-07 22:36:51 [config.py:473] Found sentence-transformers modules configuration.\n",
"INFO 06-07 22:36:52 [config.py:493] Found pooling configuration.\n",
"WARNING 06-07 22:36:52 [arg_utils.py:1583] Compute Capability < 8.0 is not supported by the V1 Engine. Falling back to V0. \n",
"WARNING 06-07 22:36:52 [arg_utils.py:1431] The model has a long context length (40960). This may causeOOM during the initial memory profiling phase, or result in low performance due to small KV cache size. Consider setting --max-model-len to a smaller value.\n",
"INFO 06-07 22:36:52 [config.py:1875] Defaulting to use mp for distributed inference\n",
"WARNING 06-07 22:36:52 [cuda.py:87] To see benefits of async output processing, enable CUDA graph. Since, enforce-eager is enabled, async output processor cannot be used\n",
"INFO 06-07 22:36:52 [api_server.py:257] Started engine process with PID 16420\n",
"INFO 06-07 22:36:56 [__init__.py:243] Automatically detected platform cuda.\n",
"INFO 06-07 22:36:59 [__init__.py:31] Available plugins for group vllm.general_plugins:\n",
"INFO 06-07 22:36:59 [__init__.py:33] - lora_filesystem_resolver -> vllm.plugins.lora_resolvers.filesystem_resolver:register_filesystem_resolver\n",
"INFO 06-07 22:36:59 [__init__.py:36] All plugins in this group will be loaded. Set `VLLM_PLUGINS` to control which plugins to load.\n",
"INFO 06-07 22:36:59 [llm_engine.py:230] Initializing a V0 LLM engine (v0.9.0.1) with config: model='Qwen/Qwen3-Embedding-4B', speculative_config=None, tokenizer='Qwen/Qwen3-Embedding-4B', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config={}, tokenizer_revision=None, trust_remote_code=True, dtype=torch.float16, max_seq_len=40960, download_dir=None, load_format=LoadFormat.AUTO, tensor_parallel_size=2, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=True, kv_cache_dtype=auto, device_config=cuda, decoding_config=DecodingConfig(backend='auto', disable_fallback=False, disable_any_whitespace=False, disable_additional_properties=False, reasoning_backend=''), observability_config=ObservabilityConfig(show_hidden_metrics_for_version=None, otlp_traces_endpoint=None, collect_detailed_traces=None), seed=0, served_model_name=local, num_scheduler_steps=1, multi_step_stream_outputs=True, enable_prefix_caching=None, chunked_prefill_enabled=False, use_async_output_proc=False, pooler_config=PoolerConfig(pooling_type='LAST', normalize=True, softmax=None, step_tag_id=None, returned_token_ids=None), compilation_config={\"compile_sizes\": [], \"inductor_compile_config\": {\"enable_auto_functionalized_v2\": false}, \"cudagraph_capture_sizes\": [], \"max_capture_size\": 0}, use_cached_outputs=True, \n",
"WARNING 06-07 22:37:00 [multiproc_worker_utils.py:306] Reducing Torch parallelism from 64 threads to 1 to avoid unnecessary CPU contention. Set OMP_NUM_THREADS in the external environment to tune this value as needed.\n",
"INFO 06-07 22:37:00 [cuda.py:240] Cannot use FlashAttention-2 backend for Volta and Turing GPUs.\n",
"INFO 06-07 22:37:00 [cuda.py:289] Using XFormers backend.\n",
"INFO 06-07 22:37:04 [__init__.py:243] Automatically detected platform cuda.\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:07 [multiproc_worker_utils.py:225] Worker ready; awaiting tasks\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:07 [__init__.py:31] Available plugins for group vllm.general_plugins:\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:07 [__init__.py:33] - lora_filesystem_resolver -> vllm.plugins.lora_resolvers.filesystem_resolver:register_filesystem_resolver\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:07 [__init__.py:36] All plugins in this group will be loaded. Set `VLLM_PLUGINS` to control which plugins to load.\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:07 [cuda.py:240] Cannot use FlashAttention-2 backend for Volta and Turing GPUs.\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:07 [cuda.py:289] Using XFormers backend.\n",
"INFO 06-07 22:37:08 [utils.py:1077] Found nccl from library libnccl.so.2\n",
"INFO 06-07 22:37:08 [pynccl.py:69] vLLM is using nccl==2.26.2\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:08 [utils.py:1077] Found nccl from library libnccl.so.2\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:08 [pynccl.py:69] vLLM is using nccl==2.26.2\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:09 [custom_all_reduce_utils.py:245] reading GPU P2P access cache from /home/jovyan/.cache/vllm/gpu_p2p_access_cache_for_0,1.json\n",
"INFO 06-07 22:37:09 [custom_all_reduce_utils.py:245] reading GPU P2P access cache from /home/jovyan/.cache/vllm/gpu_p2p_access_cache_for_0,1.json\n",
"WARNING 06-07 22:37:09 [custom_all_reduce.py:146] Custom allreduce is disabled because your platform lacks GPU P2P capability or P2P test failed. To silence this warning, specify disable_custom_all_reduce=True explicitly.\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m WARNING 06-07 22:37:09 [custom_all_reduce.py:146] Custom allreduce is disabled because your platform lacks GPU P2P capability or P2P test failed. To silence this warning, specify disable_custom_all_reduce=True explicitly.\n",
"INFO 06-07 22:37:09 [shm_broadcast.py:250] vLLM message queue communication handle: Handle(local_reader_ranks=[1], buffer_handle=(1, 4194304, 6, 'psm_f9ac8311'), local_subscribe_addr='ipc:///tmp/718ad6af-61c7-4d9f-8044-b415ab240a60', remote_subscribe_addr=None, remote_addr_ipv6=False)\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:09 [parallel_state.py:1064] rank 1 in world size 2 is assigned as DP rank 0, PP rank 0, TP rank 1, EP rank 1\n",
"INFO 06-07 22:37:09 [parallel_state.py:1064] rank 0 in world size 2 is assigned as DP rank 0, PP rank 0, TP rank 0, EP rank 0\n",
"INFO 06-07 22:37:09 [model_runner.py:1170] Starting to load model Qwen/Qwen3-Embedding-4B...\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:09 [model_runner.py:1170] Starting to load model Qwen/Qwen3-Embedding-4B...\n",
"INFO 06-07 22:37:09 [weight_utils.py:291] Using model weights format ['*.safetensors']\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:37:09 [weight_utils.py:291] Using model weights format ['*.safetensors']\n",
"INFO 06-07 22:38:15 [weight_utils.py:307] Time spent downloading weights for Qwen/Qwen3-Embedding-4B: 65.320092 seconds\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Loading safetensors checkpoint shards: 0% Completed | 0/2 [00:00<?, ?it/s]\n",
"Loading safetensors checkpoint shards: 50% Completed | 1/2 [00:02<00:02, 2.96s/it]\n",
"Loading safetensors checkpoint shards: 100% Completed | 2/2 [00:09<00:00, 4.92s/it]\n",
"Loading safetensors checkpoint shards: 100% Completed | 2/2 [00:09<00:00, 4.63s/it]\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 06-07 22:38:24 [default_loader.py:280] Loading weights took 9.43 seconds\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:38:24 [default_loader.py:280] Loading weights took 9.14 seconds\n",
"INFO 06-07 22:38:24 [model_runner.py:1202] Model loading took 3.8162 GiB and 75.582441 seconds\n",
"\u001b[1;36m(VllmWorkerProcess pid=16602)\u001b[0;0m INFO 06-07 22:38:25 [model_runner.py:1202] Model loading took 3.8162 GiB and 75.610664 seconds\n",
"INFO 06-07 22:38:25 [api_server.py:1336] Starting vLLM API server on http://0.0.0.0:8000\n",
"INFO 06-07 22:38:25 [launcher.py:28] Available routes are:\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /openapi.json, Methods: GET, HEAD\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /docs, Methods: GET, HEAD\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /docs/oauth2-redirect, Methods: GET, HEAD\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /redoc, Methods: GET, HEAD\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /health, Methods: GET\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /load, Methods: GET\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /ping, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /ping, Methods: GET\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /tokenize, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /detokenize, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /v1/models, Methods: GET\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /version, Methods: GET\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /v1/chat/completions, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /v1/completions, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /v1/embeddings, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /pooling, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /classify, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /score, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /v1/score, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /v1/audio/transcriptions, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /rerank, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /v1/rerank, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /v2/rerank, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /invocations, Methods: POST\n",
"INFO 06-07 22:38:25 [launcher.py:36] Route: /metrics, Methods: GET\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO: Started server process [16093]\n",
"INFO: Waiting for application startup.\n",
"INFO: Application startup complete.\n"
]
}
],
"source": [
"import os\n",
"import subprocess\n",
"import threading\n",
"import time\n",
"\n",
"# Set environment variable we need to support dual-GPU on Cirrus\n",
"os.environ[\"NCCL_P2P_LEVEL\"] = \"NVL\"\n",
"os.environ[\"VLLM_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\") # set same key for simplicity\n",
"\n",
"# https://huggingface.co/spaces/mteb/leaderboard \n",
"def run_vllm_server():\n",
" subprocess.run([\n",
" \"vllm\", \"serve\", \"Qwen/Qwen3-Embedding-4B\",\n",
" \"--host\", \"0.0.0.0\",\n",
" \"--port\", \"8000\",\n",
" \"--tensor-parallel-size\", \"2\",\n",
" \"--trust-remote-code\",\n",
" \"--gpu-memory-utilization\", \"0.4\",\n",
" \"--enforce-eager\",\n",
" \"--served-model-name\", \"local\",\n",
" \"--task\", \"embed\" # Run in embed mode! (default is 'generate')\n",
" ])\n",
"\n",
"# Start server in daemon thread\n",
"server_thread = threading.Thread(target=run_vllm_server, daemon=True)\n",
"server_thread.start()\n",
"\n",
"## give server time to start up:\n",
"import time\n",
"# Pause execution for 100 seconds\n",
"time.sleep(200)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9a8397fa-6896-40a5-97d9-1d0c98797b35",
"metadata": {},
"outputs": [],
"source": [
"## wait for output above to print routes, ending with: \n",
"## INFO: Application startup complete.\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "24b64902-1305-43e7-9da8-e4d82d097cb5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 06-07 22:39:51 [logger.py:42] Received request embd-9059fd2aadf84d8288c45ca3ecc8cd3c-0: prompt: ' product down', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [1985, 1495], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 22:39:51 [engine.py:316] Added request embd-9059fd2aadf84d8288c45ca3ecc8cd3c-0.\n",
"INFO 06-07 22:39:53 [metrics.py:486] Avg prompt throughput: 0.2 tokens/s, Avg generation throughput: 0.1 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.\n",
"INFO: 127.0.0.1:36040 - \"POST /v1/embeddings HTTP/1.1\" 200 OK\n",
"INFO 06-07 22:40:03 [metrics.py:486] Avg prompt throughput: 0.0 tokens/s, Avg generation throughput: 0.0 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.\n"
]
}
],
"source": [
"## NOTE! You must wait until the log above finishes and not just the cell.\n",
"## Connect to the local model\n",
"from langchain_openai import OpenAIEmbeddings\n",
"embedding = OpenAIEmbeddings(\n",
" model = \"local\", ## served model name\n",
" api_key = os.getenv(\"OPENAI_API_KEY\"),\n",
" base_url = \"http://localhost:8000/v1\",\n",
")\n",
"\n",
"## test that the model can do embeddings\n",
"from langchain_core.vectorstores import InMemoryVectorStore\n",
"vectorstore = InMemoryVectorStore.from_texts([\"test text\"], embedding=embedding)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "6181a644-e419-4986-a900-44f1d569d244",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 06-07 23:16:55 [logger.py:42] Received request embd-60cc555da14743da90337ba88edfe7cf-0: prompt: ' Stainless\">\\r\\n', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [32490, 4424], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:16:55 [engine.py:316] Added request embd-60cc555da14743da90337ba88edfe7cf-0.\n",
"INFO: 127.0.0.1:53594 - \"POST /v1/embeddings HTTP/1.1\" 200 OK\n",
"INFO 06-07 23:17:05 [metrics.py:486] Avg prompt throughput: 0.1 tokens/s, Avg generation throughput: 0.1 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.\n",
"INFO 06-07 23:17:15 [metrics.py:486] Avg prompt throughput: 0.0 tokens/s, Avg generation throughput: 0.0 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.\n"
]
}
],
"source": [
"from langchain_qdrant import QdrantVectorStore\n",
"from qdrant_client import QdrantClient\n",
"from qdrant_client.http.models import Distance, VectorParams\n",
"\n",
"client = QdrantClient(path = \"hwc_qdrant.db\")\n",
"\n",
"client.create_collection(\n",
" collection_name=\"demo_collection\",\n",
" vectors_config=VectorParams(size=2560, distance=Distance.COSINE),\n",
")\n",
"\n",
"vector_store = QdrantVectorStore(\n",
" client=client,\n",
" collection_name=\"demo_collection\",\n",
" embedding=embedding\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "ec8d7936-d6b9-4487-9146-c42f855523ec",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-0: prompt: 'Iys landscape SL defends and-fired Philadelphia for Utils wh whose.', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [40, 1047, 18414, 16797, 80960, 323, 71578, 19335, 369, 17954, 420, 6693, 13], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-1: prompt: 'eg observ.price for guitar is=! andshional,iz aik of deep(long\\\\Category.', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [791, 9282, 18057, 369, 16986, 374, 74649, 323, 927, 3914, 11, 449, 264, 1579, 315, 220, 5538, 12628, 69823, 13], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-2: prompt: '.setPropertyata dram j.Iiz��shareine *) eachessso!', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [31233, 459, 13548, 502, 2447, 449, 23272, 19368, 482, 2586, 1817, 433, 704, 0], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-3: prompt: ' Wasook.offset_T the means());\\r\\n and.after $1 +\\n in Alex.', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [14804, 1941, 14760, 1139, 279, 3363, 6201, 323, 40606, 400, 16, 3610, 304, 8515, 13], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-4: prompt: ' Traffic! });\\n\\nthisata station=[. Iprra games to================ess ed.', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [36981, 0, 3011, 574, 459, 8056, 5818, 13, 358, 649, 956, 3868, 311, 1518, 433, 1578, 13], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-5: prompt: '.Control the jPairutable theBe?\\t\\t\\t\\n whReg to (!so.', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [3957, 279, 502, 12443, 5922, 279, 3430, 30, 4557, 420, 3477, 311, 1505, 704, 13], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-6: prompt: 'eg between ==== Marine City in the actionutil][.', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [791, 1948, 220, 605, 22963, 4311, 304, 279, 1917, 1314, 1457, 13], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-7: prompt: ' parad Bad is theideo JavaScript for(key modelRO,ault-group Russian!', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [27317, 11461, 374, 279, 1888, 12914, 369, 4857, 1614, 1285, 11, 945, 4351, 8522, 0], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-8: prompt: 'eg sysyear is_h ehAGE having.io toReceiveMemoryWarning of a strangers.', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [791, 5708, 3157, 374, 1523, 220, 2636, 3585, 3432, 4245, 311, 24087, 315, 264, 39621, 13], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [logger.py:42] Received request embd-d18cf8a824104f36a07c970cfa3e999f-9: prompt: 'Iull a éSec Irefoute to �Touchacency', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [40, 617, 264, 3958, 8430, 358, 1097, 2133, 311, 636, 11309, 40624], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-0.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-1.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-2.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-3.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-4.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-5.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-6.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-7.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-8.\n",
"INFO 06-07 23:19:58 [engine.py:316] Added request embd-d18cf8a824104f36a07c970cfa3e999f-9.\n",
"INFO: 127.0.0.1:35840 - \"POST /v1/embeddings HTTP/1.1\" 200 OK\n"
]
},
{
"data": {
"text/plain": [
"['878ac59d-e276-4d29-b715-6b20cd0f76f8',\n",
" '5e5c960e-7c02-446d-9ad4-ca930ec3b57a',\n",
" '8f478874-a730-4e19-b5f2-ef3caeb96a9d',\n",
" 'ed8dd908-a4da-4b20-b3d3-b2778846298d',\n",
" 'cc487e15-f7f3-46b6-a0a4-d0be9955cdaa',\n",
" '5f380da0-9b78-4051-beea-6aa98421df33',\n",
" 'd5fa20d1-cc94-4613-ac64-b5ba3830589c',\n",
" 'cb0cbe18-5118-45f6-ae9c-1452b43cb92e',\n",
" '15181e21-fa5d-45d0-b97b-3e206d671101',\n",
" '1e769b7d-d327-465e-9b5b-3274b159ede3']"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 06-07 23:20:08 [metrics.py:486] Avg prompt throughput: 12.1 tokens/s, Avg generation throughput: 0.8 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.\n",
"INFO 06-07 23:20:19 [metrics.py:486] Avg prompt throughput: 0.0 tokens/s, Avg generation throughput: 0.0 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.\n"
]
}
],
"source": [
"from uuid import uuid4\n",
"\n",
"from langchain_core.documents import Document\n",
"\n",
"document_1 = Document(\n",
" page_content=\"I had chocolate chip pancakes and scrambled eggs for breakfast this morning.\",\n",
" metadata={\"source\": \"tweet\"},\n",
")\n",
"\n",
"document_2 = Document(\n",
" page_content=\"The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees Fahrenheit.\",\n",
" metadata={\"source\": \"news\"},\n",
")\n",
"\n",
"document_3 = Document(\n",
" page_content=\"Building an exciting new project with LangChain - come check it out!\",\n",
" metadata={\"source\": \"tweet\"},\n",
")\n",
"\n",
"document_4 = Document(\n",
" page_content=\"Robbers broke into the city bank and stole $1 million in cash.\",\n",
" metadata={\"source\": \"news\"},\n",
")\n",
"\n",
"document_5 = Document(\n",
" page_content=\"Wow! That was an amazing movie. I can't wait to see it again.\",\n",
" metadata={\"source\": \"tweet\"},\n",
")\n",
"\n",
"document_6 = Document(\n",
" page_content=\"Is the new iPhone worth the price? Read this review to find out.\",\n",
" metadata={\"source\": \"website\"},\n",
")\n",
"\n",
"document_7 = Document(\n",
" page_content=\"The top 10 soccer players in the world right now.\",\n",
" metadata={\"source\": \"website\"},\n",
")\n",
"\n",
"document_8 = Document(\n",
" page_content=\"LangGraph is the best framework for building stateful, agentic applications!\",\n",
" metadata={\"source\": \"tweet\"},\n",
")\n",
"\n",
"document_9 = Document(\n",
" page_content=\"The stock market is down 500 points today due to fears of a recession.\",\n",
" metadata={\"source\": \"news\"},\n",
")\n",
"\n",
"document_10 = Document(\n",
" page_content=\"I have a bad feeling I am going to get deleted :(\",\n",
" metadata={\"source\": \"tweet\"},\n",
")\n",
"\n",
"documents = [\n",
" document_1,\n",
" document_2,\n",
" document_3,\n",
" document_4,\n",
" document_5,\n",
" document_6,\n",
" document_7,\n",
" document_8,\n",
" document_9,\n",
" document_10,\n",
"]\n",
"uuids = [str(uuid4()) for _ in range(len(documents))]\n",
"vector_store.add_documents(documents=documents, ids=uuids)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "95ed10f3-5339-40cd-bf16-b0854f8b4b91",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import requests\n",
"import zipfile\n",
"import pathlib\n",
"from langchain_community.document_loaders import PyPDFLoader\n",
"\n",
"def download_and_unzip(url, output_dir):\n",
" response = requests.get(url)\n",
" zip_file_path = os.path.basename(url)\n",
" with open(zip_file_path, 'wb') as f:\n",
" f.write(response.content)\n",
" with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n",
" zip_ref.extractall(output_dir)\n",
" os.remove(zip_file_path)\n",
"\n",
"def pdf_loader(path):\n",
" all_documents = []\n",
" docs_dir = pathlib.Path(path)\n",
" for file in docs_dir.iterdir():\n",
" loader = PyPDFLoader(file)\n",
" documents = loader.load()\n",
" all_documents.extend(documents)\n",
" return all_documents\n",
"\n",
"\n",
"download_and_unzip(\"https://minio.carlboettiger.info/public-data/hwc.zip\", 'hwc')\n",
"docs = pdf_loader('hwc/')"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "95d3e9a3-7334-44ba-a4bc-e7bfc4076358",
"metadata": {},
"outputs": [],
"source": [
"# Build a retrival agent\n",
"from langchain_core.vectorstores import InMemoryVectorStore\n",
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
"text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
"splits = text_splitter.split_documents(docs)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "fd8bcc13-d06d-43dd-9e06-4f29da803133",
"metadata": {
"scrolled": true
},
"outputs": [
{
"ename": "ResponseHandlingException",
"evalue": "[Errno 111] Connection refused",
"output_type": "error",
"traceback": [
"\u001b[31m---------------------------------------------------------------------------\u001b[39m",
"\u001b[31mConnectError\u001b[39m Traceback (most recent call last)",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpx/_transports/default.py:101\u001b[39m, in \u001b[36mmap_httpcore_exceptions\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m 100\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m101\u001b[39m \u001b[38;5;28;01myield\u001b[39;00m\n\u001b[32m 102\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m exc:\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpx/_transports/default.py:250\u001b[39m, in \u001b[36mHTTPTransport.handle_request\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 249\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m map_httpcore_exceptions():\n\u001b[32m--> \u001b[39m\u001b[32m250\u001b[39m resp = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_pool\u001b[49m\u001b[43m.\u001b[49m\u001b[43mhandle_request\u001b[49m\u001b[43m(\u001b[49m\u001b[43mreq\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 252\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(resp.stream, typing.Iterable)\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpcore/_sync/connection_pool.py:256\u001b[39m, in \u001b[36mConnectionPool.handle_request\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 255\u001b[39m \u001b[38;5;28mself\u001b[39m._close_connections(closing)\n\u001b[32m--> \u001b[39m\u001b[32m256\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m exc \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[32m 258\u001b[39m \u001b[38;5;66;03m# Return the response. Note that in this case we still have to manage\u001b[39;00m\n\u001b[32m 259\u001b[39m \u001b[38;5;66;03m# the point at which the response is closed.\u001b[39;00m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpcore/_sync/connection_pool.py:236\u001b[39m, in \u001b[36mConnectionPool.handle_request\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 234\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m 235\u001b[39m \u001b[38;5;66;03m# Send the request on the assigned connection.\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m236\u001b[39m response = \u001b[43mconnection\u001b[49m\u001b[43m.\u001b[49m\u001b[43mhandle_request\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 237\u001b[39m \u001b[43m \u001b[49m\u001b[43mpool_request\u001b[49m\u001b[43m.\u001b[49m\u001b[43mrequest\u001b[49m\n\u001b[32m 238\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 239\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m ConnectionNotAvailable:\n\u001b[32m 240\u001b[39m \u001b[38;5;66;03m# In some cases a connection may initially be available to\u001b[39;00m\n\u001b[32m 241\u001b[39m \u001b[38;5;66;03m# handle a request, but then become unavailable.\u001b[39;00m\n\u001b[32m 242\u001b[39m \u001b[38;5;66;03m#\u001b[39;00m\n\u001b[32m 243\u001b[39m \u001b[38;5;66;03m# In this case we clear the connection and try again.\u001b[39;00m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpcore/_sync/connection.py:101\u001b[39m, in \u001b[36mHTTPConnection.handle_request\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 100\u001b[39m \u001b[38;5;28mself\u001b[39m._connect_failed = \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m101\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m exc\n\u001b[32m 103\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m._connection.handle_request(request)\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpcore/_sync/connection.py:78\u001b[39m, in \u001b[36mHTTPConnection.handle_request\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 77\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._connection \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[32m---> \u001b[39m\u001b[32m78\u001b[39m stream = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_connect\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 80\u001b[39m ssl_object = stream.get_extra_info(\u001b[33m\"\u001b[39m\u001b[33mssl_object\u001b[39m\u001b[33m\"\u001b[39m)\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpcore/_sync/connection.py:124\u001b[39m, in \u001b[36mHTTPConnection._connect\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 123\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m Trace(\u001b[33m\"\u001b[39m\u001b[33mconnect_tcp\u001b[39m\u001b[33m\"\u001b[39m, logger, request, kwargs) \u001b[38;5;28;01mas\u001b[39;00m trace:\n\u001b[32m--> \u001b[39m\u001b[32m124\u001b[39m stream = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_network_backend\u001b[49m\u001b[43m.\u001b[49m\u001b[43mconnect_tcp\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 125\u001b[39m trace.return_value = stream\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpcore/_backends/sync.py:207\u001b[39m, in \u001b[36mSyncBackend.connect_tcp\u001b[39m\u001b[34m(self, host, port, timeout, local_address, socket_options)\u001b[39m\n\u001b[32m 202\u001b[39m exc_map: ExceptionMapping = {\n\u001b[32m 203\u001b[39m socket.timeout: ConnectTimeout,\n\u001b[32m 204\u001b[39m \u001b[38;5;167;01mOSError\u001b[39;00m: ConnectError,\n\u001b[32m 205\u001b[39m }\n\u001b[32m--> \u001b[39m\u001b[32m207\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m map_exceptions(exc_map):\n\u001b[32m 208\u001b[39m sock = socket.create_connection(\n\u001b[32m 209\u001b[39m address,\n\u001b[32m 210\u001b[39m timeout,\n\u001b[32m 211\u001b[39m source_address=source_address,\n\u001b[32m 212\u001b[39m )\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/contextlib.py:158\u001b[39m, in \u001b[36m_GeneratorContextManager.__exit__\u001b[39m\u001b[34m(self, typ, value, traceback)\u001b[39m\n\u001b[32m 157\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m158\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mgen\u001b[49m\u001b[43m.\u001b[49m\u001b[43mthrow\u001b[49m\u001b[43m(\u001b[49m\u001b[43mvalue\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 159\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mStopIteration\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m exc:\n\u001b[32m 160\u001b[39m \u001b[38;5;66;03m# Suppress StopIteration *unless* it's the same exception that\u001b[39;00m\n\u001b[32m 161\u001b[39m \u001b[38;5;66;03m# was passed to throw(). This prevents a StopIteration\u001b[39;00m\n\u001b[32m 162\u001b[39m \u001b[38;5;66;03m# raised inside the \"with\" statement from being suppressed.\u001b[39;00m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpcore/_exceptions.py:14\u001b[39m, in \u001b[36mmap_exceptions\u001b[39m\u001b[34m(map)\u001b[39m\n\u001b[32m 13\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(exc, from_exc):\n\u001b[32m---> \u001b[39m\u001b[32m14\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m to_exc(exc) \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mexc\u001b[39;00m\n\u001b[32m 15\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m\n",
"\u001b[31mConnectError\u001b[39m: [Errno 111] Connection refused",
"\nThe above exception was the direct cause of the following exception:\n",
"\u001b[31mConnectError\u001b[39m Traceback (most recent call last)",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/http/api_client.py:129\u001b[39m, in \u001b[36mApiClient.send_inner\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 128\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m129\u001b[39m response = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_client\u001b[49m\u001b[43m.\u001b[49m\u001b[43msend\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 130\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpx/_client.py:914\u001b[39m, in \u001b[36mClient.send\u001b[39m\u001b[34m(self, request, stream, auth, follow_redirects)\u001b[39m\n\u001b[32m 912\u001b[39m auth = \u001b[38;5;28mself\u001b[39m._build_request_auth(request, auth)\n\u001b[32m--> \u001b[39m\u001b[32m914\u001b[39m response = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_send_handling_auth\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 915\u001b[39m \u001b[43m \u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 916\u001b[39m \u001b[43m \u001b[49m\u001b[43mauth\u001b[49m\u001b[43m=\u001b[49m\u001b[43mauth\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 917\u001b[39m \u001b[43m \u001b[49m\u001b[43mfollow_redirects\u001b[49m\u001b[43m=\u001b[49m\u001b[43mfollow_redirects\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 918\u001b[39m \u001b[43m \u001b[49m\u001b[43mhistory\u001b[49m\u001b[43m=\u001b[49m\u001b[43m[\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 919\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 920\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpx/_client.py:942\u001b[39m, in \u001b[36mClient._send_handling_auth\u001b[39m\u001b[34m(self, request, auth, follow_redirects, history)\u001b[39m\n\u001b[32m 941\u001b[39m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;28;01mTrue\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m942\u001b[39m response = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_send_handling_redirects\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 943\u001b[39m \u001b[43m \u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 944\u001b[39m \u001b[43m \u001b[49m\u001b[43mfollow_redirects\u001b[49m\u001b[43m=\u001b[49m\u001b[43mfollow_redirects\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 945\u001b[39m \u001b[43m \u001b[49m\u001b[43mhistory\u001b[49m\u001b[43m=\u001b[49m\u001b[43mhistory\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 946\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 947\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpx/_client.py:979\u001b[39m, in \u001b[36mClient._send_handling_redirects\u001b[39m\u001b[34m(self, request, follow_redirects, history)\u001b[39m\n\u001b[32m 977\u001b[39m hook(request)\n\u001b[32m--> \u001b[39m\u001b[32m979\u001b[39m response = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_send_single_request\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 980\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpx/_client.py:1014\u001b[39m, in \u001b[36mClient._send_single_request\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 1013\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m request_context(request=request):\n\u001b[32m-> \u001b[39m\u001b[32m1014\u001b[39m response = \u001b[43mtransport\u001b[49m\u001b[43m.\u001b[49m\u001b[43mhandle_request\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1016\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(response.stream, SyncByteStream)\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpx/_transports/default.py:249\u001b[39m, in \u001b[36mHTTPTransport.handle_request\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 237\u001b[39m req = httpcore.Request(\n\u001b[32m 238\u001b[39m method=request.method,\n\u001b[32m 239\u001b[39m url=httpcore.URL(\n\u001b[32m (...)\u001b[39m\u001b[32m 247\u001b[39m extensions=request.extensions,\n\u001b[32m 248\u001b[39m )\n\u001b[32m--> \u001b[39m\u001b[32m249\u001b[39m \u001b[38;5;28;01mwith\u001b[39;00m map_httpcore_exceptions():\n\u001b[32m 250\u001b[39m resp = \u001b[38;5;28mself\u001b[39m._pool.handle_request(req)\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/contextlib.py:158\u001b[39m, in \u001b[36m_GeneratorContextManager.__exit__\u001b[39m\u001b[34m(self, typ, value, traceback)\u001b[39m\n\u001b[32m 157\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m158\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mgen\u001b[49m\u001b[43m.\u001b[49m\u001b[43mthrow\u001b[49m\u001b[43m(\u001b[49m\u001b[43mvalue\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 159\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mStopIteration\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m exc:\n\u001b[32m 160\u001b[39m \u001b[38;5;66;03m# Suppress StopIteration *unless* it's the same exception that\u001b[39;00m\n\u001b[32m 161\u001b[39m \u001b[38;5;66;03m# was passed to throw(). This prevents a StopIteration\u001b[39;00m\n\u001b[32m 162\u001b[39m \u001b[38;5;66;03m# raised inside the \"with\" statement from being suppressed.\u001b[39;00m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/httpx/_transports/default.py:118\u001b[39m, in \u001b[36mmap_httpcore_exceptions\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m 117\u001b[39m message = \u001b[38;5;28mstr\u001b[39m(exc)\n\u001b[32m--> \u001b[39m\u001b[32m118\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m mapped_exc(message) \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34;01mexc\u001b[39;00m\n",
"\u001b[31mConnectError\u001b[39m: [Errno 111] Connection refused",
"\nDuring handling of the above exception, another exception occurred:\n",
"\u001b[31mResponseHandlingException\u001b[39m Traceback (most recent call last)",
"\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[27]\u001b[39m\u001b[32m, line 2\u001b[39m\n\u001b[32m 1\u001b[39m \u001b[38;5;66;03m# slow part here, runs on remote GPU\u001b[39;00m\n\u001b[32m----> \u001b[39m\u001b[32m2\u001b[39m vectorstore = \u001b[43mvector_store\u001b[49m\u001b[43m.\u001b[49m\u001b[43mfrom_documents\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdocuments\u001b[49m\u001b[43m=\u001b[49m\u001b[43msplits\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43membedding\u001b[49m\u001b[43m \u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[43membedding\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 3\u001b[39m retriever = vectorstore.as_retriever()\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/langchain_core/vectorstores/base.py:848\u001b[39m, in \u001b[36mVectorStore.from_documents\u001b[39m\u001b[34m(cls, documents, embedding, **kwargs)\u001b[39m\n\u001b[32m 845\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28many\u001b[39m(ids):\n\u001b[32m 846\u001b[39m kwargs[\u001b[33m\"\u001b[39m\u001b[33mids\u001b[39m\u001b[33m\"\u001b[39m] = ids\n\u001b[32m--> \u001b[39m\u001b[32m848\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mfrom_texts\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtexts\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43membedding\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmetadatas\u001b[49m\u001b[43m=\u001b[49m\u001b[43mmetadatas\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/langchain_qdrant/qdrant.py:343\u001b[39m, in \u001b[36mQdrantVectorStore.from_texts\u001b[39m\u001b[34m(cls, texts, embedding, metadatas, ids, collection_name, location, url, port, grpc_port, prefer_grpc, https, api_key, prefix, timeout, host, path, distance, content_payload_key, metadata_payload_key, vector_name, retrieval_mode, sparse_embedding, sparse_vector_name, collection_create_options, vector_params, sparse_vector_params, batch_size, force_recreate, validate_embeddings, validate_collection_config, **kwargs)\u001b[39m\n\u001b[32m 311\u001b[39m \u001b[38;5;250m\u001b[39m\u001b[33;03m\"\"\"Construct an instance of `QdrantVectorStore` from a list of texts.\u001b[39;00m\n\u001b[32m 312\u001b[39m \n\u001b[32m 313\u001b[39m \u001b[33;03mThis is a user-friendly interface that:\u001b[39;00m\n\u001b[32m (...)\u001b[39m\u001b[32m 326\u001b[39m \u001b[33;03m qdrant = Qdrant.from_texts(texts, embeddings, url=\"http://localhost:6333\")\u001b[39;00m\n\u001b[32m 327\u001b[39m \u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m 328\u001b[39m client_options = {\n\u001b[32m 329\u001b[39m \u001b[33m\"\u001b[39m\u001b[33mlocation\u001b[39m\u001b[33m\"\u001b[39m: location,\n\u001b[32m 330\u001b[39m \u001b[33m\"\u001b[39m\u001b[33murl\u001b[39m\u001b[33m\"\u001b[39m: url,\n\u001b[32m (...)\u001b[39m\u001b[32m 340\u001b[39m **kwargs,\n\u001b[32m 341\u001b[39m }\n\u001b[32m--> \u001b[39m\u001b[32m343\u001b[39m qdrant = \u001b[38;5;28;43mcls\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mconstruct_instance\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 344\u001b[39m \u001b[43m \u001b[49m\u001b[43membedding\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 345\u001b[39m \u001b[43m \u001b[49m\u001b[43mretrieval_mode\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 346\u001b[39m \u001b[43m \u001b[49m\u001b[43msparse_embedding\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 347\u001b[39m \u001b[43m \u001b[49m\u001b[43mclient_options\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 348\u001b[39m \u001b[43m \u001b[49m\u001b[43mcollection_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 349\u001b[39m \u001b[43m \u001b[49m\u001b[43mdistance\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 350\u001b[39m \u001b[43m \u001b[49m\u001b[43mcontent_payload_key\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 351\u001b[39m \u001b[43m \u001b[49m\u001b[43mmetadata_payload_key\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 352\u001b[39m \u001b[43m \u001b[49m\u001b[43mvector_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 353\u001b[39m \u001b[43m \u001b[49m\u001b[43msparse_vector_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 354\u001b[39m \u001b[43m \u001b[49m\u001b[43mforce_recreate\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 355\u001b[39m \u001b[43m \u001b[49m\u001b[43mcollection_create_options\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 356\u001b[39m \u001b[43m \u001b[49m\u001b[43mvector_params\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 357\u001b[39m \u001b[43m \u001b[49m\u001b[43msparse_vector_params\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 358\u001b[39m \u001b[43m \u001b[49m\u001b[43mvalidate_embeddings\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 359\u001b[39m \u001b[43m \u001b[49m\u001b[43mvalidate_collection_config\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 360\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 361\u001b[39m qdrant.add_texts(texts, metadatas, ids, batch_size)\n\u001b[32m 362\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m qdrant\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/langchain_qdrant/qdrant.py:810\u001b[39m, in \u001b[36mQdrantVectorStore.construct_instance\u001b[39m\u001b[34m(cls, embedding, retrieval_mode, sparse_embedding, client_options, collection_name, distance, content_payload_key, metadata_payload_key, vector_name, sparse_vector_name, force_recreate, collection_create_options, vector_params, sparse_vector_params, validate_embeddings, validate_collection_config)\u001b[39m\n\u001b[32m 807\u001b[39m collection_name = collection_name \u001b[38;5;129;01mor\u001b[39;00m uuid.uuid4().hex\n\u001b[32m 808\u001b[39m client = QdrantClient(**client_options)\n\u001b[32m--> \u001b[39m\u001b[32m810\u001b[39m collection_exists = \u001b[43mclient\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcollection_exists\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcollection_name\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 812\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m collection_exists \u001b[38;5;129;01mand\u001b[39;00m force_recreate:\n\u001b[32m 813\u001b[39m client.delete_collection(collection_name)\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/qdrant_client.py:2240\u001b[39m, in \u001b[36mQdrantClient.collection_exists\u001b[39m\u001b[34m(self, collection_name, **kwargs)\u001b[39m\n\u001b[32m 2230\u001b[39m \u001b[38;5;250m\u001b[39m\u001b[33;03m\"\"\"Check whether collection already exists\u001b[39;00m\n\u001b[32m 2231\u001b[39m \n\u001b[32m 2232\u001b[39m \u001b[33;03mArgs:\u001b[39;00m\n\u001b[32m (...)\u001b[39m\u001b[32m 2236\u001b[39m \u001b[33;03m True if collection exists, False if not\u001b[39;00m\n\u001b[32m 2237\u001b[39m \u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m 2238\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(kwargs) == \u001b[32m0\u001b[39m, \u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mUnknown arguments: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlist\u001b[39m(kwargs.keys())\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m\"\u001b[39m\n\u001b[32m-> \u001b[39m\u001b[32m2240\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_client\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcollection_exists\u001b[49m\u001b[43m(\u001b[49m\u001b[43mcollection_name\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcollection_name\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/qdrant_remote.py:2597\u001b[39m, in \u001b[36mQdrantRemote.collection_exists\u001b[39m\u001b[34m(self, collection_name, **kwargs)\u001b[39m\n\u001b[32m 2591\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._prefer_grpc:\n\u001b[32m 2592\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m.grpc_collections.CollectionExists(\n\u001b[32m 2593\u001b[39m grpc.CollectionExistsRequest(collection_name=collection_name),\n\u001b[32m 2594\u001b[39m timeout=\u001b[38;5;28mself\u001b[39m._timeout,\n\u001b[32m 2595\u001b[39m ).result.exists\n\u001b[32m-> \u001b[39m\u001b[32m2597\u001b[39m result: Optional[models.CollectionExistence] = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mhttp\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcollections_api\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcollection_exists\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 2598\u001b[39m \u001b[43m \u001b[49m\u001b[43mcollection_name\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcollection_name\u001b[49m\n\u001b[32m 2599\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m.result\n\u001b[32m 2600\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m result \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m, \u001b[33m\"\u001b[39m\u001b[33mCollection exists returned None\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 2601\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m result.exists\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/http/api/collections_api.py:281\u001b[39m, in \u001b[36mSyncCollectionsApi.collection_exists\u001b[39m\u001b[34m(self, collection_name)\u001b[39m\n\u001b[32m 274\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mcollection_exists\u001b[39m(\n\u001b[32m 275\u001b[39m \u001b[38;5;28mself\u001b[39m,\n\u001b[32m 276\u001b[39m collection_name: \u001b[38;5;28mstr\u001b[39m,\n\u001b[32m 277\u001b[39m ) -> m.InlineResponse2007:\n\u001b[32m 278\u001b[39m \u001b[38;5;250m \u001b[39m\u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m 279\u001b[39m \u001b[33;03m Returns \\\"true\\\" if the given collection name exists, and \\\"false\\\" otherwise\u001b[39;00m\n\u001b[32m 280\u001b[39m \u001b[33;03m \"\"\"\u001b[39;00m\n\u001b[32m--> \u001b[39m\u001b[32m281\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_build_for_collection_exists\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 282\u001b[39m \u001b[43m \u001b[49m\u001b[43mcollection_name\u001b[49m\u001b[43m=\u001b[49m\u001b[43mcollection_name\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 283\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/http/api/collections_api.py:67\u001b[39m, in \u001b[36m_CollectionsApi._build_for_collection_exists\u001b[39m\u001b[34m(self, collection_name)\u001b[39m\n\u001b[32m 62\u001b[39m path_params = {\n\u001b[32m 63\u001b[39m \u001b[33m\"\u001b[39m\u001b[33mcollection_name\u001b[39m\u001b[33m\"\u001b[39m: \u001b[38;5;28mstr\u001b[39m(collection_name),\n\u001b[32m 64\u001b[39m }\n\u001b[32m 66\u001b[39m headers = {}\n\u001b[32m---> \u001b[39m\u001b[32m67\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mapi_client\u001b[49m\u001b[43m.\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 68\u001b[39m \u001b[43m \u001b[49m\u001b[43mtype_\u001b[49m\u001b[43m=\u001b[49m\u001b[43mm\u001b[49m\u001b[43m.\u001b[49m\u001b[43mInlineResponse2007\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 69\u001b[39m \u001b[43m \u001b[49m\u001b[43mmethod\u001b[49m\u001b[43m=\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mGET\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m 70\u001b[39m \u001b[43m \u001b[49m\u001b[43murl\u001b[49m\u001b[43m=\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43m/collections/\u001b[39;49m\u001b[38;5;132;43;01m{collection_name}\u001b[39;49;00m\u001b[33;43m/exists\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m 71\u001b[39m \u001b[43m \u001b[49m\u001b[43mheaders\u001b[49m\u001b[43m=\u001b[49m\u001b[43mheaders\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mheaders\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01melse\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m,\u001b[49m\n\u001b[32m 72\u001b[39m \u001b[43m \u001b[49m\u001b[43mpath_params\u001b[49m\u001b[43m=\u001b[49m\u001b[43mpath_params\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 73\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/http/api_client.py:90\u001b[39m, in \u001b[36mApiClient.request\u001b[39m\u001b[34m(self, type_, method, url, path_params, **kwargs)\u001b[39m\n\u001b[32m 88\u001b[39m kwargs[\u001b[33m\"\u001b[39m\u001b[33mtimeout\u001b[39m\u001b[33m\"\u001b[39m] = \u001b[38;5;28mint\u001b[39m(kwargs[\u001b[33m\"\u001b[39m\u001b[33mparams\u001b[39m\u001b[33m\"\u001b[39m][\u001b[33m\"\u001b[39m\u001b[33mtimeout\u001b[39m\u001b[33m\"\u001b[39m])\n\u001b[32m 89\u001b[39m request = \u001b[38;5;28mself\u001b[39m._client.build_request(method, url, **kwargs)\n\u001b[32m---> \u001b[39m\u001b[32m90\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43msend\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtype_\u001b[49m\u001b[43m)\u001b[49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/http/api_client.py:107\u001b[39m, in \u001b[36mApiClient.send\u001b[39m\u001b[34m(self, request, type_)\u001b[39m\n\u001b[32m 106\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34msend\u001b[39m(\u001b[38;5;28mself\u001b[39m, request: Request, type_: Type[T]) -> T:\n\u001b[32m--> \u001b[39m\u001b[32m107\u001b[39m response = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mmiddleware\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43msend_inner\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 109\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m response.status_code == \u001b[32m429\u001b[39m:\n\u001b[32m 110\u001b[39m retry_after_s = response.headers.get(\u001b[33m\"\u001b[39m\u001b[33mRetry-After\u001b[39m\u001b[33m\"\u001b[39m, \u001b[38;5;28;01mNone\u001b[39;00m)\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/http/api_client.py:240\u001b[39m, in \u001b[36mBaseMiddleware.__call__\u001b[39m\u001b[34m(self, request, call_next)\u001b[39m\n\u001b[32m 239\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34m__call__\u001b[39m(\u001b[38;5;28mself\u001b[39m, request: Request, call_next: Send) -> Response:\n\u001b[32m--> \u001b[39m\u001b[32m240\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mcall_next\u001b[49m\u001b[43m(\u001b[49m\u001b[43mrequest\u001b[49m\u001b[43m)\u001b[49m\n",
"\u001b[36mFile \u001b[39m\u001b[32m/opt/conda/lib/python3.12/site-packages/qdrant_client/http/api_client.py:131\u001b[39m, in \u001b[36mApiClient.send_inner\u001b[39m\u001b[34m(self, request)\u001b[39m\n\u001b[32m 129\u001b[39m response = \u001b[38;5;28mself\u001b[39m._client.send(request)\n\u001b[32m 130\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[32m--> \u001b[39m\u001b[32m131\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m ResponseHandlingException(e)\n\u001b[32m 132\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m response\n",
"\u001b[31mResponseHandlingException\u001b[39m: [Errno 111] Connection refused"
]
}
],
"source": [
"# slow part here, runs on remote GPU\n",
"vectorstore = vector_store.from_documents(documents=splits, embedding = embedding)\n",
"retriever = vectorstore.as_retriever()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "c6e99791-8f34-4722-9708-665e409c26bd",
"metadata": {},
"outputs": [],
"source": [
"# Set up the Chat model from one of the NRP models\n",
"import os\n",
"api_key = os.getenv(\"OPENAI_API_KEY\")\n",
"\n",
"# see `curl -H \"Authorization: Bearer $OPENAI_API_KEY\" https://llm.nrp-nautilus.io/v1/models`\n",
"models = {\"llama3\": \"llama3-sdsc\", \n",
" \"deepseek-small\": \"DeepSeek-R1-Distill-Qwen-32B\",\n",
" \"deepseek\": \"deepseek-r1-qwen-qualcomm\",\n",
" \"gemma3\": \"gemma3\",\n",
" \"phi3\": \"phi3\",\n",
" \"olmo\": \"olmo\"\n",
" }\n",
"\n",
"from langchain_openai import ChatOpenAI\n",
"llm = ChatOpenAI(model = models[\"gemma3\"], \n",
" api_key = api_key, \n",
" base_url = \"https://llm.nrp-nautilus.io\", \n",
" temperature=0)\n",
"\n",
"# Embedding model from NRP usually times out.\n",
"#embedding = OpenAIEmbeddings(model = \"embed-mistral\", api_key = api_key, base_url = \"https://llm.nrp-nautilus.io\")\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "2bf50abf-5ccd-4de5-9fc4-c9043a66a108",
"metadata": {},
"outputs": [],
"source": [
"from langchain.chains import create_retrieval_chain\n",
"from langchain.chains.combine_documents import create_stuff_documents_chain\n",
"from langchain_core.prompts import ChatPromptTemplate\n",
"system_prompt = (\n",
" \"You are an assistant for question-answering tasks. \"\n",
" \"Use the following pieces of retrieved context to answer \"\n",
" \"the question. If you don't know the answer, say that you \"\n",
" \"don't know. Use five sentences maximum and keep the \"\n",
" \"answer concise.\"\n",
" \"\\n\\n\"\n",
" \"{context}\"\n",
")\n",
"prompt = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\"system\", system_prompt),\n",
" (\"human\", \"{input}\"),\n",
" ]\n",
")\n",
"question_answer_chain = create_stuff_documents_chain(llm, prompt)\n",
"rag_chain = create_retrieval_chain(retriever, question_answer_chain)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e15c64e7-0916-4042-8274-870e4fdb1af7",
"metadata": {},
"outputs": [],
"source": [
"prompt = \"I live in Tanzania and am having issues with lions breaking into my boma and preying on cattle. What interventions might work best for me?\"\n",
"results = rag_chain.invoke({\"input\": prompt})\n",
"results"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "35613607-2c36-4761-a8ea-8c0889530f34",
"metadata": {},
"outputs": [],
"source": [
"prompt = \"What are the most cost-effective prevention methods for elephants raiding my crops?\"\n",
"\n",
"results = rag_chain.invoke({\"input\": prompt})\n",
"results"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3dfc39f6-86e9-47c3-ab67-08f90ebbb823",
"metadata": {},
"outputs": [],
"source": [
"rag_chain.invoke({\"input\": \n",
" \"I have a small herd of goats and cattle and I am worried about jaguars preying on them. What preventative measures can I take?\"\n",
" })"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "56091874-0e41-4b35-be4f-08d8ec6faf56",
"metadata": {},
"outputs": [],
"source": [
"rag_chain.invoke({\"input\": \"I am trying to prevent coyotes from eating the calves of my free-range cattle. What may work best?\"})"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "918dc691-6c66-46b2-8930-01dbeb6f712b",
"metadata": {},
"outputs": [],
"source": [
"rag_chain.invoke({\"input\": \"We have major issues with deer raiding our large agricultural fields. Is there anything I can try to prevent this that won’t break the bank?\"})"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "07b9578c-9a89-4874-a34d-30a060ed3407",
"metadata": {},
"outputs": [],
"source": [
"rag_chain.invoke({\"input\": \"We live in a suburban area and bears sometimes come into our town to eat from our fruit trees and trash. What are the best ways for us to prevent this as a community? We don’t want to have to get rid of our fruit trees…\"})"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "ba272b88-1622-4d06-9361-7f1e2ca89e73",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 06-07 22:45:49 [logger.py:42] Received request embd-651e9b5086e647569840aece45d970bc-0: prompt: 'yl descent.session anyInv os beAccording tocategory Ltd D public quick in StatefulWidget.\\r\\n?', params: PoolingParams(dimensions=None, additional_metadata=None), prompt_token_ids: [3923, 36952, 10177, 894, 15174, 2643, 387, 11190, 311, 5471, 12324, 422, 584, 3974, 304, 37642, 3224, 30], prompt_embeds shape: None, lora_request: None, prompt_adapter_request: None.\n",
"INFO 06-07 22:45:49 [engine.py:316] Added request embd-651e9b5086e647569840aece45d970bc-0.\n",
"INFO: 127.0.0.1:45182 - \"POST /v1/embeddings HTTP/1.1\" 200 OK\n",
"INFO 06-07 22:45:59 [metrics.py:486] Avg prompt throughput: 1.2 tokens/s, Avg generation throughput: 0.1 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.\n"
]
},
{
"data": {
"text/plain": [
"{'input': 'What cattle husbandry strategies might be helpful to prevent conflict if we live in wolf country?',\n",
" 'context': [Document(id='b2071fd8-ba63-4f55-aaed-5469eabef499', metadata={'producer': 'PDF Architect 3', 'creator': 'PDF Architect 3', 'creationdate': '2017-01-25T14:50:41+00:00', 'author': 'V. Pimenta', 'moddate': '2017-01-25T14:52:31+00:00', 'source': 'hwc/Pimenta et al. 2017.pdf', 'total_pages': 20, 'page': 5, 'page_label': '6'}, page_content='4. Discussion\\nOur study examined a human-wildlife conflict involving wolf preda-\\ntion on cattle in northern Portugal, showing that the problem may be\\nworsening due to increased predation levels, though only a minority\\nof cattle farms was heavily affected. We found that predation was par-\\nticularly high on cattle farms using a free-ranging husbandry system,\\nbut also that predation problems within this system were largely con-\\ncentrated on the few herds that were left unconfined at night in winter.\\nIn contrast, we found that farms using a semi-confined husbandry sys-\\ntem suffered much lower losses due to wolf predation, though problems\\nwere higher where calvesb3 months were brought to pastures. These\\nresults suggest that strategies to mitigate wolf predation problems\\nshould be tailored to each husbandry system, involving changes in\\nvery specific practices within each system. Overall, our study points\\nout the importance of considering both the husbandry systems and'),\n",
" Document(id='366817d5-c040-419c-b286-c137f089d414', metadata={'producer': 'PDF Architect 3', 'creator': 'PDF Architect 3', 'creationdate': '2017-01-25T14:50:41+00:00', 'author': 'V. Pimenta', 'moddate': '2017-01-25T14:52:31+00:00', 'source': 'hwc/Pimenta et al. 2017.pdf', 'total_pages': 20, 'page': 7, 'page_label': '8'}, page_content='bandry system. Thus, conflict resolution may probably be achieved by\\nchanging these practices, without needing to change the existing cattle\\nhusbandry systems, namely working in close proximity with the few\\nbreeders chronically affected (N 10 attacks per year). These results cor-\\nroborate the idea that wolf presence is compatible with extensive cattle\\nbreeding as long as fundamental protective measures are applied.\\nAlthough our study showed a clear link between livestock husband-\\nry systems, management practices and wolf predation, we could not ac-\\ncount for potential effects of wolf numbers and space use patterns, and\\nthe availability of alternative wild prey (e.g.,Imbert et al., 2016). This\\nlimitation was partly solved through sampling design, by conducting\\nenquiries in nearby farms affected by different predation rates, thereby\\ncontrolling to some extent for variation in wolf and wild prey densities.\\nI\\nt is possible, however, that spatial variation in wolf densities could ac-'),\n",
" Document(id='e34375ec-d929-4cca-8f44-a96441e72eb2', metadata={'producer': 'PDF Architect 3', 'creator': 'PDF Architect 3', 'creationdate': '2017-01-25T14:50:41+00:00', 'author': 'V. Pimenta', 'moddate': '2017-01-25T14:52:31+00:00', 'source': 'hwc/Pimenta et al. 2017.pdf', 'total_pages': 20, 'page': 7, 'page_label': '8'}, page_content='seemed to strongly affect wolf predation risk. In the free-ranging sys-\\ntem, the herd size was a strong positive correlate of predation risk,\\nwhich is in line with observations from other wolf-livestock systems\\n(Mech et al., 2000; Treves et al., 2004, Bradley and Pletscher, 2005). An-\\nimals in large herds were often scattered over large areas, which likely\\nincreased encounter rates with wolves and thus the probability of\\npredation (Bradley and Pletscher, 2005; Iliopoulos et al., 2009). Some\\nlarge herds were probably loosely attended by the owners, which may\\nincrease vulnerability due to animals straying from the herd or becom-\\ning in poor condition. Whatever the cause, curtailing herds to reduce\\nwolf attacks should be difficult, as there is strong economic incentive\\nfor maintaining large herds. Our results suggest that a potential alterna-\\ntive would be to fence or otherwise protect the herds during the night in\\nwinter, which was predicted to achieve a major reduction in wolf preda-'),\n",
" Document(id='21a25166-c750-45e9-b6be-4ddb89362748', metadata={'producer': 'Acrobat Distiller 8.1.0 (Windows)', 'creator': 'Elsevier', 'creationdate': '2016-09-26T20:02:29+05:30', 'crossmarkdomains[2]': 'elsevier.com', 'crossmarkmajorversiondate': '2010-04-23', 'subject': 'Animal Behaviour, 120 (2016) 245-254. doi:10.1016/j.anbehav.2016.07.013', 'author': 'Bradley F. Blackwell', 'elsevierwebpdfspecifications': '6.5', 'crossmarkdomainexclusive': 'true', 'robots': 'noindex', 'moddate': '2016-09-26T20:03:01+05:30', 'doi': '10.1016/j.anbehav.2016.07.013', 'crossmarkdomains[1]': 'sciencedirect.com', 'title': 'No single solution: application of behavioural principles in mitigating human-wildlife conflict', 'source': 'hwc/Blackwell et al. 2016.pdf', 'total_pages': 10, 'page': 5, 'page_label': '250'}, page_content='pasture. The MAG device is similar, but activated by a passive\\ninfrared detector, which sets off lights and sounds to scare\\ncarnivores from the pasture. Once again, the efficacy of these\\nmethods suffers from effects of previous experience and learning.\\nSeveral field evaluations have shown that carnivores might attempt\\nto enter a pasture to access livestock from a different direction after\\nencountering a RAG or MAG device. Another downside is that while\\none producer has a RAG or MAG device that deters the carnivores,\\nthe ‘problem’ simply gets transferred to the neighbouring producer\\nwithout such devices.\\nOther recent efforts have exploited the territorial defence\\nbehaviour of scent marking by carnivores. This‘biofence’ concept\\noriginated in Botswana as a means to keep African wild dogs,\\nLycaon pictus,from leaving protected reserves and entering farm-\\nlands to depredate livestock. Biofences, however, have had limited\\nsuccess in altering wolf pack movements ( Ausband, Mitchell,')],\n",
" 'answer': 'Strategies to mitigate wolf predation should be tailored to each husbandry system, such as semi-confinement or free-ranging. For free-ranging systems, protecting herds at night during winter or curtailing herd size could reduce attacks. Additionally, devices like RAGs and MAGs can deter carnivores, though their effectiveness can be limited.'}"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 06-07 22:46:09 [metrics.py:486] Avg prompt throughput: 0.0 tokens/s, Avg generation throughput: 0.0 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.\n"
]
}
],
"source": [
"prompt = \"What cattle husbandry strategies might be helpful to prevent conflict if we live in wolf country?\"\n",
"\n",
"rag_chain.invoke({\"input\": prompt})"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9d4d1bf4-4084-430d-8b2d-39ce1d6815db",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "d4bf2492-6852-43a7-8527-06ee4e9848c0",
"metadata": {},
"outputs": [],
"source": [
"## DRAFT exploring other embedding databases\n",
"\n",
"import os\n",
"from langchain_community.vectorstores import FAISS\n",
"from langchain_community.vectorstores import Chroma\n",
"from langchain_community.vectorstores import Qdrant\n",
"from qdrant_client import QdrantClient\n",
"from qdrant_client.models import Distance, VectorParams\n",
"import gc\n",
"import torch\n",
"\n",
"# Option 1: FAISS (Facebook AI Similarity Search) - Most memory efficient\n",
"def create_faiss_vectorstore(splits, embedding, persist_directory=\"./faiss_db\", batch_size=100):\n",
" \"\"\"\n",
" Create FAISS vector store with batched processing to minimize GPU RAM usage\n",
" \"\"\"\n",
" os.makedirs(persist_directory, exist_ok=True)\n",
" \n",
" # Process documents in batches to avoid GPU memory overflow\n",
" vectorstore = None\n",
" \n",
" for i in range(0, len(splits), batch_size):\n",
" batch = splits[i:i + batch_size]\n",
" print(f\"Processing batch {i//batch_size + 1}/{(len(splits) + batch_size - 1)//batch_size}\")\n",
" \n",
" if vectorstore is None:\n",
" # Create initial vectorstore with first batch\n",
" vectorstore = FAISS.from_documents(\n",
" documents=batch,\n",
" embedding=embedding\n",
" )\n",
" else:\n",
" # Add subsequent batches to existing vectorstore\n",
" batch_vectorstore = FAISS.from_documents(\n",
" documents=batch,\n",
" embedding=embedding\n",
" )\n",
" vectorstore.merge_from(batch_vectorstore)\n",
" \n",
" # Clean up temporary vectorstore\n",
" del batch_vectorstore\n",
" \n",
" # Force garbage collection and clear GPU cache if using CUDA\n",
" gc.collect()\n",
" if torch.cuda.is_available():\n",
" torch.cuda.empty_cache()\n",
" \n",
" # Save to disk\n",
" vectorstore.save_local(persist_directory)\n",
" print(f\"Vector store saved to {persist_directory}\")\n",
" \n",
" return vectorstore\n",
"\n",
"def load_faiss_vectorstore(embedding, persist_directory=\"./faiss_db\"):\n",
" \"\"\"Load existing FAISS vector store from disk\"\"\"\n",
" return FAISS.load_local(\n",
" persist_directory,\n",
" embedding,\n",
" allow_dangerous_deserialization=True # Only if you trust the source\n",
" )\n",
"\n",
"# Option 2: Chroma - Persistent SQLite-based storage\n",
"def create_chroma_vectorstore(splits, embedding, persist_directory=\"./chroma_db\", batch_size=100):\n",
" \"\"\"\n",
" Create Chroma vector store with batched processing\n",
" \"\"\"\n",
" # Initialize Chroma with persistence\n",
" vectorstore = Chroma(\n",
" persist_directory=persist_directory,\n",
" embedding_function=embedding\n",
" )\n",
" \n",
" # Add documents in batches\n",
" for i in range(0, len(splits), batch_size):\n",
" batch = splits[i:i + batch_size]\n",
" print(f\"Processing batch {i//batch_size + 1}/{(len(splits) + batch_size - 1)//batch_size}\")\n",
" \n",
" vectorstore.add_documents(batch)\n",
" \n",
" # Force garbage collection and clear GPU cache\n",
" gc.collect()\n",
" if torch.cuda.is_available():\n",
" torch.cuda.empty_cache()\n",
" \n",
" # Persist to disk\n",
" vectorstore.persist()\n",
" print(f\"Vector store persisted to {persist_directory}\")\n",
" \n",
" return vectorstore\n",
"\n",
"def load_chroma_vectorstore(embedding, persist_directory=\"./chroma_db\"):\n",
" \"\"\"Load existing Chroma vector store from disk\"\"\"\n",
" return Chroma(\n",
" persist_directory=persist_directory,\n",
" embedding_function=embedding\n",
" )\n",
"\n",
"# Option 3: Qdrant - High-performance vector database\n",
"def create_qdrant_vectorstore(splits, embedding, collection_name=\"documents\", \n",
" path=\"./qdrant_db\", batch_size=100):\n",
" \"\"\"\n",
" Create Qdrant vector store with local file-based storage\n",
" \"\"\"\n",
" # Initialize local Qdrant client\n",
" client = QdrantClient(path=path)\n",
" \n",
" # Get embedding dimension (embed a sample text)\n",
" sample_embedding = embedding.embed_query(\"sample text\")\n",
" embedding_dim = len(sample_embedding)\n",
" \n",
" # Create collection if it doesn't exist\n",
" try:\n",
" client.create_collection(\n",
" collection_name=collection_name,\n",
" vectors_config=VectorParams(size=embedding_dim, distance=Distance.COSINE)\n",
" )\n",
" except Exception as e:\n",
" print(f\"Collection might already exist: {e}\")\n",
" \n",
" # Create vectorstore\n",
" vectorstore = Qdrant(\n",
" client=client,\n",
" collection_name=collection_name,\n",
" embeddings=embedding\n",
" )\n",
" \n",
" # Add documents in batches\n",
" for i in range(0, len(splits), batch_size):\n",
" batch = splits[i:i + batch_size]\n",
" print(f\"Processing batch {i//batch_size + 1}/{(len(splits) + batch_size - 1)//batch_size}\")\n",
" \n",
" vectorstore.add_documents(batch)\n",
" \n",
" # Force garbage collection and clear GPU cache\n",
" gc.collect()\n",
" if torch.cuda.is_available():\n",
" torch.cuda.empty_cache()\n",
" \n",
" print(f\"Vector store created in {path}\")\n",
" return vectorstore\n",
"\n",
"def load_qdrant_vectorstore(embedding, collection_name=\"documents\", path=\"./qdrant_db\"):\n",
" \"\"\"Load existing Qdrant vector store from disk\"\"\"\n",
" client = QdrantClient(path=path)\n",
" return Qdrant(\n",
" client=client,\n",
" collection_name=collection_name,\n",
" embeddings=embedding\n",
" )\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3cf725ad-69a3-4abd-9907-52427babf6d5",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# Usage examples:\n",
"\n",
"# Replace your original code with one of these options:\n",
"\n",
"# Option 1: FAISS (Recommended for most use cases)\n",
"vectorstore = create_faiss_vectorstore(\n",
" splits=splits, \n",
" embedding=embedding, \n",
" persist_directory=\"./my_faiss_db\",\n",
" batch_size=50 # Adjust based on your GPU memory\n",
")\n",
"\n",
"# To load later:\n",
"# vectorstore = load_faiss_vectorstore(embedding, \"./my_faiss_db\")\n",
"\n",
"# Option 2: Chroma (Good for development and moderate scale)\n",
"# vectorstore = create_chroma_vectorstore(\n",
"# splits=splits,\n",
"# embedding=embedding,\n",
"# persist_directory=\"./my_chroma_db\",\n",
"# batch_size=50\n",
"# )\n",
"\n",
"# Option 3: Qdrant (Best for production and very large scale)\n",
"# vectorstore = create_qdrant_vectorstore(\n",
"# splits=splits,\n",
"# embedding=embedding,\n",
"# collection_name=\"my_documents\",\n",
"# path=\"./my_qdrant_db\",\n",
"# batch_size=50\n",
"# )\n",
"\n",
"# Memory optimization settings\n",
"def optimize_gpu_memory():\n",
" \"\"\"Additional GPU memory optimization\"\"\"\n",
" if torch.cuda.is_available():\n",
" # Set memory fraction if needed\n",
" torch.cuda.set_per_process_memory_fraction(0.8) # Use 80% of GPU memory\n",
" \n",
" # Enable memory mapping for large tensors\n",
" torch.backends.cuda.matmul.allow_tf32 = True\n",
" torch.backends.cudnn.allow_tf32 = True\n",
"\n",
"# Call before processing if you have GPU memory issues\n",
"# optimize_gpu_memory()"
]
}
],
"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.12.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|