简单使用LlamaIndex实现RAG

使用 LlamaIndex 构建 RAG 应用程序 LlamaIndex(原名 GPTIndex)是一个用于构建 LLM 驱动应用程序的 Python 框架。它充当自定义数据源和大型语言模型之间的桥梁,简化了数据提取、索引和查询。LlamaIndex 内置支持各种数据源、矢量数据库和查询接口,是 RAG 应用的一体化解决方案。它还能与 LangChain、Flask 和 Docker 等工具无缝集成,使其在实际应用中具有高度的灵活性。在此处探索 LlamaIndex 的官方 GitHub 存储库。 阅读详情

简单使用LlamaIndex实现RAG

1 介绍

LlamaIndex是一个专门为大语言模型(LLM)设计的开源数据管理工具,旨在简化和优化LLM在外部数据源中的查询过程。适合在数据索引上构建RAG。

参考的地址

# 官网地址
https://docs.llamaindex.ai/en/stable/

# 模块介绍
https://docs.llamaindex.ai/en/stable/module_guides/

# Github地址
https://github.com/run-llama/llama_index

使用的组件

# Openai like
https://docs.llamaindex.ai/en/stable/api_reference/llms/openai_like/
# OpenLLM,我没测试组件,它继承了OpenAILike
https://docs.llamaindex.ai/en/stable/api_reference/llms/openllm/

# 自定义嵌入模型
https://docs.llamaindex.ai/en/stable/module_guides/models/embeddings/#custom-embedding-model

# 自定义LLM模型
https://docs.llamaindex.ai/en/stable/module_guides/models/llms/usage_custom/

# ChromaVectorStore向量存储
https://docs.llamaindex.ai/en/stable/api_reference/storage/vector_store/chroma/#llama_index.vector_stores.chroma.ChromaVectorStore

# Chroma数据库文档
https://docs.trychroma.com/docs/overview/introduction

需要安装的包

⚠️ 我使用的llma-index的版本:0.12.26

pip install llama-index
pip install llama-index-llms-openai-like
pip install llama-index-vector-stores-chroma
pip install chromadb

2 使用官网构建RAG

⚠️ 国内基本无法直接使用,因为需要OpenAI的模型,所以无法直接使用。那就需要根据自己的需求定制。

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# 加载数据
documents = SimpleDirectoryReader("E:/data").load_data()
# 转化文档
index = VectorStoreIndex.from_documents(documents)
# 构建查询引擎
query_engine = index.as_query_engine()
# 使用
response = query_engine.query("Some question about the data should go here")
print(response)

3 自定义构建RAG

3.1 RAG构建思路

使用LlamaIndex构建RAG的思路如下图,LlamaIndex需要自定义向量模型和类大模型组件。

graph TD
	A[(1)构建Documet对象列表,读数据文档] --> B
	B[(2)构建Node对象列表,使用分割器分割Document,其中分割器有SentenceSplitter、TextSplitter等] --> C
	C[(3)向量化和存储,自定义嵌入模型和存储到数据库中,可以使用SimpleVectorStore、ChromaVectorStore等] --> D
	D[(4)构建向量索引库,使用VectorStoreIndex构建向量索引] --> E
	E[(5)构建检索器,用于用户检索输入的prompt] --> F
	F[(6)构建响应生成器,自定义大模型生成用户输入的prompt] --> G
	G[(7)构建查询引擎,组合检索器和响应生成器构建查询引擎] --> H
	H[(8)使用prompt查询和生成数据]

在这里插入图片描述

3.2 自定义RAG

(1) my_document_custorm_engine.py

import chromadb
from llama_index.core import Document, VectorStoreIndex, get_response_synthesizer
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.response_synthesizers import ResponseMode
from llama_index.vector_stores.chroma import ChromaVectorStore

from my_custom_rag.custom_like_openai import CustomLikeOpenAI

# 需要安装的组件
"""
pip install llama-index
pip install llama-index-llms-openai-like
pip install llama-index-vector-stores-chroma
"""

from my_custom_rag.custom_embedding import CustomEmbeddings

# 自定嵌入模型
my_embedding = CustomEmbeddings()

# 构建文档列表,可根据自己的需求设置文本文档列表
document_text = [
    "河南大学(Henan University),简称“河大”(HENU),位于中国河南省郑州市、开封市,是河南省人民政府与中华人民共和国教育部共建公办高校 [392]、国家“双一流”建设高校 [69],入选国家“111计划” [2]、中西部高校基础能力建设工程 [313]、中国政府奖学金来华留学生接收院校 [388]。",
    "河南大学创立于1912年,始名河南留学欧美预备学校。后历经中州大学、国立开封中山大学、省立河南大学等阶段,1942年升格为国立河南大学 [153]。1952年院系调整 ,校本部更名为河南师范学院。后经开封师范学院、河南师范大学等阶段,1984年恢复河南大学校名 [153]。2000年6月,原河南大学、开封医学高等专科学校、开封师范高等专科学校合并组建新的河南大学 [154]。2012年,河南大学入选第一批卓越医生教育培养计划项目试点高校 [130];入选国家级卓越法律人才教育培养基地 [390];入选第一批国家卓越医生教育培养计划项目试点高校 [391]。",
    "截至2024年6月,学校设有40个学院、93个本科招生专业 、47个硕士学位授权一级学科 、39种硕士专业学位授权类别 、2种博士专业学位授权类别、24个博士学位授权一级学科 、20个博士后科研流动站、13个学科进入ESI世界排名前1% ;有全日制在校生5万余人、教职工4700余人,教师中有院士、学部委员6人,长江学者、国家杰青、“万人计划”领军人才等国家级领军人才26人,国家级青年人才15人;拥有3个国家重点实验室 ,1个国家野外科学观测研究站 ,3个国家地方联合工程研究中心 ,4个河南省实验室 , 5个教育部和农业部重点实验室 [448]。",
    "河南大学软件学院(Henan University Software College)是全国较早、河南省最早成立的软件学院之一,位于中国河南省开封市。学院是国家示范性软件学院联盟成员单位,信息技术新工科产学研联盟首批会员单位,2020 年度获批河南省特色化示范性软件学院,河南省鲲鹏产业学院建设高校。学院设有软件工程系、网络工程系和公共计算机教学中心,拥有“河南省智能数据处理工程研究中心”、“河南省现代网络技术实验教学示范中心”、“河南省智能网络理论与关键技术国际联合实验室”等省级科研教学平台、“河南省高等学校学科(软件工程)引智基地”、“河南省本科高校大学生校外实践教育基地”和“河南省高校优秀基层教学组织”称号。学院独立承建软件工程和网络工程两个本科专业,软件工程专业为国家一流本科专业, 网络工程专业为河南省一流本科专业。同时,拥有“软件工程技术”二级博士学位授权点,电子信息专业具有硕士学位授予权,建有软件工程博士后科研流动站。"
]

# 构建LlamaIndex的对象列表
documents = list()
for text in document_text:
    documents.append(Document(text=text))
# print(documents)

# 将LlamaIndex的Document拆分Nodes
parser = SentenceSplitter()
nodes = parser.get_nodes_from_documents(documents)

# 使用嵌入模型对node进行嵌入
for node in nodes:
    node.embedding = my_embedding.get_text_embedding(node.get_content())

# 创建Chroma客户端
client = chromadb.Client()

# 创建集合
collection = client.create_collection("my-documents")
chroma_vector_store = ChromaVectorStore(chroma_collection=collection)

# 存入向量库中
chroma_vector_store.add(nodes)

# 使用索引对象
# 注意:VectorStoreIndex必须有向量库支持,否则会报下面的错误
# Cannot initialize from a vector store that does not store text.
vector_index = VectorStoreIndex.from_vector_store(chroma_vector_store, embed_model=my_embedding)


# Llama index中的OpenAILike调用千问和Kimi不能使用,一直报参数错误,所以只能自定义了
llm = CustomLikeOpenAI(
    model="qwen2.5-14b-instruct",
    api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",
    api_key = "sk-XXX"
)

# 下面的是LlamaIndex中的OpenAILike
# llm = OpenAILike(
#     model="qwen2.5-14b-instruct",
#     base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
#     api_key = "sk-XXX"
# )

"""
# 显示构建查询引擎=检索器+响应生成器

# 创建检索器,similarity_top_k设置返回值的数量
query_retriever = vector_index.as_retriever(similarity_top_k=1)

# 响应生成器有compact(默认模式)、refine、simple_summarize等
response_synthesizer = get_response_synthesizer(
    llm=llm,
    response_mode=ResponseMode.COMPACT,
    # streaming=True
)

query_engine = RetrieverQueryEngine(
    retriever=query_retriever,
    response_synthesizer=response_synthesizer
)

"""
# 隐式构建查询引擎,上面两步可以使用1行构建
query_engine = vector_index.as_query_engine(
    llm=llm,
    # streaming=True
)

# 如果不使用流式输出,直接打印即可
query_data = query_engine.query("用30字介绍一下河南大学")
print(query_data)

# # 使用流式输出
# for text in query_data.response_gen:
#     print(text)
#     pass

(2)custom_embedding.py

自定义嵌入模型

from llama_index.core.base.embeddings.base import Embedding
from llama_index.core.embeddings import BaseEmbedding
from sentence_transformers import SentenceTransformer

# 构建向量模型,可根据自己的需求,自定义调用互联网和本地模型等
embedder = SentenceTransformer("E:/model/sentencetransformers/distiluse-base-multilingual-cased-v1")


class CustomEmbeddings(BaseEmbedding):
    def _get_query_embedding(self, query: str) -> Embedding:
        # 生成嵌入列表
        return embedder.encode(query).tolist()

    async def _aget_query_embedding(self, query: str) -> Embedding:
        # 生成嵌入列表
        return embedder.encode(query).tolist()

    def _get_text_embedding(self, text: str) -> Embedding:
        # 生成嵌入列表
        return embedder.encode(text).tolist()

(3)custom_like_openai.py

自定义大模型

from typing import Any

from llama_index.core.base.llms.types import CompletionResponseGen, LLMMetadata, CompletionResponse
from llama_index.core.llms import CustomLLM
from openai import OpenAI
from pydantic import Field


class CustomLikeOpenAI(CustomLLM):
    model: str = Field(description="自定义模型名称")
    api_key: str = Field(description="自定义API Key")
    api_base: str = Field(description="自定义API地址")
    context_window: int = Field(default=32768, description="上下文窗口大小")
    temperature: float = Field(ge=0, le=1, default=0.3, description="设置温度,值域须为 [0, 1]")
    num_output: int = Field(default=8192, description="设置max_tokens")

    def __init__(self, **data):
        # 必须调用父类初始化
        super().__init__(**data)

        # 创建对象
        self._client = OpenAI(
            api_key=self.api_key,
            base_url=self.api_base
        )

    @property
    def metadata(self) -> LLMMetadata:
        """Get LLM metadata."""
        return LLMMetadata(
            context_window=self.context_window,
            num_output=self.num_output,
            model_name=self.model
        )

    def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse:
        """
        生成文本

        :param prompt: 添加提示词
        :param kwargs: 其他相关参数
        :return: CompletionResponse
        """
        # 构建生成
        completion = self._client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "user", "content": prompt}
            ],
            temperature=self.temperature,
            max_tokens=self.num_output
        )
        # 返回值
        return CompletionResponse(text=completion.choices[0].message.content)

    def stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen:
        """
        生成流式文本

        :param prompt: 提示词
        :param kwargs: 其他参数
        :return: CompletionResponseGen迭代器
        """

        # 根据需要可以不实现,如果不想实现使用下面代码即可
        # raise NotImplementedError("Streaming not supported")

        # 构建数据流
        stream = self._client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "user", "content": prompt}
            ],
            temperature=self.temperature,
            max_tokens=self.num_output,
            stream=True
        )
        # 遍历数据流
        for chunk in stream:
            # 获取新文本
            delta = chunk.choices[0].delta

            # 判断数据是否存在
            if delta.content:
                yield CompletionResponse(text=delta.content, delta=delta.content)

3.3 其他学习

(1)使用SimpleVectorStore存储

from llama_index.core import Document
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.vector_stores import SimpleVectorStore, VectorStoreQuery
from sentence_transformers import SentenceTransformer

# 构建向量模型
embedder = SentenceTransformer("E:/model/sentencetransformers/distiluse-base-multilingual-cased-v1")

# 构建文档列表,可根据自己的需求设置文本文档列表
document_text = [
    "A man is eating food.",
    "A man is eating a piece of bread.",
    "The girl is carrying a baby.",
    "A man is riding a horse.",
    "A woman is playing violin.",
    "Two men pushed carts through the woods.",
    "A man is riding a white horse on an enclosed ground.",
    "A monkey is playing drums.",
    "A cheetah is running behind its prey.",
]

# 构建LlamaIndex的对象列表
documents = list()
for text in document_text:
    documents.append(Document(text=text))
# print(documents)

# 将LlamaIndex的Document拆分Nodes
parser = SentenceSplitter()
nodes = parser.get_nodes_from_documents(documents)

# 使用嵌入模型对node进行嵌入
for node in nodes:
    node.embedding = embedder.encode(node.get_content())
# print(nodes)

# 下面一般不会用于生产环境,生产环境一般用向量库
# 基于内存的方式存储向量
simple_vector_store = SimpleVectorStore()
simple_vector_store.add(nodes)

# 持久化nodes,默认存储在”./storage“
# simple_vector_store.persist()
# 获取持久化数据
# simple_vector_store = SimpleVectorStore.from_persist_path("./storage/vector_store.json")

# # 对查询的文本进行嵌入
query_embed = embedder.encode("A man is eating pasta").tolist()
# 查询到的目标数据
target_data_embed = simple_vector_store.query(VectorStoreQuery(query_embedding=query_embed, similarity_top_k=2))

print(target_data_embed)

(2)使用索引VectorStoreIndex

import chromadb
from llama_index.core import Document, VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter
from llama_index.vector_stores.chroma import ChromaVectorStore

from my_custom_rag.custom_embedding import CustomEmbeddings

# 自定嵌入模型
my_embedding = CustomEmbeddings()

# 构建文档列表,可根据自己的需求设置文本文档列表
document_text = [
    "A man is eating food.",
    "A man is eating a piece of bread.",
    "The girl is carrying a baby.",
    "A man is riding a horse.",
    "A woman is playing violin.",
    "Two men pushed carts through the woods.",
    "A man is riding a white horse on an enclosed ground.",
    "A monkey is playing drums.",
    "A cheetah is running behind its prey.",
]

# 构建LlamaIndex的对象列表
documents = list()
for text in document_text:
    documents.append(Document(text=text))
# print(documents)

# 将LlamaIndex的Document拆分Nodes
parser = SentenceSplitter()
nodes = parser.get_nodes_from_documents(documents)

# 使用嵌入模型对node进行嵌入
for node in nodes:
    node.embedding = my_embedding.get_text_embedding(node.get_content())

# 创建Chroma客户端
client = chromadb.Client()

# 创建集合
collection = client.create_collection("my-documents")
chroma_vector_store = ChromaVectorStore(chroma_collection=collection)

# 存入向量库中
chroma_vector_store.add(nodes)


# 使用索引对象
# 注意:VectorStoreIndex必须有向量库支持,否则会报下面的错误
# Cannot initialize from a vector store that does not store text.
vector_index = VectorStoreIndex.from_vector_store(chroma_vector_store, embed_model=my_embedding)

# 创建检索器,similarity_top_k设置返回值的数量
query_retriever = vector_index.as_retriever(similarity_top_k=1)

# 查询数据
query_text = "A man is eating pasta"
retrieve_data = query_retriever.retrieve(query_text)

print(retrieve_data)
使用LlamaIndex构建RAG LlamaIndex是一个数据框架,它主要用于连接大型语言模型(LLMs)与外部数据源,例如API、PDF文档、SQL数据库等。这个框架的设计目的是为了增强LLM的能力,使其能够理解和生成更准确、更有上下文关联的文本,尤其是在涉及私人数据或特定领域知识的情况下。LlamaIndex通过创建索引结构来组织和访问数据,这样可以更高效地检索相关信息并将其提供给LLM。这些索引可以是列表索引、向量索引、树索引或关键词索引等,具体取决于数据类型和需求。 阅读详情

相关推荐

LlamaIndex——RAG概述

目前,以下组件是 Transformation 对象:文本分割器、节点解析器、元数据提取器、Embeddingsmodel(查看我们支持的嵌入列表)。除了这些模块,我们可以自定义转换操作,例如import re],

weixin_45325331的博客 3748

AiDocZh.com重磅发布!LlamaIndex中文文档上线啦!

LlamaIndex 是一个用于构建上下文增强LLM应用的框架。上下文增强是指将LLM应用于您的私有数据或领域特定数据的任何用例。一些流行的用例问答聊天机器人(通常称为RAG系统,代表“检索增强生成”)文档理解与提取能够进行研究并采取行动的自主代理LlamaIndex 提供了从原型到生产环境构建上述任何用例所需的工具。这些工具允许您同时摄取/处理数据,并实现将数据访问与LLM提示结合的复杂查询工作流程。这是一个汇聚做AI工具中文文档的网站,方便大家在学习和工作中查阅相关工具文档,快速使用相关工具。

数智笔记 8359

RAG 进阶 LlamaIndex多文档

我们一起来学习LlamaIndex功能更完善的多文档RAG,大家可以参照官方文档来对比学习。LlamaIndex 为多文档RAG提供了VectorStoreIndex、SummaryIndex、ObjectIndex、QueryEngineTool、FnRetrieverOpenAIAgent 等丰富组件,过程复杂,但井然有序除VectorStoreIndex、SummaryIndex,还有agent 索引, object 索引。

2401_85324918的博客 1448

llamaindex介绍以及加载中文模型的4种方法

llamaIndex是一个用于LLM应用程序的数据框架。用于注入,结构化,并访问私有或特定领域数据。用通俗易懂的方式讲解:大模型应用框架 LangChain 和 LlamaIndex,到底谁更胜一筹?llamaindex的官网介绍:https://docs.llamaindex.ai/en/stable/examples/low_level/oss_ingestion_retrieval/内容包括如下使用模型,加载数据,数据向量化,存储向量,对输入query做检索,跟踪。效果评估。

qq_29837229的博客 3745

LLamaIndex构建RAG

LLamaIndex 大模型应用程序的数据框架,用于注入,结构化,并私有或特定领域数据解决大模型和数据间的衔接问题。数据可能存在sql,pdf,api之后,LLamaIndex应运而生。通过数据增强模型----RAG。

m0_57755179的博客 726

大模型上层工具链(一):Llama_index【建立自己的垂直领域资料人工智能助理】

有了llama_index之后,我们就可以将自己的文档库通过llama_index生成一份index文件。当用户提问时,llama_index通过的index文件能索引到相关的资料,将他们一起喂给GPT。这样,最终能得到更精确的答案。ChatGPT的泛用性极高,上知天文,下通地理,参考古今,博稽中外,几乎无所不知,无所不晓。但如果涉及垂直领域的专业知识点,ChatGPT难免也会有语焉不详,闪烁其词的毛病,本次我们将特定领域的学习材料“喂”给ChatGPT,让它“学习”后再来回答专业问题。

u013250861的博客 1189

DeepSeek 大模型 + LlamaIndex + MySQL 数据库 + 知识文档 实现简单 RAG 系统

DeepSeek 大模型 + LlamaIndex + MySQL 数据库 + 知识文档 实现简单 RAG 系统

爱的叹息的专栏 1294

保姆级教程:用Intouch SMC连接S7-200 Smart PLC,Modbus TCP和S7协议一次搞定

本文详细介绍了如何使用Intouch SMC连接S7-200 Smart PLC,涵盖Modbus TCP和S7协议的双协议通信配置。通过环境准备、参数设置、常见问题排查及实战技巧,帮助工程师快速实现工业自动化系统中的稳定通信,提升设备监控效率。

weixin_30499315的博客 433

InternLM + LlamaIndex RAG 实践

给模型注入新知识的方式,可以简单分为两种方式,一种是内部的,即更新模型的权重,另一个就是外部的方式,给模型注入格外的上下文或者说外部信息,不改变它的的权重。st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?

Foolbird123的博客 824

深度学习&故障诊断初学者 - 学习路线

针对初学者,一头雾水,不知如何学习,本文给出了一个学习路线 Python学习 - 打好编程基础 https://www.bilibili.com/video/BV1vA411b7Rn?spm_id_from=333.337.search-card.all.click B站免费课程 学到P49 建议时长 2周 深度学习理论 - 浅浅理解神经网络 https://www.bilibili.com/video/BV1FT4y1E74V?p=41 建议时长 2周...............

m0_47410750的博客 6万+

PyCharm+QT Designer整合

CMD下使用pip安装PyQt4或者PYQT5 这里要注意,你下载的PYQT5不包含QT designer 还要:pip3 install PyQt5-tools,好像Pyqt5中将designer分离了或者查看源码:https://github.com/altendky/pyqt5-tools,编译安装 将QT Designer整合到PyCharm的External Tools中,以后就可...

mxh的博客 6414

书生浦语大模型第3期基础岛——InternLM + LlamaIndex RAG 实践

打开llamaindex_internlm.py 贴入以下代码。点击选择镜像使用 Cuda11.7-conda镜像。下载Sentence Transformer模型。打开download_hf.py 贴入以下代码。把InternLM2 1.8B 软连接出来。安装LlamaIndex词嵌入向量依赖。安装 Llamaindex和相关的包。安装python依赖包。下载NLTK相关资源。

tianyuqianmo的博客 2047

Informer:比Transformer更有效的长时间序列预测

目录 AAAI 2021最佳论文:比Transformer更有效的长时间序列预测 Background Why attention Methods:the details of Informer Solve_Challenge_1:最基本的一个思路就是降低Attention的计算量,仅计算一些非常重要的或者说有代表性的Attention即可,一些相近的思路在近期不断的提出,比如Sparse-Attention,这个方法涉及了稀疏化Attention的操作,来减少Attention计算量,然后涉及的

To be a better man 1万+

如何在LlamaIndex中使用RAG?

什么是 Llama-Index LlamaIndex是一个数据框架,用于帮助基于 LLM`的应用程序摄取、构建结构和访问私有或特定领域的数据。

2401_85325557的博客 921

GPOPSII 对控制量变化率进行约束,避免控制量振荡

在这篇文章中,在GPOPSII中通过对控制量变化的约束,优化求解得到更平滑的控制量曲线,更符合真实控制约束。

Dannyfomer的博客 1870

Cadence仿真笔记(二):传统noise仿真—共源极的噪声

cadence中进行传统噪声仿真

Bao_xue的博客 1万+

LLM之RAG实战(三十二)| 使用RAGAs和LlamaIndex评估RAG

第二个和第三个问题的上下文精度为0,表明检索到的上下文中的相关上下文没有排在最前面。此外,忠实度得分并不低,这表明答案主要是从上下文中得出或总结的,可以得出结论,答案不是由于LLM的幻觉而产生的。在RAGAs中,如果您想使用另一个LLM(如Gemini)来使用LlamaIndex进行评估,即使在调试了RAGAs的源代码后,我也没有在版本0.0.22中找到任何有用的方法。此外,我们发现,尽管我们的上下文相关性得分较低,gpt-3.5-turb-16k(RAGA的默认模型)仍然能够从中推断出答案。

wshzd的博客 4309

PyCharm配置SSH远程解释器第3步时弹框报错:com.google.gson.stream.MalformedJsonException: Expected value at l...如何解决?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值 。

**My Coding Family** 1928

【大模型】基于LlamaIndex实现大模型RAG

LlamaIndex是一个LLM文本增强的框架,其中包含完整的RAG解决方案。项目在2023年1月29日发布了第一个版本,当时叫做“GPT Index v0.2.17” ,项目作者Jerry Liu。

酒酿小圆子呀~ 2606

【ArcGIS风暴】ArcGIS 10.2导入Excel数据X、Y坐标(经纬度、平面坐标),生成Shapefile点数据图层

用过CASS的人都知道,野外数字测图得到的点数据(平面坐标)可以直接导入到CASS中,进一步绘制地形图。那么,带有坐标的数据能不能在ArcGIS中实现点图层的生成呢?答案是必须的! 本文以气象台站shp数据的生成为例,详细介绍ArcGIS 10.2中导入X、Y坐标(这里指的是经度、纬度),生成Shapefile点数据的流程。 相关阅读:《全站仪、RTK测量坐标数据在CASS和ArcGIS中展点的区别和联系》 目录 1、数据准备 2、添加X、Y数据 3、属性表连接(Join) 4、导出为Sh.

智慧空间实验室 10万+

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

llamaindex实现企业级RAG应用(一)

查询引擎可以通过()的方式一步构建完成,但若要实现更复杂的RAG流程,则需要我们精准控制query_engine的内部细节,这里我们手动构建一个。2.1 自定义响应器通俗地说,查询引擎=检索器+响应器,检索器可灵活操作的代码不多,这里仅构建响应器# 自定义响应器"根据以下上下文信息:\n""使用中文回答以下问题\n ""问题: {query_str}\n""答案: "self,) -> None:# 必须实现的接口# 必须实现的接口, 更新提示词# 生成响应的接口self,

weixin_42479327的博客 1292

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Llamaindex RAG实践

基于 LlamaIndex 构建自己的 RAG 知识库,寻找一个问题 A 在使用 LlamaIndex 之前InternLM2-Chat-1.8B模型不会回答,借助 LlamaIndex 后 InternLM2-Chat-1.8B 模型具备回答 A 的能力,截图保存。本文将分为以下几个部分来介绍,如何使用 LlamaIndex 来部署 InternLM2 1.8B(以 InternStudio 的环境为例)

2201_75335094的博客 2215

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

基于 Milvus + LlamaIndex 实现高级 RAG

随着大语言模型(LLM)技术的发展,RAG(Retrieval Augmented Generation)技术得到了广泛探讨和研究,越来越多的高级 RAG 检索方法也随之被人发现,相对于普通的 RAG 检索,高级 RAG 通过更深化的技术细节、更复杂的搜索策略,提供出了更准确、更相关、更丰富的信息检索结果。如果检索需要精确的关键词匹配,这种检索技术很有益处。生成回复质量面临着幻觉挑战,即 LLM 生成的答案并没有基于所提供的上下文,和上下文不相关,或者生成的回复存在着包含有害或歧视内容的潜在风险。

ZILLIZ 1631

四、RAG与LlamaIndex

RAG(检索增强生成)是一种结合检索和生成技术的方法,通过从文档库中检索相关信息来提升大模型回答的准确性。它解决了大模型的知识局限性、幻觉问题和数据安全等挑战。RAG分为原始、高级和模块化三个阶段,LlamaIndex作为开源框架,支持数据整合、索引构建和增强LLM推理能力,帮助开发者构建知识助手和AI代理。相比重新训练或微调模型,RAG成本更低、信息实时更新且结果更可信。LlamaCloud则提供托管服务,简化企业级应用的数据管理流程。

nzlyll的博客 2548

使用RAGAs + LlamaIndex进行RAG评估

使用RAGAs + LlamaIndex进行RAG评估

安静的软件工程师 2657

【Llamaindex RAG实践】

给模型注入新知识的方式,可以简单分为两种方式,一种是内部的,即更新模型的权重,另一个就是外部的方式,给模型注入格外的上下文或者说外部信息,不改变它的的权重。st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?st.session_state.messages = [{"role": "assistant", "content": "你好,我是你的助手,有什么我可以帮助你的吗?

m0_53291740的博客 1094
上一篇: Docker安装嵌入框架Text Embeddings Inference (TEI)
下一篇: 在线Markdown转化微信格式的编辑器
MasonYyp
博客等级 码龄9年 301粉丝 297原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值