> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# RAG系统实战
- URL: https://www.hubwiz.com/blog/rag-system-hands-on/
- Published: 2024-11-01T07:29:37.000Z
- Updated: 2024-11-01T07:29:37.000Z
- Description: 本文指导读者使用四种关键技术构建 RAG 系统：Llama3、Ollama、DSPy 和 Milvus。
- Author: admin
- Tags: RAG, LLAMA, OLLAMA, DSPY, MILVUS, MILVUSRM, #Import 2026-10-14 14:41

到目前为止，你可能已经熟悉了检索增强生成 (RAG) 系统，这是 NLP 应用程序中使用的框架。在本文中，我们旨在指导读者使用四种关键技术构建 RAG 系统：Llama3、Ollama、DSPy 和 Milvus。首先，让我们了解它们是什么。

## 1、 Llama3、Ollama、DSPy 和 Milvus

Llama3 是 Meta 的一个开源语言模型，具有预训练和指令微调的语言模型，具有 8B 和 70B 参数。它基于 NLP 技术的最新进展构建，并声称在理解和响应复杂查询方面具有很高的准确性。

Ollama 允许你在本地运行开源大型语言模型，例如 Llama 2：Ollama 将模型权重、配置和数据捆绑到一个包中。

DSPy 是使用语言模型和检索模型解决高级任务的框架。

最后，Milvus 是一个先进的矢量数据库，专为高效的相似性搜索和快速数据检索而设计。它提供可扩展的存储解决方案和高速搜索功能。将 Milvus 集成到 RAG 系统中可显著增强其快速查找和检索相关信息的能力。

## 2、设置和安装

首先，创建并激活适合处理依赖项的 Python 环境。您可以使用 venv 或 conda 等虚拟环境来隔离和管理项目包。

通过在终端中运行以下命令来安装必要的 Python 库。

```
pip install dspy pymilvus openai pandas
```

将已安装的库导入 Python 脚本以确保它们已准备好使用。

```
import dspy
import milvus
import openai
import os
import pandas as pd

```

要为 OpenAI 配置 API 密钥，请在环境变量中设置它们。将 `your_openai_api_key`替换为实际的 OpenAI API 密钥。

```
# Configure the OpenAI and Milvus API keys (you need to replace 'your_key_here' with actual keys)
os.environ['OPENAI_API_KEY'] = 'your_openai_api_key'

```

## 3、Milvus 配置

设置 OpenAI API 密钥后，下一步是配置 Milvus 以管理 RAG 系统中的嵌入。开始初始化 Milvus 客户端以使用提供的 URI 连接到您的数据库。此连接使你的系统能够与 Milvus 向量数据库进行交互。

连接后，你需要设置专门为嵌入设计的集合。使用必要的字段定义集合以存储嵌入和唯一标识符。指定向量维度并选择适当的索引类型以优化 Milvus 中的搜索功能。

以下是如何初始化 Milvus 客户端并设置集合：

```

    from pymilvus import MilvusClient, MetricType, IndexType, DataType

    # Initialize Milvus client
    milvus_client = Milvus(uri='your_milvus_uri')

    # Define collection parameters
    collection_name = 'ZillizBlogCollection'
    collection_params = {
        'fields': [
            {'name': 'text', 'type': DataType.FLOAT_VECTOR, 'params': {'dim': 768}, 'indexes': [{'index_type': IndexType.IVF_FLAT, 'metric_type': MetricType.L2}]},
            {'name': 'id', 'type': DataType.INT64, 'auto_id': True}
        ]
    }

    # Create collection if it doesn't exist
    if not milvus_client.has_collection(collection_name):
        milvus_client.create_collection(collection_name, collection_params)

```

对于数据提取，请预处理文本数据并将其转换为嵌入，然后再将其插入到集合中。此过程通常涉及使用模型从文本生成嵌入，如下面的函数所示：

```

    # Function to create Milvus vectors for the blog posts
    def create_milvus_vectors(data_frame, text_column='text'):
        # Assuming the use of an OpenAI model to generate embeddings
        embeddings = openai.Embedding.create(
            input=data_frame[text_column].tolist(),
            model="text-embedding-ada-002"
        )
        return embeddings['data']

```

## 4、MilvusRM 集成

MilvusRM 是一个用于将检索机制与 Milvus 集合高效集成的组件。通过指定集合名称和连接 URI 来初始化 MilvusRM，如以下代码所示。

```
from dspy.retrieve.milvus_rm import MilvusRM

# Initialize the MilvusRM retriever
milvus_retriever = MilvusRM(
    collection_name=collection_name,
    uri='your_milvus_uri',
    k=5
)

```

## 5、Llama3 和 Ollama 设置

要通过 Ollama 托管服务将你的应用程序连接到 Llama3，请配置必要的设置，例如模型版本和令牌限制。此设置使你的系统能够访问 Llama3 生成响应的功能。以下是你可以如何建立此连接。

```
# Connect to Llama3 hosted with Ollama
llama3_ollama = dspy.OllamaLocal(
    model="llama3:8b-instruct-q5_1",
    max_tokens=4000,
    timeout_s=480
)

```

配置连接后，进行简单测试以确保与 Llama3 的连接正常运行。此验证步骤非常重要，可以检查系统是否能够有效地与 Llama3 通信并接收响应。

```
# Test connection
test_query = "What is the latest in AI?"
test_response = llama3_ollama(test_query)
print("Test Llama3 response:", test_response)

```

## 6、构建 RAG 系统

为 RAG 系统定义一个 Python 类，以整合 MilvusRM 的检索功能和 Llama3 的生成能力。此类结构允许系统通过检索相关信息并生成响应来有效地处理查询。

```
class RAG(dspy.Module):
    def __init__(self, retriever, generator, k=5):
        super().__init__()
        self.retrieve = dspy.Retrieve(k=k, retriever_model=retriever)
        self.generate_answer = dspy.Predict(generator)

    def forward(self, question):
        context = self.retrieve(question).passages
        pred = self.generate_answer(context=context, question=question).answer
        return dspy.Prediction(context=context, answer=pred, question=question)

```

使用之前初始化的组件实例化 RAG 系统，设置它来处理和响应查询。

```
# Instantiate the RAG system
rag_system = RAG(retriever=milvus_retriever, generator=llama3_ollama)

```

## 7、MIPRO 优化

定义优化指标以评估 RAG 系统生成的响应。该指标应将生成的响应与基本事实答案进行比较，以评估准确性和相关性。

```
# Define the evaluation metric
def metric_function(gold, pred):
    # This could be more complex, integrating more advanced alignment and coherence metrics
    return np.mean(gold == pred)

```

配置并启动 MIPRO 优化器，根据检索到的文档优化 Llama3 使用的提示。此优化过程旨在提高生成的响应的相关性和质量。

```
from dspy.teleprompt import MIPRO

# Assume 'trainset' is a DataFrame loaded with question-answer pairs
trainset = pd.DataFrame({
    'question': ['What is AI?', 'Explain machine learning'],
    'gold_answer': ['Artificial intelligence is the simulation of human intelligence in machines.', 'Machine learning is a subset of AI that allows systems to learn and improve from experience.']
})

# Configure and run MIPRO optimizer
mipro_optimizer = MIPRO(
    prompt_model=llama3_ollama,
    task_model=llama3_ollama,
    metric=metric_function,
    num_candidates=3
)

```

## 8、评估和测试

测试 RAG 系统包括向其提供预定的查询并分析其生成的响应。我们通过将系统答案与已知的正确答案（通常称为“黄金”答案）进行比较来评估系统的准确性。通过这种比较，我们可以确定系统提供正确信息的频率。

除了准确性之外，我们还评估生成的响应的相关性。相关性衡量系统的答案与查询意图的一致性。此评估有助于确保系统提供的信息正确、适合上下文且对用户有用。

## 9、结束语

本教程教会了我们集成检索和生成组件对于有效自然语言处理的重要性。我们对配置和优化每个组件以及了解它们在处理查询和生成响应中的作用有了深入的了解。

我们可以考虑扩展数据集以提高响应的多样性和质量，从而增强我们的系统。此外，集成更复杂的评估指标将提供对系统性能和相关性的更深入的了解。

---

原文链接：[How to build a Retrieval-Augmented Generation (RAG) system using Llama3, Ollama, DSPy, and Milvus](https://zilliz.com/learn/how-to-build-rag-system-using-llama3-ollama-dspy-milvus?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处