Codificação de um experimento AutoAI RAG com um modelo de fundação personalizado
Analise as diretrizes e os exemplos de código para saber como codificar um experimento AutoAI RAG e usar modelos de base personalizados.
A implementação do modelo personalizado usa a biblioteca do cliente watsonx.ai Python (versão 1.3.17 ou posterior).
Siga estas etapas para usar um modelo de fundação personalizado em seu experimento AutoAI RAG.
- Preparar os pré-requisitos para a implementação do modelo de fundação personalizado
- Implantar o modelo
- Preparar dados de aterramento
- Preparar dados de avaliação
- Execute o experimento
- Analise os padrões e selecione o melhor
Etapa 1: Prepare os pré-requisitos para a implementação do modelo de fundação personalizado
Faça o download do snapshot do modelo.
from pathlib import Path from huggingface_hub import snapshot_download byom_cache_dir = Path("your", "model", "cache", "dir") if not byom_cache_dir.exists(): raise FileExistsError("Please use the path which exists.") if byom_cache_dir.is_file(): raise NotADirectoryError("Please use the path which points to a directory.") snapshot_download(HUGGING_FACE_MODEL_REPOSITORY, cache_dir=byom_cache_dir)Use o código para inicializar o cliente. Por exemplo:
from ibm_watsonx_ai import APIClient, Credentials credentials = Credentials( url=URL, username=USERNAME, password=PASSWORD, instance_id=INSTANCE_ID, version=VERSION, verify=False, ) client = APIClient(credentials=credentials, project_id=PROJECT_ID)Conecte-se ao site S3Bucket.
from ibm_watsonx_ai.helpers.connections import DataConnection, S3Location location = S3Location(bucket=BUCKET_NAME, path=BUCKET_MODEL_DIR_NAME) data_connection = DataConnection(location=location, connection_asset_id=DATASOURCE_CONNECTION_ASSET_ID) data_connection.set_client(api_client=client)Faça upload de arquivos de modelo para o site S3Bucket.
model_files = byom_cache_dir / "model_dir_name" / "snapshots" / "snapshot_id" if not model_files.exists(): raise FileExistsError("Please use the snapshot path which exists.") if model_files.is_file(): raise NotADirectoryError("Please use the snapshot path which points to a directory.") for model_file in model_files.iterdir(): # avoid uploading unnecessary files if model_file.name.startswith("."): continue data_connection.write(data=str(model_file), remote_name=model_file.name)
Etapa 2: Implantar o modelo
Para implantar seu modelo de fundação personalizado, siga as etapas da documentação sobre modelos personalizados.
Etapa 3: Preparar dados de aterramento
Prepare e conecte os documentos de aterramento que você usará para executar o experimento RAG. Para obter detalhes, consulte Obtenção e preparação de dados em um projeto.
- Formatos compatíveis: PDF, HTML, DOCX, Markdown, texto simples
- Conecte-se a dados em um bucket Cloud Object Storage, a uma pasta em um bucket ou especifique até 20 arquivos.
- AutoAI usa amostra de documentos para executar o experimento
Por exemplo, para criar uma conexão de dados quando os documentos são armazenados em um bucket 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>
)
)
]
Etapa 4: Preparar dados de avaliação
Faça o download do documento
granite_code_models.pdf.import wget data_url = "https://arxiv.org/pdf/2405.04324" byom_input_filename = "granite_code_models.pdf" wget.download(data_url, byom_input_filename)Preparar os dados de avaliação.
Para
correct_answer_document_ids, forneça o nome do arquivo baixado.import json local_benchmark_json_filename = "benchmark.json" 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": [byom_input_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": [byom_input_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": [byom_input_filename] }, ] with open(local_benchmark_json_filename, mode="w", encoding="utf-8") as fp: json.dump(benchmarking_data, fp, indent=4)Faça upload dos arquivos de avaliação para seu bucket Cloud Object Storage.
documents_dir_location = S3Location(bucket=BUCKET_NAME, path=byom_input_filename) documents_dir_data_connection = DataConnection(location=documents_dir_location, connection_asset_id=DATASOURCE_CONNECTION_ASSET_ID) documents_dir_data_connection.set_client(api_client=client) documents_dir_data_connection.write(data=byom_input_filename, remote_name=byom_input_filename) benchmark_file_location = S3Location(bucket=BUCKET_NAME, path=BUCKET_BENCHMARK_JSON_FILE_PATH) benchmark_file_data_connection = DataConnection(location=benchmark_file_location, connection_asset_id=DATASOURCE_CONNECTION_ASSET_ID) benchmark_file_data_connection.set_client(api_client=client) benchmark_file_data_connection.write(data=local_benchmark_json_filename)
Etapa 5: Execute o experimento AutoAI RAG com o modelo de fundação personalizado
Execute o experimento com o Python SDK. Para deployment_id, forneça o ID do modelo de fundação personalizado implantado.
from ibm_watsonx_ai.experiment import AutoAI
from ibm_watsonx_ai.foundation_models.schema import (
AutoAIRAGCustomModelConfig,
AutoAIRAGModelParams
)
experiment = AutoAI(credentials, project_id=PROJECT_ID)
custom_prompt_template_text = "Answer my question {question} related to these documents {reference_documents}."
custom_context_template_text = "My document {document}"
parameters = AutoAIRAGModelParams(max_sequence_length=32_000)
custom_foundation_model = AutoAIRAGCustomModelConfig(
deployment_id=deployment_id,
project_id=PROJECT_ID,
prompt_template_text=custom_prompt_template_text,
context_template_text=custom_context_template_text,
parameters=parameters
)
rag_optimizer = experiment.rag_optimizer(
name='AutoAI RAG - Custom foundation model experiment',
description = "AutoAI RAG experiment with custom foundation model.",
max_number_of_rag_patterns=4,
optimization_metrics=['faithfulness'],
foundation_models=[custom_foundation_model],
)
rag_optimizer.run(
test_data_references=[benchmark_file_data_connection],
input_data_references=[documents_dir_data_connection],
)
Para obter detalhes da vaga, use:
rag_optimizer.get_details()
Quando o status estiver concluído, você poderá passar para a próxima etapa.
Etapa 6: Analise os padrões e selecione o melhor
Após a conclusão bem-sucedida do experimento AutoAI RAG, você poderá analisar os padrões. Use o método summary para listar padrões concluídos e informações de métricas de avaliação na forma de um Pandas DataFrame para que você possa analisar os padrões, classificados de acordo com o desempenho em relação à métrica otimizada.
summary = rag_optimizer.summary()
summary
Por exemplo, os resultados do padrão são exibidos da seguinte forma:
| Padrão | correção_de_resposta_média | fidelidade média | correção_do_contexto_médio | chunking.chunk_size | embeddings.model_id | vector_store.distance_metric | retrieval.method | retrieval.number_of_chunks | generation.deployment_id |
|---|---|---|---|---|---|---|---|---|---|
| Pattern1 | 0.6802 | 0.5407 | 1.0000 | 512 | ibm/slate-125m-english-rtrvr | euclidiano | janela | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
| Pattern2 | 0.7172 | 0.5950 | 1.0000 | 1024 | intfloat/multilingual-e5-large | euclidiano | janela | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
| Pattern3 | 0.6543 | 0.5144 | 1.0000 | 1024 | intfloat/multilingual-e5-large | euclidiano | simples | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
| Pattern4 | 0.6216 | 0.5030 | 1.0000 | 1024 | intfloat/multilingual-e5-large | cosseno | janela | 5 | 38aeef16-c69c-4858-ba69-42f97d965abc |
| Pattern5 | 0.7369 | 0.5630 | 1.0000 | 1024 | intfloat/multilingual-e5-large | cosseno | janela | 3 | 38aeef16-c69c-4858-ba69-42f97d965abc |
Selecione um padrão para testar localmente
Recrie o índice do documento antes de poder selecionar um padrão e testá-lo localmente.
Dica:No exemplo de código a seguir, o índice é criado com os documentos
core_api.htmlefm_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)Consultar o padrão RAG localmente.
from ibm_watsonx_ai.deployments import RuntimeContext runtime_context = RuntimeContext(api_client=client) inference_service_function = 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_function(context)["body"]["choices"][0]["message"]["content"])
A resposta do modelo é semelhante a esta:
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.
Para recuperar um padrão específico, passe o número do padrão para rag_optimizer.get_pattern().
Obter notebook de inferência e indexação
Para fazer download de um notebook de inferência específico, use o endereço get_inference_notebook(). Se você deixar o endereço pattern_name vazio, o método fará o download do notebook do melhor padrão calculado.
rag_optimizer.get_inference_notebook(pattern_name='Pattern3')
Para obter mais informações e exemplos de código, consulte o notebook Using AutoAI RAG with custom foundation model.