0 / 0
영어 버전 문서로 돌아가기

AutoAI 의 RAG 실험을 Milvus 벡터 저장소로 코딩하기

마지막 업데이트 날짜: 2025년 3월 21일
AutoAI 의 RAG 실험을 Milvus 벡터 저장소로 코딩하기

AutoAI 의 RAG 실험을 벡터 저장소로 사용하는 Milvus 데이터베이스를 코딩하는 방법을 배우기 위해 가이드라인과 코드 샘플을 검토하십시오.

기업용 또는 생산용 RAG 솔루션의 경우, Milvus 를 사용하여 벡터 데이터베이스를 설정하십시오. 벡터화된 콘텐츠는 향후 패턴 및 통합을 위해 유지됩니다. 자세한 내용은 Milvus 로 작업하기를 참조하세요.

다음 섹션에서는 RAG 패턴 자동화( Milvus 데이터베이스 노트북을 이용한 RAG 패턴 자동화)에 제공된 주석이 달린 샘플 코드를 자세히 설명합니다.

노트북은 watsonx.ai Python 클라이언트 라이브러리(버전 1.1.11 이상)를 사용하며, 이 버전은 다음과 같습니다.

다음 단계에 따라 사용 사례에 맞는 AutoAI RAG 실험을 코딩하세요.

  1. 데이터 준비를 위한 전제 조건 준비 및 실험 설정
  2. RAG 실험 구성하기
  3. 실험 실행
  4. 패턴을 검토하고 가장 적합한 패턴을 선택하세요
  5. 패턴 배치
  6. 정리(선택 사항)

1단계: 데이터 준비 및 실험 설정을 위한 전제 조건 준비하기

실험을 위한 전제 조건을 준비합니다.

  • 필요한 모듈과 종속성을 설치하고 가져옵니다. 예를 들어,
pip install 'ibm-watsonx-ai[rag]>=1.1.11'
pip install langchain-community==0.2.4
from ibm_watsonx_ai import APIClient, Credentials

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

client = APIClient(credentials)
client.set.default_project("<Project ID>")
client.set.default_space("<Space GUID>")
  • 접지 문서 준비
  • 평가 데이터 준비

접지 문서

RAG 실험을 실행하는 데 사용할 접지 문서를 준비하고 연결합니다. 자세한 내용은 프로젝트에서 데이터 가져오기 및 준비하기를 참조하세요.

  • 지원되는 형식: PDF, HTML, DOCX, 마크다운, 일반 텍스트
  • Cloud Object Storage 버킷 또는 버킷의 폴더에 있는 데이터에 연결하거나 최대 20개의 파일을 지정할 수 있습니다.
  • AutoAI 실험 실행을 위한 문서를 샘플링합니다

예를 들어, 문서가 Cloud Object Storage 버킷에 저장되어 있을 때 데이터 연결을 만들려면 다음과 같이 하세요:

from ibm_watsonx_ai.helpers import DataConnection, S3Location

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=<BACKET_NAME>,
        path=<BACKET_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 실험으로 작업하기 위한 메서드 집합을 제공합니다. 이 단계에서는 실험을 정의하기 위해 세부 정보를 입력합니다. 사용 가능한 구성 옵션은 다음과 같습니다:

매개변수 설명
이름 올바른 이름 입력 실험 이름
설명 실험 설명 선택 사항으로 실험을 설명합니다
embedding_models 시도해 볼 모델 임베딩 ibm/slate-125m-english-rtrvr
intfloat/multilingual-e5-large
검색_방법 사용할 검색 방법 simple 모든 관련 문서 검색 및 순위 지정
window 정해진 수의 관련 문서 검색 및 순위 지정
기초_모델 시도해 볼 파운데이션 모델 작업별 기초 모델 보기
최대_개수_오브_래그_패턴 생성할 수 있는 최대 RAG 패턴 수 4-20
최적화_메트릭 최적화에 사용할 지표 이름 faithfulness
answer_correctness

다음 샘플 코드는 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]
)
Tip: 구성 표에 설명된 대로 지원되는 값을 사용하여 구성을 수정할 수 있습니다.
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=["ibm/granite-13b-chat-v2","mistralai/mixtral-8x7b-instruct-v01"],
    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단계: 패턴을 검토하고 가장 적합한 패턴을 선택합니다

AutoAI RAG 실험이 성공적으로 완료되면 패턴을 검토할 수 있습니다. ' summary ' 방법을 사용하면 완성된 패턴과 평가 지표 정보를 판다스 DataFrame 형태로 나열하여 최적화된 지표 대비 성능에 따라 순위가 매겨진 패턴을 검토할 수 있습니다.

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 유클리디안 Windows 5 meta-llama/llama-3-70b-instruct
Pattern2 0.7172 0.5950 1.0000 1024자입니다. intfloat/multilingual-e5-large 유클리디안 Windows 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 코사인 Windows 5 meta-llama/llama-3-70b-instruct
Pattern5 0.7369 0.5630 1.0000 1024자입니다. intfloat/multilingual-e5-large 코사인 Windows 3 mistralai/mixtral-8x7b-instruct-v01

로컬에서 테스트할 패턴 선택

다음 단계는 패턴을 선택하고 로컬에서 테스트하는 것입니다.

best_pattern = rag_optimizer.get_pattern()
payload = {
    client.deployments.ScoringMetaNames.INPUT_DATA: [
        {
            "values": ["How to use new approach of providing credentials to APIClient?"],
        }
    ]
}

resp = best_pattern.query(payload)
print(resp["predictions"][0]["values"][0][0])

모델의 반응:

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 함수를 저장한 다음 배포된 에셋을 생성하는 방식으로 이루어집니다. 배포에 대한 자세한 내용은 AI 자산 배포 및 관리온라인 배포를 참조하세요.

배포를 만들려면 다음과 같이 하세요:

deployment_details = best_pattern.deploy(
    name="AutoAI RAG deployment - ibm_watsonx_ai documentataion",
    space_id=space_id
)

배포된 자산의 배포 ID를 검색합니다.

deployment_id = client.deployments.get_id(deployment_details)
deployment_scoring_href = client.deployments.get_scoring_href(deployment_details)
print(deployment_scoring_href)

이제 RAG 서비스가 공간에 배포되어 테스트할 수 있습니다.

배포된 패턴 테스트

이 코드 샘플은 배포된 솔루션을 테스트하는 방법을 보여줍니다. 페이로드에 다음 형식을 사용하여 시험 문제를 입력합니다:

questions = ["How to use new approach of providing credentials to APIClient?"]

payload = {
    client.deployments.ScoringMetaNames.INPUT_DATA: [
        {
            "values": questions,
            "access_token": client.service_instance._get_token()
        }
    ]
}

resp = client.deployments.score(deployment_id, payload)
print(resp["predictions"][0]["values"][0][0])

모델의 반응:

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.

Cloud Object Storage.

실험의 최종 상태가 실패 또는 오류인 경우 rag_optimizer.get_logs()을 사용하거나 실험 결과를 참조하여 무엇이 잘못되었는지 파악합니다. 실험 결과와 로그는 계정에 연결된 기본 Cloud Object Storage 인스턴스에 저장됩니다. 기본적으로 결과는 실험 훈련 ID에 따라 default_autoai_rag_out 디렉토리에 저장됩니다.

결과는 패턴별로 정리됩니다. 예를 들어,

|-- Pattern1
|      | -- evaluation_results.json
|      | -- indexing_notebook.ipynb (Milvus)
|      | -- inference_notebook.ipynb (Milvus)
|-- Pattern2
|    ...
|-- training_status.json

각 패턴에는 이러한 결과가 포함되어 있습니다:

  • evaluation_results.json 파일에는 각 벤치마크 질문에 대한 평가 결과가 포함되어 있습니다.
  • indexing_notebook.ipynb에는 벡터 데이터베이스 인덱스를 구축하기 위한 파이썬 코드가 포함되어 있습니다. 데이터 검색, 청킹, 임베딩 생성을 위한 명령어를 소개합니다.
  • inference_notebook.ipynb 노트북은 사용자 쿼리에 대해 지식창고에서 관련 구절을 검색하고 검색된 구절을 대규모 언어 모델에 공급하여 응답을 생성하는 데 중점을 둡니다.

노트북을 검토하거나 인증 자격 증명을 추가해 노트북을 실행할 수 있습니다.

참고:

결과 indexing_notebook.ipynb 문서 임베딩 및 색인화 코드가 포함되어 있습니다. You can accelerate the document indexing task by changing vector_store.add_documents() to vector_store.add_documents_async().

추론 및 색인 노트북 가져오기

서비스에서 지정된 추론 노트북을 다운로드하려면 get_inference_notebook()을 사용하세요. pattern_name을 비워두면 메서드는 가장 높은 순위의 패턴에 대한 노트북을 다운로드합니다.

rag_optimizer.get_inference_notebook(pattern_name='Pattern3')

6단계: 정리(선택 사항)

Milvus 벡터 데이터베이스에서 컬렉션을 제거하려면 Milvus 에 대한 파이썬 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)

다음 단계

상위 주제: AutoAI SDK로 RAG 패턴 자동화하기