AutoAI RAG 实验编码 Python

查看指南和代码示例,了解如何使用向量存储数据库编码 AutoAI RAG 实验。 您可以通过 Milvus 或 Elasticsearch 向量存储使用以下步骤和代码示例。

对于带有 Milvus 矢量存储的企业或生产型 RAG 解决方案,可通过 Milvus 建立矢量数据库。 矢量化内容可持续用于未来的模式和集成。 有关详细信息,请参阅 Milvus。

有关使用 Milvus 向量存储编码 AutoAI RAG 实验的更多信息和代码示例,请参阅 Milvus 数据库自动运行 RAG 模式笔记本。

笔记本使用 watsonx.ai Python 客户端库 (版本 1.3.17 或更高版本)。

请按照以下步骤为您的使用案例编写 AutoAI RAG 实验代码。

  1. 准备数据的先决条件并设置实验
  2. 配置 RAG 实验
  3. 运行实验
  4. 查看图案并选择最佳图案
  5. 部署模式
  6. 清理(可选)

第 1 步:准备数据和建立实验的先决条件

准备好实验的前提条件。

在使用示例代码之前,您必须执行以下设置任务:

  • 联系Cloud Pak for Data管理员,向他们索要您的账户凭据
  1. 安装并导入所需的模块和依赖项。 例如:

    pip install wget
    pip install 'ibm-watsonx-ai[rag]>=1.3.17'
    
  2. 连接至 Watson Machine Learning。

    在IBM Cloud Pak for Data 上验证Watson Machine Learning服务。 您需要提供平台 "url、"username和 "api_key

    username = 'PASTE YOUR USERNAME HERE'
    api_key = 'PASTE YOUR API_KEY HERE'
    url = 'PASTE THE PLATFORM URL HERE'
    
  3. 使用此代码初始化客户端。 例如:

    from ibm_watsonx_ai import APIClient, Credentials
    
    credentials = Credentials(
        username = "username",
        api_key = "***********",
        url = "url",
        instance_id = "openshift"
    )
    
    client = APIClient(credentials)
    

    另外,您也可以使用 usernamepassword 来验证 Watson Machine Learning 服务。

    credentials = Credentials(
        username=***,
        password=***,
        url=***,
        instance_id="openshift"
    )
    
    client = APIClient(credentials)
    
  4. 为你的工作创造空间。 请参阅创建空间

  5. 设置默认空格:

    client.set.default_space("<Space GUID>")
    
  6. 准备接地文件。

  7. 准备评估数据。

接地文档

准备并连接用于运行 RAG 实验的接地文件。 有关详细信息,请参阅 在项目中获取和准备数据

  • 支持的格式:PDF、HTML、 DOCX、Markdown、纯文本
  • 连接到 Cloud Object Storage 存储桶、存储桶中的文件夹或指定多达 20 个文件中的数据。
  • AutoAI为运行实验提供文件样本

例如,当文档存储在 Cloud Object Storage 存储桶中时,创建数据连接:

from ibm_watsonx_ai.helpers import DataConnection, S3Location

datasource_name = 'bluemixcloudobjectstorage'

conn_meta_props= {
    client.connections.ConfigurationMetaNames.NAME: f"Connection to input data - {datasource_name} ",
    client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: client.connections.get_datasource_type_id_by_name(datasource_name),
    client.connections.ConfigurationMetaNames.DESCRIPTION: "ibm-watsonx-ai SDK documentation",
    client.connections.ConfigurationMetaNames.PROPERTIES: {
        'bucket': <BUCKET_NAME>,
        'access_key': <ACCESS_KEY>,
        'secret_key': <SECRET_ACCESS_KEY>,
        'iam_url': 'https://iam.cloud.ibm.com/identity/token',
        'url': <ENDPOINT_URL>
    }
}

conn_details = client.connections.create(meta_props=conn_meta_props)
cos_connection_id = client.connections.get_id(conn_details)

input_data_references = [
    DataConnection(
        connection_asset_id=cos_connection_id,
        location=S3Location(
            bucket=<BUCKET_NAME>,
            path=<BUCKET_PATH>
        )
    )
]

下面的示例演示了如何使用在项目中创建(或推广到空间)的数据资产:

注:

core_api.html 是示例笔记本中使用的基础文档文件的一个示例。

import os, wget
from ibm_watsonx_ai.helpers import DataConnection

input_data_filename = "core_api.html"
input_data_path = f"https://ibm.github.io/watsonx-ai-python-sdk/{input_data_filename}"

if not os.path.isfile(input_data_filename):
    wget.download(input_data_path, out=input_data_filename)

asset_details = client.data_assets.create(input_data_filename, input_data_filename)
asset_id = client.data_assets.get_id(asset_details)

input_data_references = [DataConnection(data_asset_id=asset_id)]
提示:

input_data_references 最多支持 20 个 DataConnection 实例。

求值数据

评估数据必须采用 JSON 格式,并具有包含这些字段的固定模式:question, correct_answer, correct_answer_document_ids

例如:

[
    {
        "question": "What is the purpose of get_token()?",
        "correct_answer": "get_token() is used to retrieve an authentication token for secure API access.",
        "correct_answer_document_ids": [
            "core_api.html"
        ]
    },
    {
        "question": "How does the delete_model() function operate?",
        "correct_answer": "delete_model() method allows users to delete models they've created or managed.",
        "correct_answer_document_ids": [
            "core_api.html"
        ]
    }
]

准备评估数据:

import os, wget
from ibm_watsonx_ai.helpers import DataConnection

test_data_filename = "benchmarking_data_core_api.json"
test_data_path = f"https://github.com/IBM/watsonx-ai-samples/tree/master/cloud/data/autoai_rag{test_data_filename}"

if not os.path.isfile(test_data_filename):
    wget.download(test_data_path, out=test_data_filename)

test_asset_details = client.data_assets.create(name=test_data_filename, file_path=test_data_filename)
test_asset_id = client.data_assets.get_id(test_asset_details)

test_data_references = [DataConnection(data_asset_id=test_asset_id)]

连接到 Milvus 矢量数据库

如果使用的是 Milvus 矢量数据库,请创建与矢量存储的连接。

注意 :如果您已经拥有 Milvus 连接,则无需创建连接。
from ibm_watsonx_ai.helpers import DataConnection

milvus_data_source_type_id = client.connections.get_datasource_type_uid_by_name("milvus")
details = client.connections.create(
    {
        client.connections.ConfigurationMetaNames.NAME: "Milvus Connection",
        client.connections.ConfigurationMetaNames.DATASOURCE_TYPE: milvus_data_source_type_id,
        client.connections.ConfigurationMetaNames.PROPERTIES: {
            "host": <PASTE MILVUS HOST HERE>,
            "port": <PASTE MILVUS PORT HERE>,
            "username": <PASTE MILVUS USERNAME HERE>,
            "password": <PASTE MILVUS PASSWORD HERE>,
            "ssl": True,
        },
    }
)

milvus_connection_id = client.connections.get_id(details)
vector_store_references = [DataConnection(connection_asset_id=milvus_connection_id)]

步骤 2:配置 RAG 优化器

rag_optimizer 对象提供了一套用于 AutoAI RAG 实验的方法。 在此步骤中,输入定义实验的详细信息。 有关可用的配置选项,请参阅实验设置的配置参数

下面的示例代码显示了使用 ibm-watsonx-ai SDK 文档运行实验的配置选项:

from ibm_watsonx_ai.experiment import AutoAI

experiment = AutoAI(credentials, project_id=project_id)

rag_optimizer = experiment.rag_optimizer(
    name='DEMO - AutoAI RAG ibm-watsonx-ai SDK documentation',
    description="AutoAI RAG experiment grounded with the ibm-watsonx-ai SDK documentation",
    max_number_of_rag_patterns=5,
    optimization_metrics=[AutoAI.RAGMetrics.ANSWER_CORRECTNESS]
)
提示:

您可以使用实验设置的配置参数中提供的支持值修改配置。

from ibm_watsonx_ai.foundation_models.schema import (
    AutoAIRAGModelConfig,
    AutoAIRAGModelParams,
)

parameters = AutoAIRAGModelParams(max_sequence_length=32_000)

foundation_model = AutoAIRAGModelConfig(
    model_id="ibm/granite-13b-instruct-v2",
    parameters=parameters,
    prompt_template_text="Answer my question {question} related to these documents {reference_documents}.",
    context_template_text="My document {document}",
    word_to_token_ratio=1.5,
)

chunking_config = {
    "method": "recursive",
    "chunk_size": 256,
    "chunk_overlap": 128,
}

rag_optimizer = experiment.rag_optimizer(
    name="DEMO - AutoAI RAG ibm-watsonx-ai SDK documentation",
    description="AutoAI RAG experiment grounded with the ibm-watsonx-ai SDK documentation",
    embedding_models=["ibm/slate-125m-english-rtrvr"],
    foundation_models=[
        "mistralai/mixtral-8x7b-instruct-v01",
        foundation_model,
    ],
    chunking=[chunking_config],
    max_number_of_rag_patterns=5,
    optimization_metrics=[AutoAI.RAGMetrics.ANSWER_CORRECTNESS]
)

步骤 3:运行实验

运行优化器,使用指定的配置选项创建 RAG 模式。 在本代码示例中,任务以交互模式运行。 将 background_mode 更改为 True,即可在后台运行任务。

run_details = rag_optimizer.run(
    input_data_references=input_data_references,
    test_data_references=test_data_references,
    vector_store_references=vector_store_references,
    background_mode=False
)

步骤 4:审查模式并选择最佳模式

AutoAIRAG 实验成功完成后,您可以查看模式。 使用 "summary方法以 PandasDataFrame的形式列出已完成的模式和评估指标信息,这样您就可以根据优化指标的性能排序来查看模式。

summary = rag_optimizer.summary()
summary

例如,模式结果显示如下:

模式 平均正确率 平均忠实度 平均语境正确性 chunking.chunk_size embeddings.model_id vector_store.distance_metric retrieval.method retrieval.number_of_chunks generation.model_id
Pattern1 0.6802 0.5407 1.0000 512 ibm/slate-125m-english-rtrvr 欧几里得 窗口 5 meta-llama/llama-3-70b-instruct
Pattern2 0.7172 0.5950 1.0000 1024 intfloat/multilingual-e5-large 欧几里得 窗口 5 ibm/granite-13b-chat-v2
Pattern3 0.6543 0.5144 1.0000 1024 intfloat/multilingual-e5-large 欧几里得 简式 5 ibm/granite-13b-chat-v2
Pattern4 0.6216 0.5030 1.0000 1024 intfloat/multilingual-e5-large 余弦 窗口 5 meta-llama/llama-3-70b-instruct
Pattern5 0.7369 0.5630 1.0000 1024 intfloat/multilingual-e5-large 余弦 窗口 3 mistralai/mixtral-8x7b-instruct-v01

选择一个模式进行本地测试

下一步是选择一种模式并在本地进行测试。

best_pattern = rag_optimizer.get_pattern()
from ibm_watsonx_ai.deployments import RuntimeContext

runtime_context = RuntimeContext(api_client=client)
inference_service = best_pattern.inference_service(runtime_context)[0]
question = "How to use new approach of providing credentials to APIClient?"

context = RuntimeContext(
    api_client=client,
    request_payload_json={"messages": [{"role": "user", "content": question}]},
)
print(inference_service(context)["body"]["choices"][0]["message"]["content"])

模特的回答:

According to the document, the new approach to provide credentials to APIClient is by using the Credentials class. Here's an example:


from ibm_watsonx_ai import APIClient
from ibm_watsonx_ai import Credentials

credentials = Credentials(
                   url = "https://us-south.ml.cloud.ibm.com",
                   token = "***********",
                  )

client = APIClient(credentials)


This replaces the old approach of passing a dictionary with credentials to the APIClient constructor.
提示:

要检索特定模式,请将模式名称传递给 rag_optimizer.get_pattern()

步骤 5:部署模式

在本地测试模式后,可以部署模式以获取端点并将其包含在应用程序中。 通过存储已定义的 RAG 功能,然后创建已部署资产来完成部署。 有关部署的更多信息,请参阅 部署和管理人工智能资产 在线部署

创建部署:

deployment_details = best_pattern.inference_service.deploy(
    name="AutoAI RAG deployment - ibm_watsonx_ai documentation",
    space_id=space_id,
    deploy_params={"tags": ["wx-autoai-rag"]}
)

读取已部署资产的部署 ID。

deployment_id = client.deployments.get_id(deployment_details)

RAG 服务现已部署到一个空间,可供测试。

测试已部署的模式

本代码示例演示了如何测试已部署的解决方案。 使用以下格式在有效载荷中输入测试问题:

payload = {
    "messages": [{"role": "user", "content": "How to use new approach of providing credentials to APIClient?"}]
}

score_response = client.deployments.run_ai_service(deployment_id, payload)
answer = score_response["choices"][0]["message"]["content"]
print(answer)

模特的回答:

According to the document, the new approach to provide credentials to APIClient is by using the Credentials class. Here's an example:


from ibm_watsonx_ai import APIClient
from ibm_watsonx_ai import Credentials

credentials = Credentials(
                   url = "https://us-south.ml.cloud.ibm.com",
                   token = "***********",
                  )

client = APIClient(credentials)


This replaces the old approach of passing a dictionary with credentials to the APIClient constructor.

获取推理和索引笔记本

要从服务处下载指定的推理笔记本,请使用 get_inference_notebook()。 如果将 pattern_name 留空,该方法将下载排名最高的模式的笔记本。

rag_optimizer.get_inference_notebook(pattern_name='Pattern3')

步骤 6:清理(可选)

如果您想从 Milvus 矢量数据库中删除您的收藏,请使用 Milvus 的 python SDK。

要查找集合名称,请访问模式详细信息 ,查看矢量存储索引名称

例如:

from pymilvus import MilvusClient

password = "<YOUR APIKEY>"
user = "ibmlhapikey"
uri = f"https://<HOST>:<PORT_NUMBER>"

collection_name = "autoai_rag_5c74df6a_20250319124623"

client = MilvusClient(uri=uri, password=password, user=milvus_credentials["username"])

client.drop_collection(collection_name=collection_name)

后续步骤

  • 使用新问题运行推理笔记本,以使用选定的 RAG 模式。
  • 使用 Prompt Lab 中来自该实验的索引文件,为基础模型提供基础提示。 请参阅使用 AutoAI 索引与文档进行聊天