0 / 0
資料の 英語版 に戻る
AutoAI RAG実験のテキスト抽出のコーディング
最終更新: 2025年2月21日
AutoAI RAG実験のテキスト抽出のコーディング

ガイドラインとコードサンプルを確認し、 AutoAI RAG実験のコーディング方法を学びましょう。 watsonx テキスト抽出機能を使用して入力文書を処理します。

AutoAI RAG実験用の入力文書を処理するために、テキスト抽出機能を使用することができます。 テキスト抽出機能は、表、画像、図表を含む高品質なビジネス文書をマークダウン形式に変換します。 生成されたマークダウンファイルは、 AutoAI RAG実験で使用することで、生成されたパターンの品質を向上させることができます。

テキスト抽出サービスは 、 watsonx.ai Python クライアントライブラリ (バージョン 1.1.11 以降)を使用します。 watsonx.ai Python SDK からのテキスト抽出の使用方法の詳細については 、「テキスト抽出」 を参照してください。

AutoAI RAG 実験でテキスト抽出機能を使用するには、以下の手順に従ってください。

  1. データ準備の前提条件を整え、実験のセットアップを行う
  2. テキスト抽出を含む入力文書の処理
  3. RAGオプティマイザを設定する
  4. エクスペリメントの実行
  5. パターンを確認し、最適なものを選択してください。

ステップ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)
    
  • 作品用のプロジェクトやスペースを作成します。 プロジェクトの作成またはスペースの作成を参照してください。

  • プロジェクトまたはスペースのIDを取得します。 プロジェクトIDの確認を参照してください。

  • デフォルトのプロジェクトまたはスペースを設定する:

client.set.default_project("<Project ID>")
client.set.default_space("<Space GUID>")
  • グラウンディングを準備する
  • 評価データを準備する

グラウンディング

Prepare and connect to the grounding documents that you will use to run the AutoAI RAG experiment with the text extraction service.

  1. 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)
    
  2. 入力用とテキスト抽出サービス出力用の2つの資産を用意します。

    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形式でなければなりません。 questioncorrect_answercorrect_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: テキスト抽出機能で入力文書を処理する

  1. テキスト抽出サービスを初期化します。

    from ibm_watsonx_ai.foundation_models.extractions import TextExtractions
    
    extraction = TextExtractions(
        credentials=credentials,
        space_id=<Space GUID>,
    )
    
  2. テキスト抽出ジョブを実行します。

    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']
    
  3. 仕事の詳細を確認する。

    extraction.get_job_details(job_id)
    
  4. ステータスが completed の場合、次のステップに進みます。

ステップ3:RAGオプティマイザを設定する

rag_optimizer オブジェクトは、 AutoAI RAG実験で作業するための一連のメソッドを提供します。 このステップでは、実験を定義するための詳細を入力します。 利用可能な構成オプションは以下の通りです

パラメーター 説明
名前 有効な名前を入力してください 実験名
説明 エクスペリメントの説明 オプションとして実験について記述する
埋め込みモデル 試すためにモデルを埋め込む ibm/slate-125m-english-rtrvr
intfloat/multilingual-e5-large
retrieval_methods 使用する取得方法 simple すべての関連文書を取得し、ランク付けします。 関連文書を固定数取得し、ランク付けします。
window
foundation_models 試す基盤モデル 参照 タスク別基盤モデル
最大ラグランジュパターン数 作成するRAGパターンの最大数 4-20
optimization_metrics 最適化に使用するメトリック名 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 ユークリッド ウィンドウ 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

ローカルでテストするパターンを選択

次のステップは、パターンを選択し、ローカルでテストすることです。 Chromaはインメモリであるため、ドキュメントインデックスを再作成する必要があります。

ヒント:

次のコードサンプルでは、 core_api.htmlfm_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と watsonx のテキスト抽出サービスノートブックを参照してください。

親トピック: AutoAI SDK による RAG パターンの自動化