行业知识
llama-index调用qwen大模型实现RAG
2026-11-24 21:05:43
来源:互联网转载
背景
llama-index在实现RAG方案的时候多是用的llama等英文大模型,对于国内的诸多模型案例较少,本次将使用qwen大模型实现llama-index的RAG方案。
环境配置
(1)pip包
llamaindex需要预装很多包,这里先把我成功的案例里面的pip包配置发出来,在requirements.txt里面。
absl-py==1.4.0accelerate==0.27.2aiohttp==3.9.3aiosignal==1.3.1aliyun-python-sdk-core==2.13.36aliyun-python-sdk-kms==2.16.1annotated-types==0.6.0anyio==3.7.1apphub @ file:///environment/apps/apphub/dist/apphub-1.0.0.tar.gz#sha256=260f99c0de4c575b19ab913aa134877e9efd81b820b97511fc8379674643c253argon2-cffi==21.3.0argon2-cffi-bindings==21.2.0asgiref==3.7.2asttokens==2.2.1astunparse==1.6.3async-timeout==4.0.3attrs==23.1.0Babel==2.12.1backcall==0.2.0backoff==2.2.1bcrypt==4.1.2beautifulsoup4==4.12.3bleach==6.0.0boltons @ file:///croot/boltons_1677628692245/workbrotlipy==0.7.0bs4==0.0.2build==1.1.1cachetools==5.3.1certifi @ file:///croot/certifi_1690232220950/work/certificffi @ file:///croot/cffi_1670423208954/workchardet==3.0.4charset-normalizer @ file:///tmp/build/80754af9/charset-normalizer_1630003229654/workchroma-hnswlib==0.7.3chromadb==0.4.24click==7.1.2cmake==3.25.0coloredlogs==15.0.1comm==0.1.4conda @ file:///croot/conda_1690494963117/workconda-content-trust @ file:///tmp/abs_5952f1c8-355c-4855-ad2e-538535021ba5h26t22e5/croots/recipe/conda-content-trust_1658126371814/workconda-libmamba-solver @ file:///croot/conda-libmamba-solver_1685032319139/work/srcconda-package-handling @ file:///croot/conda-package-handling_1685024767917/workconda_package_streaming @ file:///croot/conda-package-streaming_1685019673878/workcontourpy==1.2.0crcmod==1.7cryptography @ file:///croot/cryptography_1686613057838/workcycler==0.12.1dataclasses-json==0.6.4debugpy==1.6.7decorator==5.1.1defusedxml==0.7.1Deprecated==1.2.14dirtyjson==1.0.8distro==1.9.0ecdsa==0.18.0exceptiongroup==1.1.2executing==1.2.0fastapi==0.104.1fastjsonschema==2.18.0featurize==0.0.24filelock==3.9.0flatbuffers==23.5.26fonttools==4.44.0frozenlist==1.4.1fsspec==2024.2.0gast==0.4.0google-auth==2.22.0google-auth-oauthlib==1.0.0google-pasta==0.2.0googleapis-common-protos==1.62.0greenlet==3.0.3grpcio==1.62.0gunicorn==21.2.0h11==0.14.0h5py==3.9.0httpcore==0.17.3httptools==0.6.1httpx==0.24.1huggingface-hub==0.20.3humanfriendly==10.0idna==2.10imageio==2.32.0importlib-metadata==6.11.0importlib_resources==6.1.3ipykernel==6.25.0ipython==8.14.0ipython-genutils==0.2.0ipywidgets==8.1.2jedi==0.19.0Jinja2==3.1.2jmespath==0.10.0joblib==1.3.2json5==0.9.14jsonpatch @ file:///tmp/build/80754af9/jsonpatch_1615747632069/workjsonpointer==2.1jsonschema==4.18.6jsonschema-specifications==2023.7.1jupyter-server==1.24.0jupyter_client==8.3.0jupyter_core==5.3.1jupyterlab==3.2.9jupyterlab-pygments==0.2.2jupyterlab_server==2.24.0jupyterlab_widgets==3.0.10keras==2.13.1kiwisolver==1.4.5kubernetes==29.0.0lazy_loader==0.3libclang==16.0.6libmambapy @ file:///croot/mamba-split_1685993156657/work/libmambapylit==15.0.7llama-index==0.10.17llama-index-agent-openai==0.1.5llama-index-cli==0.1.8llama-index-core==0.10.17llama-index-embeddings-huggingface==0.1.4llama-index-embeddings-openai==0.1.6llama-index-indices-managed-llama-cloud==0.1.3llama-index-legacy==0.9.48llama-index-llms-huggingface==0.1.3llama-index-llms-openai==0.1.7llama-index-multi-modal-llms-openai==0.1.4llama-index-program-openai==0.1.4llama-index-question-gen-openai==0.1.3llama-index-readers-file==0.1.8llama-index-readers-llama-parse==0.1.3llama-index-vector-stores-chroma==0.1.5llama-parse==0.3.8llamaindex-py-client==0.1.13Markdown==3.4.4MarkupSafe==2.1.2marshmallow==3.21.1matplotlib==3.8.1matplotlib-inline==0.1.6mistune==3.0.1mmh3==4.1.0monotonic==1.6mpmath==1.2.1multidict==6.0.4mypy-extensions==1.0.0nbclassic==0.2.8nbclient==0.8.0nbconvert==7.7.3nbformat==5.9.2nest-asyncio==1.6.0networkx==3.0nltk==3.8.1notebook==6.4.12numpy==1.24.1nvidia-cublas-cu12==12.1.3.1nvidia-cuda-cupti-cu12==12.1.105nvidia-cuda-nvrtc-cu12==12.1.105nvidia-cuda-runtime-cu12==12.1.105nvidia-cudnn-cu12==8.9.2.26nvidia-cufft-cu12==11.0.2.54nvidia-curand-cu12==10.3.2.106nvidia-cusolver-cu12==11.4.5.107nvidia-cusparse-cu12==12.1.0.106nvidia-nccl-cu12==2.19.3nvidia-nvjitlink-cu12==12.4.99nvidia-nvtx-cu12==12.1.105oauthlib==3.2.2onnxruntime==1.17.1openai==1.13.3opencv-python==4.8.1.78opentelemetry-api==1.23.0opentelemetry-exporter-otlp-proto-common==1.23.0opentelemetry-exporter-otlp-proto-grpc==1.23.0opentelemetry-instrumentation==0.44b0opentelemetry-instrumentation-asgi==0.44b0opentelemetry-instrumentation-fastapi==0.44b0opentelemetry-proto==1.23.0opentelemetry-sdk==1.23.0opentelemetry-semantic-conventions==0.44b0opentelemetry-util-http==0.44b0opt-einsum==3.3.0orjson==3.9.15oss2==2.18.1overrides==7.7.0packaging @ file:///croot/packaging_1678965309396/workpandas==2.1.2pandocfilters==1.5.0parso==0.8.3pexpect==4.8.0pickleshare==0.7.5Pillow==9.3.0platformdirs==3.10.0pluggy @ file:///tmp/build/80754af9/pluggy_1648024709248/workposthog==3.5.0prometheus-client==0.17.1prompt-toolkit==3.0.39protobuf==4.23.4psutil==5.9.5ptyprocess==0.7.0pulsar-client==3.4.0pure-eval==0.2.2pyasn1==0.5.0pyasn1-modules==0.3.0pycosat @ file:///croot/pycosat_1666805502580/workpycparser @ file:///tmp/build/80754af9/pycparser_1636541352034/workpycryptodome==3.18.0pydantic==2.4.2pydantic_core==2.10.1Pygments==2.15.1PyMuPDF==1.23.26PyMuPDFb==1.23.22pyOpenSSL @ file:///croot/pyopenssl_1677607685877/workpyparsing==3.1.1pypdf==4.1.0PyPika==0.48.9pyproject_hooks==1.0.0PySocks @ file:///home/builder/ci_310/pysocks_1640793678128/workpython-dateutil==2.8.2python-dotenv==1.0.0pytz==2023.3.post1PyYAML==6.0.1pyzmq==25.1.0referencing==0.30.0regex==2023.12.25requests==2.31.0requests-oauthlib==1.3.1rpds-py==0.9.2rsa==4.9ruamel.yaml @ file:///croot/ruamel.yaml_1666304550667/workruamel.yaml.clib @ file:///croot/ruamel.yaml.clib_1666302247304/worksafetensors==0.4.2scikit-image==0.22.0scikit-learn==1.3.2scipy==1.11.3seaborn==0.13.0Send2Trash==1.8.2six @ file:///tmp/build/80754af9/six_1644875935023/worksniffio==1.3.0socksio==1.0.0soupsieve==2.4.1SQLAlchemy==2.0.28sshpubkeys==3.3.1stack-data==0.6.2starlette==0.27.0sympy==1.11.1tabulate==0.8.7tenacity==8.2.3tensorboard==2.13.0tensorboard-data-server==0.7.1tensorflow==2.13.0tensorflow-estimator==2.13.0tensorflow-io-gcs-filesystem==0.33.0termcolor==2.3.0terminado==0.17.1threadpoolctl==3.2.0tifffile==2023.9.26tiktoken==0.6.0tinycss2==1.2.1tokenizers==0.15.2tomli==2.0.1toolz @ file:///croot/toolz_1667464077321/worktorch==2.2.1torchaudio==2.0.2+cu118torchvision==0.15.2+cu118tornado==6.3.2tqdm==4.66.2traitlets==5.9.0transformers==4.38.2triton==2.2.0typer==0.9.0typing-inspect==0.9.0typing_extensions==4.8.0tzdata==2023.3urllib3==1.25.11uvicorn==0.23.2uvloop==0.19.0watchfiles==0.21.0wcwidth==0.2.5webencodings==0.5.1websocket-client==1.2.1websockets==12.0Werkzeug==2.3.6widgetsnbextension==4.0.10workspace @ file:///home/featurize/work/workspace/dist/workspace-0.1.0.tar.gz#sha256=b292beb3599f79d3791771eff9dc422cc37c58c1fc8daadeafbf025a2e7ea986wrapt==1.15.0yarl==1.9.2zipp==3.17.0zstandard @ file:///croot/zstandard_1677013143055/work
(2)python 环境
(3)安装命令
!pip install llama-index!pip install llama-index-llms-huggingface!pip install llama-index-embeddings-huggingface!pip install llama-index ipywidgets!pip install torch!git clone https://www.modelscope.cn/AI-ModelScope/bge-small-zh-v1.5.git!git clone https://www.modelscope.cn/qwen/Qwen1.5-4B-Chat.git
(4)目录结构
代码
(1)加载模型
import torchfrom llama_index.llms.huggingface import HuggingFaceLLMfrom llama_index.core import PromptTemplateimport osos.environ['KMP_DUPLICATE_LIB_OK']='True'# Model names (make sure you have access on HF)LLAMA2_7B = "/home/featurize/Qwen1.5-4B-Chat"# LLAMA2_7B_CHAT = "meta-llama/Llama-2-7b-chat-hf"# LLAMA2_13B = "meta-llama/Llama-2-13b-hf"LLAMA2_13B_CHAT = "/home/featurize/Qwen1.5-4B-Chat"# LLAMA2_70B = "meta-llama/Llama-2-70b-hf"# LLAMA2_70B_CHAT = "meta-llama/Llama-2-70b-chat-hf"selected_model = LLAMA2_13B_CHATSYSTEM_PROMPT = """You are an AI assistant that answers questions in a friendly manner, based on the given source documents. Here are some rules you always follow:- Generate human readable output, avoid creating output with gibberish text.- Generate only the requested output, don't include any other language before or after the requested output.- Never say thank you, that you are happy to help, that you are an AI agent, etc. Just answer directly.- Generate professional language typically used in business documents in North America.- Never generate offensive or foul language."""query_wrapper_prompt = PromptTemplate( "[INST]\n" + SYSTEM_PROMPT + "\n\n{query_str}[/INST] ")llm = HuggingFaceLLM(context_window=4096, max_new_tokens=2048, generate_kwargs={"temperature": 0.0, "do_sample": False}, query_wrapper_prompt=query_wrapper_prompt, tokenizer_name=selected_model, model_name=selected_model, device_map="auto") (2)加载词嵌入向量
from llama_index.embeddings.huggingface import HuggingFaceEmbeddingembed_model = HuggingFaceEmbedding(model_name="/home/featurize/bge-small-zh-v1.5")
from llama_index.core import SettingsSettings.llm = llmSettings.embed_model = embed_model
from llama_index.core import SimpleDirectoryReader# load documentsdocuments = SimpleDirectoryReader("./data/").load_data() from llama_index.core import VectorStoreIndexindex = VectorStoreIndex.from_documents(documents)
index
# set Logging to DEBUG for more detailed outputsquery_engine = index.as_query_engine()
response = query_engine.query("小额贷款咋规定的?")print(response)
知识库
llamaindex实现RAG中很关键的一环就是知识库,知识库主要是各种类型的文档,这里给的文档是一个pdf文件,文件内容如下。
总结
从上面的代码可以看出,我们使用qwen和bge-zh模型可以实现本地下载模型的RAG方案,知识库里面的内容也可以实现中文问答,这非常有利于我们进行私有化部署方案,从而扩展我们的功能。