AutoAI 의 텍스트 추출 실험을 코딩하기
AutoAI 의 지침과 코드 샘플을 검토하여 watsonx 의 텍스트 추출 기능을 사용하여 입력 문서를 처리하는 실험을 코딩하는 방법을 알아보십시오.
AutoAI 텍스트 추출 기능을 사용하여 RAG 실험을 위한 입력 문서를 처리할 수 있습니다. 텍스트 추출 기능은 표, 이미지, 다이어그램이 포함된 고품질의 비즈니스 문서를 마크다운 형식으로 변환합니다. 그 결과로 만들어진 마크다운 파일은 생성된 패턴의 품질을 향상시키기 위해 RAG 실험( AutoAI )에서 사용될 수 있습니다.
텍스트 추출 서비스는 watsonx.ai Python 클라이언트 라이브러리 (버전 1.1.11 이상)를 사용합니다. watsonx.ai Python SDK의 텍스트 추출 기능 사용에 대한 자세한 정보는 텍스트 추출을 참조하십시오.
AutoAI 의 RAG 실험에서 텍스트 추출 기능을 사용하려면 다음 단계를 따르십시오.
- 데이터 준비를 위한 전제 조건을 준비하고 실험을 설정합니다
- 텍스트 추출 기능으로 입력 문서 처리
- RAG 최적화 프로그램 구성
- 실험 실행
- 패턴을 검토하고 가장 적합한 것을 선택하십시오
1단계: 데이터 준비를 위한 전제 조건을 준비하고 실험을 설정합니다
실험을 위한 전제 조건을 준비하십시오.
필요한 모듈과 의존성을 설치하고 가져옵니다. 예를 들어,
pip install 'ibm-watsonx-ai[rag]>=1.1.11' pip install langchain-community==0.2.4
- 작업 자격 증명을 추가합니다. 작업 자격 증명 추가하기를 참조하세요.
- watsonx.ai 런타임 서비스를 추가합니다. 서비스 만들기 참조.
- API 키를 입력하세요. 사용자 API 키 관리하기를 참조하십시오.
사용자 인증을 통해 클라이언트를 초기화하십시오. 예를 들어,
from ibm_watsonx_ai import APIClient, Credentials credentials = Credentials( url = "https://us-south.ml.cloud.mydomain.com", api_key = "***********" ) client = APIClient(credentials)
프로젝트 또는 스페이스의 ID를 확인하세요. 프로젝트 ID 찾기 참조.
기본 프로젝트 또는 공간 설정하기:
client.set.default_project("<Project ID>")
client.set.default_space("<Space GUID>")
- 기초 문서 준비
- 평가 데이터 준비
근거 문서
AutoAI 텍스트 추출 서비스를 이용해 RAG 실험을 실행하는 데 사용할 기초 문서를 준비하고 연결합니다.
Cloud Object Storage 에 연결하고 ID를 가져옵니다.
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)
두 개의 연결 자산을 준비합니다. 하나는 입력용이고, 다른 하나는 텍스트 추출 서비스 출력용입니다.
from ibm_watsonx_ai.helpers import DataConnection, S3Location input_data_reference = DataConnection( connection_asset_id=cos_connection_id, location=S3Location( bucket=<BUCKET_NAME>, path=<TEXT EXTRACTION INPUT FILENAME> ), ) input_data_reference.set_client(client) result_data_reference = DataConnection( connection_asset_id=cos_connection_id, location=S3Location( bucket=<BUCKET_NAME>, path=<TEXT EXTRACTION OUTPUT FILENAME> ) ) result_data_reference.set_client(client)
평가 데이터
평가 데이터 입력용:
- 데이터는 JSON 형식이어야 하며, 다음 필드가 포함된 고정된 스키마를 사용해야 합니다.
question
,correct_answer
,correct_answer_document_ids
correct_answer_document_ids
텍스트 추출 서비스 출력 파일을 참조해야 합니다
benchmarking_data = [
{
"question": "What are the two main variants of Granite Code models?",
"correct_answer": "The two main variants are Granite Code Base and Granite Code Instruct.",
"correct_answer_document_ids": <TEXT EXTRACTION OUTPUT FILENAME>
},
{
"question": "What is the purpose of Granite Code Instruct models?",
"correct_answer": "Granite Code Instruct models are finetuned for instruction-following tasks using datasets like CommitPack, OASST, HelpSteer, and synthetic code instruction datasets, aiming to improve reasoning and instruction-following capabilities.",
"correct_answer_document_ids": <TEXT EXTRACTION OUTPUT FILENAME>
},
{
"question": "What is the licensing model for Granite Code models?",
"correct_answer": "Granite Code models are released under the Apache 2.0 license, ensuring permissive and enterprise-friendly usage.",
"correct_answer_document_ids": <TEXT EXTRACTION OUTPUT FILENAME>
},
]
평가 데이터를 준비하려면:
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)]
2단계: 텍스트 추출 기능으로 입력된 문서 처리
텍스트 추출 서비스를 초기화합니다.
from ibm_watsonx_ai.foundation_models.extractions import TextExtractions extraction = TextExtractions( credentials=credentials, space_id=<Space GUID>, )
텍스트 추출 작업을 실행합니다.
from ibm_watsonx_ai.metanames import TextExtractionsMetaNames response = extraction.run_job( document_reference=input_data_reference, results_reference=result_data_reference, steps={ TextExtractionsMetaNames.OCR: { "process_image": True, "languages_list": ["en"], }, TextExtractionsMetaNames.TABLE_PROCESSING: {"enabled": True}, }, results_format="markdown", ) job_id = response['metadata']['id']
작업 세부 사항 확인하기.
extraction.get_job_details(job_id)
상태가
completed
이면 다음 단계로 넘어갑니다.
3단계: RAG 최적화 프로그램 구성
rag_optimizer
객체는 AutoAI RAG 실험을 위한 일련의 방법을 제공합니다. 이 단계에서는 실험을 정의하는 세부 사항을 입력합니다. 다음과 같은 구성 옵션을 사용할 수 있습니다:
매개변수 | 설명 | 값 |
---|---|---|
이름 | 올바른 이름 입력 | 실험 이름 |
설명 | 실험 설명 | 선택적으로 실험에 대한 설명 |
임베딩 모델 | 시도해 볼 모델 내장 | ibm/slate-125m-english-rtrvr intfloat/multilingual-e5-large |
검색 방법 | 사용할 검색 방법 | simple 모든 관련 문서를 검색하고 순위를 매깁니다 window 고정된 수의 관련 문서를 검색하고 순위를 매깁니다 |
foundation_models | 시도해 볼 수 있는 기초 모델 | 작업별 기초 모델 보기 |
최대 헝겊 패턴 수 | 만들 수 있는 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]
)
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]
)
4단계: 실험 실행
지정된 구성 옵션을 사용하여 최적화 프로그램을 실행하여 RAG 패턴을 만듭니다. 텍스트 추출의 결과를 AutoAI 의 RAG 실험에 입력으로 사용하십시오.
이 Chroma 실험을 실행하는 코드 샘플에서 작업은 대화형 모드로 실행됩니다. background_mode
를 True로 변경하면 백그라운드에서 작업을 실행할 수 있습니다.
input_data_references = [result_data_reference]
rag_optimizer.run(
input_data_references=input_data_references,
test_data_references=test_data_references,
background_mode=False
)
5단계: 패턴을 검토하고 가장 적합한 것을 선택합니다
AutoAI 의 RAG 실험이 성공적으로 완료되면, 그 패턴을 검토할 수 있습니다. summary
방법을 사용하여 완료된 패턴과 평가 지표 정보를 Pandas DataFrame 의 형태로 나열하면 최적화된 지표에 대한 성과에 따라 순위가 매겨진 패턴을 검토할 수 있습니다.
summary = rag_optimizer.summary()
summary
예를 들어, 패턴 결과는 다음과 같이 표시됩니다
패턴 | 정답률 | 성실성 | mean_context_correctness | 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 |
로컬에서 테스트할 패턴을 선택하세요
다음 단계는 패턴을 선택하고 로컬에서 테스트하는 것입니다. Chroma는 인메모리 방식이기 때문에 문서 색인을 다시 만들어야 합니다.
다음 코드 샘플에서 인덱스는 문서 core_api.html
와 fm_embeddings.html
로 구성됩니다.
from langchain_community.document_loaders import WebBaseLoader
best_pattern = rag_optimizer.get_pattern()
urls = [
"https://ibm.github.io/watsonx-ai-python-sdk/core_api.html",
"https://ibm.github.io/watsonx-ai-python-sdk/fm_embeddings.html",
]
docs_list = WebBaseLoader(urls).load()
doc_splits = best_pattern.chunker.split_documents(docs_list)
best_pattern.indexing_function(doc_splits)
RAG 패턴을 로컬로 쿼리합니다.
payload = {
client.deployments.ScoringMetaNames.INPUT_DATA: [
{
"values": ["How to use new approach of providing credentials to APIClient?"],
}
]
}
best_pattern.query(payload)
모델의 반응은 다음과 같습니다
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()
에 전달하십시오.
실험 결과를 검토하는 Cloud Object Storage
실험의 최종 상태가 실패 또는 오류인 경우, rag_optimizer.get_logs()
를 사용하거나 실험 결과를 참조하여 무엇이 잘못되었는지 파악하십시오. 실험 결과와 로그는 계정에 연결된 기본 Cloud Object Storage 인스턴스에 저장됩니다. 기본적으로 결과는 " default_autoai_rag_out
" 디렉토리에 저장됩니다.
결과는 패턴별로 정리됩니다. 예를 들어,
|-- Pattern1
| | -- evaluation_results.json
| | -- indexing_inference_notebook.ipynb (Chroma)
|-- Pattern2
| ...
|-- training_status.json
각 패턴에는 다음과 같은 결과가 포함됩니다
evaluation_results.json
파일에는 각 벤치마크 질문에 대한 평가 결과가 포함되어 있습니다.indexing_inference_notebook.ipynb
에는 벡터 데이터베이스 인덱스를 구축하고 검색 및 생성 기능을 구축하기 위한 Python 코드가 포함되어 있습니다. 이 노트북은 데이터 검색, 청크, 임베딩 생성, 청크 검색, 프롬프트 작성, 답변 생성을 위한 명령어를 소개합니다.
결과 노트북 indexing_notebook.ipynb
에는 문서를 삽입하고 색인하기 위한 코드가 포함되어 있습니다. vector_store.add_documents()
를 vector_store.add_documents_async()
로 변경하면 문서 색인 작업 속도를 높일 수 있습니다.
추론 및 색인 노트북 만들기
특정 추론 노트북을 다운로드하려면, get_inference_notebook()
를 이용하십시오. pattern_name
을 비워두면, 이 방법은 가장 잘 계산된 패턴의 노트북을 다운로드합니다.
rag_optimizer.get_inference_notebook(pattern_name='Pattern3')
더 많은 정보와 코드 샘플을 보려면 AutoAI 의 RAG with watsonx Text Extraction service notebook을 참고하세요.
상위 주제: RAG 패턴 검색 자동화