すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:ナレッジベース API

最終更新日:May 29, 2026

Alibaba Cloud Model Studio のナレッジベースは、既存の業務システムとの統合、運用の自動化、複雑な取得ニーズへの対応を可能にするオープン API を提供します。

前提条件

  1. API を使用してナレッジベースを管理するには、RAM ユーザーAPI 権限 (AliyunBailianDataFullAccess ポリシー) を取得し、ワークスペースに参加する必要があります。Alibaba Cloud アカウントの場合は不要です。

    RAM ユーザーは、参加しているワークスペース内のナレッジベースのみを管理できます。Alibaba Cloud アカウントは、すべてのワークスペース内のナレッジベースを管理できます。
  2. ナレッジベース API を呼び出すには、最新バージョンの Alibaba Cloud Model Studio SDK をインストールします。インストール手順については、Alibaba Cloud SDK Development Reference をご参照ください。

    SDK が要件を満たさない場合は、署名メカニズムを使用して HTTP リクエスト経由でナレッジベース API を呼び出すことができます。接続の詳細については、API 概要をご参照ください。
  3. AccessKey ID と AccessKey Secret および ワークスペース ID を取得します。サンプルコードを実行するために、これらをシステム環境変数として設定します。以下は Linux でこれらの変数を設定する方法の例です:

    IDE または他の開発プラグインを使用する場合、開発環境で ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET、および WORKSPACE_ID 変数を設定してください。
    export ALIBABA_CLOUD_ACCESS_KEY_ID='Your AccessKey ID'
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET='Your AccessKey Secret'
    export WORKSPACE_ID='Your Alibaba Cloud Model Studio workspace ID'
  4. ナレッジベースを作成するために、サンプルのナレッジドキュメント Alibaba Cloud Model Studio スマートフォンシリーズ紹介.docx を準備します。

サンプルコード

ナレッジベースの作成

重要
  • この例を呼び出す前に、前提条件を完了し、RAM ユーザーに AliyunBailianDataFullAccess ポリシーがあることを確認してください。

  • IDE または他の開発プラグインを使用する場合は、開発環境で ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET、および WORKSPACE_ID 環境変数を設定してください。

Python

# このサンプルコードは参照用です。本番環境では使用しないでください。
import hashlib
import os
import time

import requests
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models


def check_environment_variables():
    """必要な環境変数が設定されていることを確認します。"""
    required_vars = {
        'ALIBABA_CLOUD_ACCESS_KEY_ID': 'Alibaba Cloud AccessKey ID',
        'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'Alibaba Cloud AccessKey Secret',
        'WORKSPACE_ID': 'Alibaba Cloud Model Studio workspace ID'
    }
    missing_vars = []
    for var, description in required_vars.items():
        if not os.environ.get(var):
            missing_vars.append(var)
            print(f"エラー: {var} 環境変数を設定してください ({description})。")
    
    return len(missing_vars) == 0


def calculate_md5(file_path: str) -> str:
    """
    ファイルの MD5 ハッシュを計算します。

    Args:
        file_path (str): ファイルのローカルパス。

    Returns:
        str: ファイルの MD5 ハッシュ。
    """
    md5_hash = hashlib.md5()

    # ファイルをバイナリモードで読み込みます。
    with open(file_path, "rb") as f:
        # 大きなファイルを処理する際にメモリを節約するために、ファイルをチャンクで読み込みます。
        for chunk in iter(lambda: f.read(4096), b""):
            md5_hash.update(chunk)

    return md5_hash.hexdigest()


def get_file_size(file_path: str) -> int:
    """
    ファイルのサイズをバイト単位で返します。
    Args:
        file_path (str): ファイルのローカルパス。
    Returns:
        int: ファイルサイズ (バイト単位)。
    """
    return os.path.getsize(file_path)


# クライアントを初期化します。
def create_client() -> bailian20231229Client:
    """
    クライアントを作成して設定します。

    Returns:
        bailian20231229Client: 設定済みのクライアント。
    """
    config = open_api_models.Config(
        access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
    # このエンドポイントはアジアパシフィック SE 1 (シンガポール) リージョン用です。別のリージョンを使用する場合は変更してください。
    config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
    return bailian20231229Client(config)


# ファイルアップロードリースをリクエストします。
def apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id):
    """
    Model Studio サービスからファイルアップロードリースをリクエストします。

    Args:
        client (bailian20231229Client): クライアント。
        category_id (str): カテゴリ ID。
        file_name (str): ファイル名。
        file_md5 (str): ファイルの MD5 ハッシュ。
        file_size (int): ファイルサイズ (バイト単位)。
        workspace_id (str): ワークスペース ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    request = bailian_20231229_models.ApplyFileUploadLeaseRequest(
        file_name=file_name,
        md_5=file_md5,
        size_in_bytes=file_size,
    )
    runtime = util_models.RuntimeOptions()
    return client.apply_file_upload_lease_with_options(category_id, workspace_id, request, headers, runtime)


# ファイルを一時ストレージにアップロードします。
def upload_file(pre_signed_url, headers, file_path):
    """
    アップロードリースから取得した署名付き URL にファイルをアップロードします。
    Args:
        pre_signed_url (str): アップロードリースからの URL。
        headers (dict): アップロード用のリクエストヘッダー。
        file_path (str): ファイルのローカルパス。
    """
    with open(file_path, 'rb') as f:
        file_content = f.read()
    upload_headers = {
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type": headers["Content-Type"]
    }
    response = requests.put(pre_signed_url, data=file_content, headers=upload_headers)
    response.raise_for_status()


# ファイルをカテゴリに追加します。
def add_file(client: bailian20231229Client, lease_id: str, parser: str, category_id: str, workspace_id: str):
    """
    Model Studio サービスの指定されたカテゴリにファイルを追加します。

    Args:
        client (bailian20231229Client): クライアント。
        lease_id (str): リース ID。
        parser (str): ファイルのパーサー。
        category_id (str): カテゴリ ID。
        workspace_id (str): ワークスペース ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    request = bailian_20231229_models.AddFileRequest(
        lease_id=lease_id,
        parser=parser,
        category_id=category_id,
    )
    runtime = util_models.RuntimeOptions()
    return client.add_file_with_options(workspace_id, request, headers, runtime)


# ファイルの解析ステータスをクエリします。
def describe_file(client, workspace_id, file_id):
    """
    ファイルに関する基本情報を取得します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        file_id (str): ファイル ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    runtime = util_models.RuntimeOptions()
    return client.describe_file_with_options(workspace_id, file_id, headers, runtime)


# ナレッジベース (インデックス) を初期化します。
def create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type):
    """
    Model Studio サービスでナレッジベースを作成します (インデックスを初期化します)。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        file_id (str): ファイル ID。
        name (str): ナレッジベースの名前。
        structure_type (str): ナレッジベースのデータの型。
        source_type (str): データソースのタイプ。例えば、このスクリプトでは 'DATA_CENTER_FILE' を使用します。
        sink_type (str): ナレッジベースのベクターストレージタイプ。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    request = bailian_20231229_models.CreateIndexRequest(
        structure_type=structure_type,
        name=name,
        source_type=source_type,
        sink_type=sink_type,
        document_ids=[file_id]
    )
    runtime = util_models.RuntimeOptions()
    return client.create_index_with_options(workspace_id, request, headers, runtime)


# インデックス作成タスクを送信します。
def submit_index(client, workspace_id, index_id):
    """
    Model Studio サービスにインデックス作成タスクを送信します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    submit_index_job_request = bailian_20231229_models.SubmitIndexJobRequest(
        index_id=index_id
    )
    runtime = util_models.RuntimeOptions()
    return client.submit_index_job_with_options(workspace_id, submit_index_job_request, headers, runtime)


# インデックス作成タスクのステータスを取得します。
def get_index_job_status(client, workspace_id, job_id, index_id):
    """
    インデックス作成タスクのステータスをクエリします。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        job_id (str): インデックス作成タスクの ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
        index_id=index_id,
        job_id=job_id
    )
    runtime = util_models.RuntimeOptions()
    return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)


def create_knowledge_base(
        file_path: str,
        workspace_id: str,
        name: str
):
    """
    Model Studio でナレッジベースを作成します。
    Args:
        file_path (str): ファイルのローカルパス。
        workspace_id (str): ワークスペース ID。
        name (str): ナレッジベースの名前。
    Returns:
        str or None: 成功した場合はナレッジベース ID、失敗した場合は None。
    """
    # デフォルト値を設定します。
    category_id = 'default'
    parser = 'DASHSCOPE_DOCMIND'
    source_type = 'DATA_CENTER_FILE'
    structure_type = 'unstructured'
    sink_type = 'DEFAULT'
    try:
        # ステップ 1: クライアントを初期化します...
        print("ステップ 1: クライアントを初期化しています...")
        client = create_client()
        # ステップ 2: ファイル情報を準備します...
        print("ステップ 2: ファイル情報を準備しています...")
        file_name = os.path.basename(file_path)
        file_md5 = calculate_md5(file_path)
        file_size = get_file_size(file_path)
        # ステップ 3: Model Studio からアップロードリースをリクエストします...
        print("ステップ 3: Model Studio からアップロードリースをリクエストしています...")
        lease_response = apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id)
        lease_id = lease_response.body.data.file_upload_lease_id
        upload_url = lease_response.body.data.param.url
        upload_headers = lease_response.body.data.param.headers
        # ステップ 4: ファイルを Model Studio にアップロードします...
        print("ステップ 4: ファイルを Model Studio にアップロードしています...")
        upload_file(upload_url, upload_headers, file_path)
        # ステップ 5: ファイルを Model Studio に追加します...
        print("ステップ 5: ファイルを Model Studio に追加しています...")
        add_response = add_file(client, lease_id, parser, category_id, workspace_id)
        file_id = add_response.body.data.file_id
        # ステップ 6: Model Studio でファイルステータスを確認します...
        print("ステップ 6: Model Studio でファイルステータスを確認しています...")
        while True:
            describe_response = describe_file(client, workspace_id, file_id)
            status = describe_response.body.data.status
            print(f"現在のファイルステータス: {status}")
            if status == 'INIT':
                print("ファイルは解析待ちです。お待ちください...")
            elif status == 'PARSING':
                print("ファイルは解析中です。お待ちください...")
            elif status == 'PARSE_SUCCESS':
                print("ファイルは正常に解析されました!")
                break
            else:
                print(f"不明なファイルステータス: {status}。テクニカルサポートにお問い合わせください。")
                return None
            time.sleep(5)
        # ステップ 7: Model Studio でナレッジベースを初期化します...
        print("ステップ 7: Model Studio でナレッジベースを初期化しています...")
        index_response = create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type)
        index_id = index_response.body.data.id
        # ステップ 8: インデックス作成タスクを Model Studio に送信します...
        print("ステップ 8: インデックス作成タスクを Model Studio に送信しています...")
        submit_response = submit_index(client, workspace_id, index_id)
        job_id = submit_response.body.data.id
        # ステップ 9: Model Studio からインデックス作成タスクのステータスを取得します...
        print("ステップ 9: Model Studio からインデックス作成タスクのステータスを取得しています...")
        while True:
            get_index_job_status_response = get_index_job_status(client, workspace_id, job_id, index_id)
            status = get_index_job_status_response.body.data.status
            print(f"現在のインデックス作成タスクのステータス: {status}")
            if status == 'COMPLETED':
                break
            time.sleep(5)
        print("Model Studio ナレッジベースが正常に作成されました!")
        return index_id
    except Exception as e:
        print(f"エラーが発生しました: {e}")
        return None


def main():
    if not check_environment_variables():
        print("環境変数チェックに失敗しました。")
        return
    file_path = input("アップロードするファイルのローカルパスを入力してください (例: /path/to/file.docx): ")
    kb_name = input("ナレッジベースの名前を入力してください: ")
    workspace_id = os.environ.get('WORKSPACE_ID')
    create_knowledge_base(file_path, workspace_id, kb_name)


if __name__ == '__main__':
    main()

Java

// このサンプルコードは参照用です。本番環境では使用しないでください。
import com.aliyun.bailian20231229.models.*;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class KnowledgeBaseCreate {

    /**
     * 必要な環境変数を確認し、不足しているものがあればプロンプトを表示します。
     *
     * @return 必要な環境変数がすべて設定されていれば true、そうでなければ false。
     */
    public static boolean checkEnvironmentVariables() {
        Map<String, String> requiredVars = new HashMap<>();
        requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_ID", "Alibaba Cloud AccessKey ID");
        requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "Alibaba Cloud AccessKey secret");
        requiredVars.put("WORKSPACE_ID", "Alibaba Cloud Model Studio workspace ID");

        List<String> missingVars = new ArrayList<>();
        for (Map.Entry<String, String> entry : requiredVars.entrySet()) {
            String value = System.getenv(entry.getKey());
            if (value == null || value.isEmpty()) {
                missingVars.add(entry.getKey());
                System.out.println("エラー: " + entry.getKey() + " 環境変数を設定してください (" + entry.getValue() + ")");
            }
        }

        return missingVars.isEmpty();
    }

    /**
     * ファイルの MD5 ハッシュを計算します。
     *
     * @param filePath ファイルのローカルパス。
     * @return ファイルの MD5 ハッシュ。
     * @throws Exception エラーが発生した場合。
     */
    public static String calculateMD5(String filePath) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : md.digest()) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }

    /**
     * ファイルサイズをバイト単位で取得します。
     *
     * @param filePath ファイルのローカルパス。
     * @return ファイルサイズ (バイト単位)。
     */
    public static String getFileSize(String filePath) {
        File file = new File(filePath);
        long fileSize = file.length();
        return String.valueOf(fileSize);
    }

    /**
     * クライアントを初期化します。
     *
     * @return 設定済みのクライアントオブジェクト。
     */
    public static com.aliyun.bailian20231229.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // 以下のエンドポイントはパブリッククラウドのエンドポイントです。必要に応じて変更できます。
        config.endpoint = "bailian.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.bailian20231229.Client(config);
    }

    /**
     * ファイルアップロードリースをリクエストします。
     *
     * @param client      クライアントオブジェクト。
     * @param categoryId  カテゴリ ID。
     * @param fileName    ファイル名。
     * @param fileMd5     ファイルの MD5 ハッシュ。
     * @param fileSize    ファイルサイズ (バイト単位)。
     * @param workspaceId ワークスペース ID。
     * @return Alibaba Cloud Model Studio からのレスポンス。
     */
    public static ApplyFileUploadLeaseResponse applyLease(com.aliyun.bailian20231229.Client client, String categoryId, String fileName, String fileMd5, String fileSize, String workspaceId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = new com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest();
        applyFileUploadLeaseRequest.setFileName(fileName);
        applyFileUploadLeaseRequest.setMd5(fileMd5);
        applyFileUploadLeaseRequest.setSizeInBytes(fileSize);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        ApplyFileUploadLeaseResponse applyFileUploadLeaseResponse = null;
        applyFileUploadLeaseResponse = client.applyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
        return applyFileUploadLeaseResponse;
    }

    /**
     * ファイルを一時ストレージにアップロードします。
     *
     * @param preSignedUrl アップロードリースからの URL。
     * @param headers      アップロード用のリクエストヘッダー。
     * @param filePath     ファイルのローカルパス。
     * @throws Exception エラーが発生した場合。
     */
    public static void uploadFile(String preSignedUrl, Map<String, String> headers, String filePath) throws Exception {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IllegalArgumentException("ファイルが存在しないか、通常のファイルではありません: " + filePath);
        }

        try (FileInputStream fis = new FileInputStream(file)) {
            URL url = new URL(preSignedUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("PUT");
            conn.setDoOutput(true);

            // アップロードリクエストヘッダーを設定します。
            conn.setRequestProperty("X-bailian-extra", headers.get("X-bailian-extra"));
            conn.setRequestProperty("Content-Type", headers.get("Content-Type"));

            // ファイルをチャンクで読み込んでアップロードします。
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                conn.getOutputStream().write(buffer, 0, bytesRead);
            }

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("アップロードに失敗しました: " + responseCode);
            }
        }
    }

    /**
     * ファイルをカテゴリに追加します。
     *
     * @param client      クライアントオブジェクト。
     * @param leaseId     リース ID。
     * @param parser      ファイルパーサー。
     * @param categoryId  カテゴリ ID。
     * @param workspaceId ワークスペース ID。
     * @return Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static AddFileResponse addFile(com.aliyun.bailian20231229.Client client, String leaseId, String parser, String categoryId, String workspaceId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.AddFileRequest addFileRequest = new com.aliyun.bailian20231229.models.AddFileRequest();
        addFileRequest.setLeaseId(leaseId);
        addFileRequest.setParser(parser);
        addFileRequest.setCategoryId(categoryId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.addFileWithOptions(workspaceId, addFileRequest, headers, runtime);
    }

    /**
     * ファイルに関する情報を取得します。
     *
     * @param client      クライアントオブジェクト。
     * @param workspaceId ワークスペース ID。
     * @param fileId      ファイル ID。
     * @return Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static DescribeFileResponse describeFile(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
    }

    /**
     * Alibaba Cloud Model Studio でナレッジベースを作成します (インデックスを初期化します)。
     *
     * @param client        クライアントオブジェクト。
     * @param workspaceId   ワークスペース ID。
     * @param fileId        ファイル ID。
     * @param name          ナレッジベース名。
     * @param structureType ナレッジベースのデータ構造。
     * @param sourceType    データソースのタイプ。カテゴリとファイルがサポートされています。
     * @param sinkType      ナレッジベースのベクターストレージタイプ。
     * @return Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static CreateIndexResponse createIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId, String name, String structureType, String sourceType, String sinkType) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.CreateIndexRequest createIndexRequest = new com.aliyun.bailian20231229.models.CreateIndexRequest();
        createIndexRequest.setStructureType(structureType);
        createIndexRequest.setName(name);
        createIndexRequest.setSourceType(sourceType);
        createIndexRequest.setSinkType(sinkType);
        createIndexRequest.setDocumentIds(Collections.singletonList(fileId));
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.createIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
    }

    /**
     * Alibaba Cloud Model Studio にインデックス作成タスクを送信します。
     *
     * @param client      クライアントオブジェクト。
     * @param workspaceId ワークスペース ID。
     * @param indexId     ナレッジベース ID。
     * @return Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static SubmitIndexJobResponse submitIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.SubmitIndexJobRequest submitIndexJobRequest = new com.aliyun.bailian20231229.models.SubmitIndexJobRequest();
        submitIndexJobRequest.setIndexId(indexId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.submitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
    }

    /**
     * インデックス作成タスクのステータスを取得します。
     *
     * @param client      クライアントオブジェクト。
     * @param workspaceId ワークスペース ID。
     * @param jobId       タスク ID。
     * @param indexId     ナレッジベース ID。
     * @return Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest();
        getIndexJobStatusRequest.setIndexId(indexId);
        getIndexJobStatusRequest.setJobId(jobId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        GetIndexJobStatusResponse getIndexJobStatusResponse = null;
        getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
        return getIndexJobStatusResponse;
    }

    /**
     * Alibaba Cloud Model Studio でナレッジベースを作成します。
     *
     * @param filePath    ファイルのローカルパス。
     * @param workspaceId ワークスペース ID。
     * @param name        ナレッジベース名。
     * @return 成功した場合はナレッジベース ID、それ以外の場合は null。
     */
    public static String createKnowledgeBase(String filePath, String workspaceId, String name) {
        // デフォルト値を設定します。
        String categoryId = "default";
        String parser = "DASHSCOPE_DOCMIND";
        String sourceType = "DATA_CENTER_FILE";
        String structureType = "unstructured";
        String sinkType = "DEFAULT";
        try {
            // ステップ 1: クライアントを初期化します。
            System.out.println("ステップ 1: クライアントを初期化しています。");
            com.aliyun.bailian20231229.Client client = createClient();

            // ステップ 2: ファイル情報を準備します。
            System.out.println("ステップ 2: ファイル情報を準備しています。");
            String fileName = new File(filePath).getName();
            String fileMd5 = calculateMD5(filePath);
            String fileSize = getFileSize(filePath);

            // ステップ 3: Alibaba Cloud Model Studio からアップロードリースをリクエストします。
            System.out.println("ステップ 3: Alibaba Cloud Model Studio からアップロードリースをリクエストしています。");
            ApplyFileUploadLeaseResponse leaseResponse = applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
            String leaseId = leaseResponse.getBody().getData().getFileUploadLeaseId();
            String uploadUrl = leaseResponse.getBody().getData().getParam().getUrl();
            Object uploadHeaders = leaseResponse.getBody().getData().getParam().getHeaders();

            // ステップ 4: ファイルを Alibaba Cloud Model Studio にアップロードします。
            System.out.println("ステップ 4: ファイルを Alibaba Cloud Model Studio にアップロードしています。");
            // jackson-databind 依存関係が必要です。
            // 前のステップの uploadHeaders を Map (キーと値のペア) に変換します。
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> uploadHeadersMap = (Map<String, String>) mapper.readValue(mapper.writeValueAsString(uploadHeaders), Map.class);
            uploadFile(uploadUrl, uploadHeadersMap, filePath);

            // ステップ 5: ファイルを Alibaba Cloud Model Studio サーバーに追加します。
            System.out.println("ステップ 5: ファイルを Alibaba Cloud Model Studio サーバーに追加しています。");
            AddFileResponse addResponse = addFile(client, leaseId, parser, categoryId, workspaceId);
            String fileId = addResponse.getBody().getData().getFileId();

            // ステップ 6: Alibaba Cloud Model Studio でファイルステータスを確認します。
            System.out.println("ステップ 6: Alibaba Cloud Model Studio でファイルステータスを確認しています。");
            while (true) {
                DescribeFileResponse describeResponse = describeFile(client, workspaceId, fileId);
                String status = describeResponse.getBody().getData().getStatus();
                System.out.println("現在のファイルステータス: " + status);

                if (status.equals("INIT")) {
                    System.out.println("ファイルは解析待ちです。");
                } else if (status.equals("PARSING")) {
                    System.out.println("ファイルは解析中です。");
                } else if (status.equals("PARSE_SUCCESS")) {
                    System.out.println("ファイルは正常に解析されました。");
                    break;
                } else {
                    System.out.println("不明なファイルステータス: " + status + "。テクニカルサポートにお問い合わせください。");
                    return null;
                }
                TimeUnit.SECONDS.sleep(5);
            }

            // ステップ 7: Alibaba Cloud Model Studio でナレッジベースを作成します。
            System.out.println("ステップ 7: Alibaba Cloud Model Studio でナレッジベースを作成しています。");
            CreateIndexResponse indexResponse = createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType);
            String indexId = indexResponse.getBody().getData().getId();

            // ステップ 8: Alibaba Cloud Model Studio にインデックス作成タスクを送信します。
            System.out.println("ステップ 8: Alibaba Cloud Model Studio にインデックス作成タスクを送信しています。");
            SubmitIndexJobResponse submitResponse = submitIndex(client, workspaceId, indexId);
            String jobId = submitResponse.getBody().getData().getId();

            // ステップ 9: Alibaba Cloud Model Studio からインデックス作成タスクのステータスを取得します。
            System.out.println("ステップ 9: Alibaba Cloud Model Studio からインデックス作成タスクのステータスを取得しています。");
            while (true) {
                GetIndexJobStatusResponse getStatusResponse = getIndexJobStatus(client, workspaceId, jobId, indexId);
                String status = getStatusResponse.getBody().getData().getStatus();
                System.out.println("現在のインデックス作成タスクのステータス: " + status);

                if (status.equals("COMPLETED")) {
                    break;
                }
                TimeUnit.SECONDS.sleep(5);
            }

            System.out.println("ナレッジベースは正常に作成されました。");
            return indexId;

        } catch (Exception e) {
            System.out.println("エラーが発生しました: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * アプリケーションのメインエントリポイント。
     */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        if (!checkEnvironmentVariables()) {
            return;
        }

        System.out.print("アップロードするファイルのローカルパスを入力してください。例: Linux の場合 /xxx/xxx/Alibaba_Cloud_Model_Studio_Phone_Series_Introduction.docx:");
        String filePath = scanner.nextLine();

        System.out.print("ナレッジベースの名前を入力してください: ");
        String kbName = scanner.nextLine();

        String workspaceId = System.getenv("WORKSPACE_ID");
        String result = createKnowledgeBase(filePath, workspaceId, kbName);
        if (result != null) {
            System.out.println("ナレッジベース ID: " + result);
        }
    }
}

PHP

<?php
// このサンプルコードは参照用です。本番環境では使用しないでください。
namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\SDK\Bailian\V20231229\Bailian;
use AlibabaCloud\SDK\Bailian\V20231229\Models\AddFileRequest;
use \Exception;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Bailian\V20231229\Models\ApplyFileUploadLeaseRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\CreateIndexRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\SubmitIndexJobRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\GetIndexJobStatusRequest;

class KnowledgeBaseCreate {

    /**
    * 必要な環境変数をチェックし、設定を促します。
    *
    * @return bool 必要な環境変数がすべて設定されていれば true、そうでなければ false。
    */
    public static function checkEnvironmentVariables() {
        $requiredVars = [
            'ALIBABA_CLOUD_ACCESS_KEY_ID' => 'Alibaba Cloud AccessKey ID',
            'ALIBABA_CLOUD_ACCESS_KEY_SECRET' => 'Alibaba Cloud AccessKey secret',
            'WORKSPACE_ID' => 'Alibaba Cloud Model Studio workspace ID'
        ];
        $missingVars = [];
        foreach ($requiredVars as $var => $description) {
            if (!getenv($var)) {
                $missingVars[] = $var;
                echo "エラー: $var 環境変数を設定してください ($description)\n";
            }
        }
        return count($missingVars) === 0;
    }

    /**
     * ファイルの MD5 ハッシュを計算します。
     *
     * @param string $filePath ファイルのローカルパス。
     * @return string ファイルの MD5 ハッシュ。
     */
    public static function calculateMd5($filePath) {
        $md5Hash = hash_init("md5");
        $handle = fopen($filePath, "rb");
        while (!feof($handle)) {
            $chunk = fread($handle, 4096);
            hash_update($md5Hash, $chunk);
        }
        fclose($handle);
        return hash_final($md5Hash);
    }

    /**
     * ファイルサイズをバイト単位で取得します。
     *
     * @param string $filePath ファイルのローカルパス。
     * @return int ファイルサイズ (バイト単位)。
     */
    public static function getFileSize($filePath) {
        return (string)filesize($filePath);
    }

    /**
     * クライアントを初期化します。
     *
     * @return Bailian 設定済みのクライアントオブジェクト。
     */
    public static function createClient(){
        $config = new Config([
            "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
            "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        ]);
        // 以下のエンドポイントはパブリッククラウド用です。必要に応じて変更できます。
        $config->endpoint = 'bailian.ap-southeast-1.aliyuncs.com';
        return new Bailian($config);
    }

    /**
     * ファイルアップロードリースを申請します。
     *
     * @param Bailian $client クライアント。
     * @param string $categoryId カテゴリ ID。
     * @param string $fileName ファイル名。
     * @param string $fileMd5 ファイルの MD5 ハッシュ。
     * @param int $fileSize ファイルサイズ (バイト単位)。
     * @param string $workspaceId ワークスペース ID。
     * @return ApplyFileUploadLeaseResponse サービスからのレスポンス。
     */
    public static function applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId) {
        $headers = [];
        $applyFileUploadLeaseRequest = new ApplyFileUploadLeaseRequest([
            "fileName" => $fileName,
            "md5" => $fileMd5,
            "sizeInBytes" => $fileSize
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->applyFileUploadLeaseWithOptions($categoryId, $workspaceId, $applyFileUploadLeaseRequest, $headers, $runtime);
    }

    /**
     * ファイルを一時ストレージにアップロードします。
    *
    * @param string $preSignedUrl アップロードリースからの URL。
    * @param array $headers アップロード用のリクエストヘッダー。
    * @param string $filePath ファイルのローカルパス。
    */
    public static function uploadFile($preSignedUrl, $headers, $filePath) {
        $fileContent = file_get_contents($filePath);
        // アップロードリクエストヘッダーを設定します。
        $uploadHeaders = [
            "X-bailian-extra" => $headers["X-bailian-extra"],
            "Content-Type" => $headers["Content-Type"]
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function($key, $value) {
            return "$key: $value";
        }, array_keys($uploadHeaders), $uploadHeaders));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            throw new Exception("アップロードに失敗しました: " . curl_error($ch));
        }
        curl_close($ch);
    }

    /**
     * ファイルをカテゴリに追加します。
     *
     * @param Bailian $client クライアント。
     * @param string $leaseId リース ID。
     * @param string $parser ファイルのパーサー。
     * @param string $categoryId カテゴリ ID。
     * @param string $workspaceId ワークスペース ID。
     * @return AddFileResponse サービスからのレスポンス。
     */
    public static function addFile($client, $leaseId, $parser, $categoryId, $workspaceId) {
        $headers = [];
        $addFileRequest = new AddFileRequest([
            "leaseId" => $leaseId,
            "parser" => $parser,
            "categoryId" => $categoryId
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->addFileWithOptions($workspaceId, $addFileRequest, $headers, $runtime);
    }

    /**
     * ファイルの基本情報を取得します。
     *
     * @param Bailian $client クライアント。
     * @param string $workspaceId ワークスペース ID。
     * @param string $fileId ファイル ID。
     * @return DescribeFileResponse サービスからのレスポンス。
     */
    public static function describeFile($client, $workspaceId, $fileId) {
        $headers = [];
        $runtime = new RuntimeOptions([]);
        return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
    }

    /**
     * ナレッジベースを作成します (インデックスを初期化します)。
     *
     * @param Bailian $client クライアント。
     * @param string $workspaceId ワークスペース ID。
     * @param string $fileId ファイル ID。
     * @param string $name ナレッジベース名。
     * @param string $structureType ナレッジベースのデータ構造。
     * @param string $sourceType データソースのデータの型。カテゴリとファイルタイプがサポートされています。
     * @param string $sinkType ナレッジベースのベクターストレージタイプ。
     * @return CreateIndexResponse サービスからのレスポンス。
     */
    public static function createIndex($client, $workspaceId, $fileId, $name, $structureType, $sourceType, $sinkType) {
        $headers = [];
        $createIndexRequest = new CreateIndexRequest([
            "structureType" => $structureType,
            "name" => $name,
            "sourceType" => $sourceType,
            "documentIds" => [
                $fileId
            ],
            "sinkType" => $sinkType
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->createIndexWithOptions($workspaceId, $createIndexRequest, $headers, $runtime);
    }

    /**
     * インデックス作成タスクを送信します。
     *
     * @param Bailian $client クライアント。
     * @param string $workspaceId ワークスペース ID。
     * @param string $indexId ナレッジベース ID。
     * @return SubmitIndexJobResponse サービスからのレスポンス。
     */
    public static function submitIndex($client, $workspaceId, $indexId) {
        $headers = [];
        $submitIndexJobRequest = new SubmitIndexJobRequest([
            'indexId' => $indexId
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->submitIndexJobWithOptions($workspaceId, $submitIndexJobRequest, $headers, $runtime);
    }

    /**
     * インデックス作成タスクのステータスをクエリします。
     *
     * @param Bailian $client クライアント。
     * @param string $workspaceId ワークスペース ID。
     * @param string $indexId ナレッジベース ID。
     * @param string $jobId タスク ID。
     * @return GetIndexJobStatusResponse サービスからのレスポンス。
     */
    public static function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
        $headers = [];
        $getIndexJobStatusRequest = new GetIndexJobStatusRequest([
            'indexId' => $indexId,
            'jobId' => $jobId
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
    }

    /**
     * ナレッジベースを作成します。
     *
     * @param string $filePath ファイルのローカルパス。
     * @param string $workspaceId ワークスペース ID。
     * @param string $name ナレッジベース名。
     * @return string|null 作成されたナレッジベースの ID、失敗した場合は null。
     */
    public static function createKnowledgeBase($filePath, $workspaceId, $name) {
        // デフォルト値を設定します。
        $categoryId = 'default';
        $parser = 'DASHSCOPE_DOCMIND';
        $sourceType = 'DATA_CENTER_FILE';
        $structureType = 'unstructured';
        $sinkType = 'DEFAULT';
        try {
            // ステップ 1: クライアントを初期化します。
            echo "ステップ 1: クライアントを初期化\n";
            $client = self::createClient();

            // ステップ 2: ファイル情報を準備します。
            echo "ステップ 2: ファイル情報を準備\n";
            $fileName = basename($filePath);
            echo "ファイル名: $fileName\n";
            $fileMd5 = self::calculateMd5($filePath);
            $fileSize = self::getFileSize($filePath);

            // ステップ 3: アップロードリースを申請します。
            echo "ステップ 3: アップロードリースを申請中\n";
            $leaseResponse = self::applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId);
            $leaseId = $leaseResponse->body->data->fileUploadLeaseId;
            $uploadUrl = $leaseResponse->body->data->param->url;
            $uploadHeaders = $leaseResponse->body->data->param->headers;
            $uploadHeadersMap = json_decode(json_encode($uploadHeaders), true);

            // ステップ 4: ファイルをアップロードします。
            echo "ステップ 4: ファイルをアップロード中\n";
            self::uploadFile($uploadUrl, $uploadHeadersMap, $filePath);

            // ステップ 5: サービスにファイルを登録します。
            echo "ステップ 5: サービスにファイルを登録中\n";
            $addResponse = self::addFile($client, $leaseId, $parser, $categoryId, $workspaceId);
            $fileId = $addResponse->body->data->fileId;
            echo "ファイル ID: $fileId\n";
            // ステップ 6: ファイルステータスを確認します。
            echo "ステップ 6: ファイルステータスを確認中\n";
            while (true) {
                $describeResponse = self::describeFile($client, $workspaceId, $fileId);
                $status = $describeResponse->body->data->status;
                echo "現在のファイルステータス: $status\n";
                if ($status == 'INIT') {
                    echo "ファイルは解析待ちです。お待ちください...\n";
                } elseif ($status == 'PARSING') {
                    echo "ファイルは解析中です。お待ちください...\n";
                } elseif ($status == 'PARSE_SUCCESS') {
                    echo "ファイルは正常に解析されました。\n";
                    break;
                } else {
                    echo "不明なファイルステータス: $status。テクニカルサポートにお問い合わせください。\n";
                    return null;
                }
                sleep(5);
            }

            // ステップ 7: ナレッジベースを初期化します。
            echo "ステップ 7: ナレッジベースを初期化中\n";
            $indexResponse = self::createIndex($client, $workspaceId, $fileId, $name, $structureType, $sourceType, $sinkType);
            $indexId = $indexResponse->body->data->id;

            // ステップ 8: インデックス作成タスクを送信します。
            echo "ステップ 8: インデックス作成タスクを送信中\n";
            $submitResponse = self::submitIndex($client, $workspaceId, $indexId);
            $jobId = $submitResponse->body->data->id;

            // ステップ 9: インデックス作成タスクのステータスを取得します。
            echo "ステップ 9: インデックス作成タスクのステータスを確認中\n";
            while (true) {
                $getIndexJobStatusResponse = self::getIndexJobStatus($client, $workspaceId, $jobId, $indexId);
                $status = $getIndexJobStatusResponse->body->data->status;
                echo "現在のインデックス作成タスクのステータス: $status\n";
                if ($status == 'COMPLETED') {
                    break;
                }
                sleep(5);
            }
            echo "ナレッジベースが正常に作成されました!\n";
            return $indexId;
        } catch (Exception $e) {
            echo "エラーが発生しました: {$e->getMessage()}\n";
            return null;
        }
    }


    /**
     * メイン関数。
     */
    public static function main($args){
        if (!self::checkEnvironmentVariables()) {
            echo "環境変数チェックに失敗しました。\n";
            return;
        }
        $filePath = readline("アップロードするファイルのローカルパスを入力してください (例: /path/to/your/file.docx): ");
        $kbName = readline("ナレッジベースの名前を入力してください: ");
        $workspaceId = getenv('WORKSPACE_ID');
        $result = self::createKnowledgeBase($filePath, $workspaceId, $kbName);
       if ($result) {
           echo "ナレッジベース ID: $result\n";
       } else {
           echo "ナレッジベースの作成に失敗しました。\n";
       }
    }
}
// autoload.php が現在のファイルの親ディレクトリにあると仮定します。プロジェクトの構造に応じてパスを調整してください。
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
KnowledgeBaseCreate::main(array_slice($argv, 1));

Node.js

// このサンプルコードは参照用です。本番環境では使用しないでください。
'use strict';

const fs = require('fs');
const path = require('path');
const axios = require('axios');
const crypto = require('crypto');

const bailian20231229 = require('@alicloud/bailian20231229');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');

class KbCreate {

  /**
   * 必要な環境変数が設定されているか確認します。
   * @returns {boolean} - 必要な環境変数がすべて設定されていれば true、そうでなければ false。
   */
  static checkEnvironmentVariables() {
    const requiredVars = {
      'ALIBABA_CLOUD_ACCESS_KEY_ID': 'Alibaba Cloud Access Key ID',
      'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'Alibaba Cloud Access Key Secret',
      'WORKSPACE_ID': 'Alibaba Cloud Model Studio workspace ID'
    };

    const missing = [];
    for (const [varName, desc] of Object.entries(requiredVars)) {
      if (!process.env[varName]) {
        console.error(`エラー: ${varName} 環境変数を設定してください (${desc})`);
        missing.push(varName);
      }
    }
    return missing.length === 0;
  }

  /**
   * ファイルの MD5 ハッシュを計算します。
   * @param {string} filePath - ローカルファイルのパス。
   * @returns {Promise<string>} - ファイルの MD5 ハッシュ。
   */
  static async calculateMD5(filePath) {
    const hash = crypto.createHash('md5');
    const stream = fs.createReadStream(filePath);

    return new Promise((resolve, reject) => {
      stream.on('data', chunk => hash.update(chunk));
      stream.on('end', () => resolve(hash.digest('hex')));
      stream.on('error', reject);
    });
  }

  /**
   * ファイルのサイズをバイト単位で取得します。
   * @param {string} filePath - ローカルファイルのパス。
   * @returns {string} - ファイルサイズ (文字列)。
   */
  static getFileSize(filePath) {
    try {
      const stats = fs.statSync(filePath);
      return stats.size.toString();
    } catch (err) {
      console.error(`ファイルサイズの取得に失敗しました: ${err.message}`);
      throw err;
    }
  }

  /**
   * API クライアントを作成して設定します。
   * @returns {bailian20231229.default} クライアントインスタンス。
   */
  static createClient() {
    const config = new OpenApi.Config({
      accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
      accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
    });
    // 以下のエンドポイントはパブリッククラウド用です。必要に応じて変更できます。
    config.endpoint = `bailian.ap-southeast-1.aliyuncs.com`;
    return new bailian20231229.default(config);
  }

  /**
   * ファイルをアップロードするためのリースをリクエストします。
   * @param {Bailian20231229Client} client - クライアントインスタンス。
   * @param {string} categoryId - カテゴリ ID。
   * @param {string} fileName - ファイル名。
   * @param {string} fileMd5 - ファイルの MD5 ハッシュ。
   * @param {string} fileSize - ファイルサイズ (バイト単位)。
   * @param {string} workspaceId - ワークスペース ID。
   * @returns {Promise<bailian20231229.ApplyFileUploadLeaseResponse>} - リース詳細を含むレスポンス。
   */
  static async applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId) {
    const headers = {};
    const req = new bailian20231229.ApplyFileUploadLeaseRequest({
      md5: fileMd5,
      fileName,
      sizeInBytes: fileSize
    });
    const runtime = new Util.RuntimeOptions({});
    return await client.applyFileUploadLeaseWithOptions(
      categoryId,
      workspaceId,
      req,
      headers,
      runtime
    );
  }

  /**
   * ファイルを一時ストレージにアップロードします。
   * @param {string} preSignedUrl - アップロード用の署名付き URL。
   * @param {Object} headers - アップロード用のリクエストヘッダー。
   * @param {string} filePath - ローカルファイルのパス。
   */
  static async uploadFile(preSignedUrl, headers, filePath) {
    const uploadHeaders = {
      "X-bailian-extra": headers["X-bailian-extra"],
      "Content-Type": headers["Content-Type"]
    };
    const stream = fs.createReadStream(filePath);
    try {
      await axios.put(preSignedUrl, stream, { headers: uploadHeaders });
    } catch (e) {
      throw new Error(`アップロードに失敗しました: ${e.message}`);
    }
  }

  /**
   * ファイルをカテゴリに追加します。
   * @param {Bailian20231229Client} client - クライアントインスタンス。
   * @param {string} leaseId - リース ID。
   * @param {string} parser - ファイルのパーサー。
   * @param {string} categoryId - カテゴリ ID。
   * @param {string} workspaceId - ワークスペース ID。
   * @returns {Promise<bailian20231229.AddFileResponse>} - ファイル ID を含むレスポンス。
   */
  static async addFile(client, leaseId, parser, categoryId, workspaceId) {
    const headers = {};
    const req = new bailian20231229.AddFileRequest({
      leaseId,
      parser,
      categoryId
    });
    const runtime = new Util.RuntimeOptions({});
    return await client.addFileWithOptions(workspaceId, req, headers, runtime);
  }

  /**
   * ファイルの解析ステータスをクエリします。
   * @param {Bailian20231229Client} client - クライアントインスタンス。
   * @param {string} workspaceId - ワークスペース ID。
   * @param {string} fileId - ファイル ID。
   * @returns {Promise<bailian20231229.DescribeFileResponse>} - ファイルのステータスを含むレスポンス。
   */
  static async describeFile(client, workspaceId, fileId) {
    const headers = {};
    const runtime = new Util.RuntimeOptions({});
    return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
  }

  /**
   * ナレッジベース (インデックス) を初期化します。
   * @param {Bailian20231229Client} client - クライアントインスタンス。
   * @param {string} workspaceId - ワークスペース ID。
   * @param {string} fileId - ファイル ID。
   * @param {string} name - ナレッジベースの名前。
   * @param {string} structureType - ナレッジベースのデータ構造タイプ。
   * @param {string} sourceType - ソースのデータの型。カテゴリとファイルタイプがサポートされています。
   * @param {string} sinkType - ナレッジベースのベクターストレージタイプ。
   * @returns {Promise<bailian20231229.CreateIndexResponse>} - インデックス ID を含むレスポンス。
   */
  static async createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType) {
    const headers = {};
    const req = new bailian20231229.CreateIndexRequest({
      name,
      structureType,
      documentIds: [fileId],
      sourceType,
      sinkType
    });
    const runtime = new Util.RuntimeOptions({});
    return await client.createIndexWithOptions(workspaceId, req, headers, runtime);
  }

  /**
   * インデックス作成ジョブを送信します。
   * @param {Bailian20231229Client} client - クライアントインスタンス。
   * @param {string} workspaceId - ワークスペース ID。
   * @param {string} indexId - 処理するインデックス (ナレッジベース) の ID。
   * @returns {Promise<bailian20231229.SubmitIndexJobResponse>} - ジョブ ID を含むレスポンス。
   */
  static async submitIndex(client, workspaceId, indexId) {
    const headers = {};
    const req = new bailian20231229.SubmitIndexJobRequest({ indexId });
    const runtime = new Util.RuntimeOptions({});
    return await client.submitIndexJobWithOptions(workspaceId, req, headers, runtime);
  }

  /**
   * インデックス作成ジョブのステータスをクエリします。
   * @param {Bailian20231229Client} client - クライアントインスタンス。
   * @param {string} workspaceId - ワークスペース ID。
   * @param {string} jobId - ジョブ ID。
   * @param {string} indexId - 処理するインデックス (ナレッジベース) の ID。
   * @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - インデックス作成ジョブのステータスを含むレスポンス。
   */
  static async getIndexJobStatus(client, workspaceId, jobId, indexId) {
    const headers = {};
    const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId });
    const runtime = new Util.RuntimeOptions({});
    return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime);
  }

  /**
   * ナレッジベースを作成します。
   * @param {string} filePath - ローカルファイルのパス。
   * @param {string} workspaceId - ワークスペース ID。
   * @param {string} name - ナレッジベースの名前。
   * @returns {Promise<string | null>} - 成功した場合はナレッジベースの ID、それ以外の場合は null。
   */
  static async createKnowledgeBase(filePath, workspaceId, name) {
    const categoryId = 'default';
    const parser = 'DASHSCOPE_DOCMIND';
    const sourceType = 'DATA_CENTER_FILE';
    const structureType = 'unstructured';
    const sinkType = 'DEFAULT';

    try {
      console.log("ステップ 1: クライアントを初期化しています。");
      const client = this.createClient();

      console.log("ステップ 2: ファイル情報を準備しています。");
      const fileName = path.basename(filePath);
      const fileMd5 = await this.calculateMD5(filePath);
      const fileSize = this.getFileSize(filePath);

      console.log("ステップ 3: Alibaba Cloud Model Studio からアップロードリースを申請しています");
      const leaseRes = await this.applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
      const leaseId = leaseRes.body.data.fileUploadLeaseId;
      const uploadUrl = leaseRes.body.data.param.url;
      const uploadHeaders = leaseRes.body.data.param.headers;

      console.log("ステップ 4: Alibaba Cloud Model Studio にファイルをアップロードしています");
      await this.uploadFile(uploadUrl, uploadHeaders, filePath);

      console.log("ステップ 5: Alibaba Cloud Model Studio にファイルを追加しています");
      const addRes = await this.addFile(client, leaseId, parser, categoryId, workspaceId);
      const fileId = addRes.body.data.fileId;

      console.log("ステップ 6: Alibaba Cloud Model Studio でファイルステータスを確認しています");
      while (true) {
        const descRes = await this.describeFile(client, workspaceId, fileId);
        const status = descRes.body.data.status;
        console.log(`現在のファイルステータス: ${status}`);

        if (status === 'INIT') console.log("ファイルは解析待ちです。お待ちください。");
        else if (status === 'PARSING') console.log("ファイルは解析中です。お待ちください。");
        else if (status === 'PARSE_SUCCESS') break;
        else {
          console.error(`不明なファイルステータス: ${status}。テクニカルサポートにお問い合わせください。`);
          return null;
        }
        await this.sleep(5);
      }

      console.log("ステップ 7: Alibaba Cloud Model Studio でナレッジベースを初期化しています");
      const indexRes = await this.createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType);
      const indexId = indexRes.body.data.id;

      console.log("ステップ 8: Alibaba Cloud Model Studio にインデックス作成ジョブを送信しています");
      const submitRes = await this.submitIndex(client, workspaceId, indexId);
      const jobId = submitRes.body.data.id;

      console.log("ステップ 9: Alibaba Cloud Model Studio からインデックス作成ジョブのステータスを確認しています");
      while (true) {
        const jobRes = await this.getIndexJobStatus(client, workspaceId, jobId, indexId);
        const status = jobRes.body.data.status;
        console.log(`現在のインデックス作成ジョブのステータス: ${status}`);
        if (status === 'COMPLETED') break;
        await this.sleep(5);
      }
      console.log("Alibaba Cloud Model Studio ナレッジベースが正常に作成されました!");
      return indexId;
    } catch (e) {
      console.error(`エラーが発生しました: ${e.message}`);
      return null;
    }
  }

  /**
   * 指定された秒数待機します。
   * @param {number} seconds - 待機時間 (秒)。
   * @returns {Promise<void>}
   */
  static sleep(seconds) {
    return new Promise(resolve => setTimeout(resolve, seconds * 1000));
  }

  static async main(args) {
    if (!this.checkEnvironmentVariables()) {
      console.log("環境変数チェックに失敗しました。");
      return;
    }

    const readline = require('readline').createInterface({
      input: process.stdin,
      output: process.stdout
    });

    try {
      const filePath = await new Promise((resolve, reject) => {
        readline.question("アップロードするファイルのローカルパスを入力してください (例: Linux の場合 /path/to/Alibaba Cloud Model Studio Phone Series Introduction.docx):", (ans) => {
          ans.trim() ? resolve(ans) : reject(new Error("パスは空にできません。"));
        });
      });
      const kbName = await new Promise((resolve, reject) => {
        readline.question("ナレッジベースの名前を入力してください:", (ans) => {
          ans.trim() ? resolve(ans) : reject(new Error("ナレッジベース名は空にできません。"));
        });
      });
      const workspaceId = process.env.WORKSPACE_ID;

      const result = await KbCreate.createKnowledgeBase(filePath, workspaceId, kbName);
      if (result) console.log(`ナレッジベース ID: ${result}`);
      else console.log("ナレッジベースの作成に失敗しました。");
    } catch (err) {
      console.error(err.message);
    } finally {
      readline.close();
    }
  }
}

exports.KbCreate = KbCreate;
KbCreate.main(process.argv.slice(2));

C#

// このサンプルコードは参照用です。本番環境では使用しないでください。
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Tea;
using Tea.Utils;


namespace AlibabaCloud.SDK.KnowledgeBase
{
    public class KnowledgeBaseCreate
    {
        /// <summary>
        /// 必要な環境変数が設定されていることを確認します。
        /// </summary>
        /// <returns>必要な環境変数がすべて設定されていれば `true`、そうでなければ `false` を返します。</returns>
        public static bool CheckEnvironmentVariables()
        {
            var requiredVars = new Dictionary<string, string>
            {
                { "ALIBABA_CLOUD_ACCESS_KEY_ID", "Alibaba Cloud AccessKey ID" },
                { "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "Alibaba Cloud AccessKey secret" },
                { "WORKSPACE_ID", "Alibaba Cloud Model Studio workspace ID" }
            };

            var missingVars = new List<string>();
            foreach (var entry in requiredVars)
            {
                string value = Environment.GetEnvironmentVariable(entry.Key);
                if (string.IsNullOrEmpty(value))
                {
                    missingVars.Add(entry.Key);
                    Console.WriteLine($"エラー: {entry.Key} 環境変数を設定してください ({entry.Value})。");
                }
            }

            return missingVars.Count == 0;
        }

        /// <summary>
        /// ファイルの MD5 ハッシュを計算します。
        /// </summary>
        /// <param name="filePath">ファイルのローカルパス。</param>
        /// <returns>ファイルの MD5 ハッシュ。</returns>
        /// <exception cref="Exception">計算中にエラーが発生した場合にスローされます。</exception>
        public static string CalculateMD5(string filePath)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] hashBytes = md5.ComputeHash(stream);
                    StringBuilder sb = new StringBuilder();
                    foreach (byte b in hashBytes)
                    {
                        sb.Append(b.ToString("x2"));
                    }
                    return sb.ToString();
                }
            }
        }

        /// <summary>
        /// ファイルサイズをバイト単位で取得します。
        /// </summary>
        /// <param name="filePath">ファイルのローカルパス。</param>
        /// <returns>ファイルサイズ (バイト単位)。</returns>
        public static string GetFileSize(string filePath)
        {
            var file = new FileInfo(filePath);
            return file.Length.ToString();
        }

        /// <summary>
        /// クライアントを初期化します。
        /// </summary>
        /// <returns>設定済みのクライアントオブジェクト。</returns>
        /// <exception cref="Exception">初期化中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
        {
            var config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
            // これはパブリックエンドポイントの例です。必要に応じて変更してください。
            config.Endpoint = "bailian.ap-southeast-1.aliyuncs.com";
            return new AlibabaCloud.SDK.Bailian20231229.Client(config);
        }

        /// <summary>
        /// ファイルアップロードリースをリクエストします。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="categoryId">カテゴリ ID。</param>
        /// <param name="fileName">ファイル名。</param>
        /// <param name="fileMd5">ファイルの MD5 ハッシュ。</param>
        /// <param name="fileSize">ファイルサイズ (バイト単位)。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <returns>Alibaba Cloud Model Studio からのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseResponse ApplyLease(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string categoryId,
            string fileName,
            string fileMd5,
            string fileSize,
            string workspaceId)
        {
            var headers = new Dictionary<string, string>() { };
            var applyFileUploadLeaseRequest = new AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseRequest
            {
                FileName = fileName,
                Md5 = fileMd5,
                SizeInBytes = fileSize
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.ApplyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
        }

        /// <summary>
        /// ファイルを一時ストレージにアップロードします。
        /// </summary>
        /// <param name="preSignedUrl">アップロードリースからの URL。</param>
        /// <param name="headers">アップロード用のリクエストヘッダー。</param>
        /// <param name="filePath">ファイルのローカルパス。</param>
        /// <exception cref="Exception">アップロード中にエラーが発生した場合にスローされます。</exception>
        public static void UploadFile(string preSignedUrl, Dictionary<string, string> headers, string filePath)
        {
            var file = new FileInfo(filePath);
            if (!File.Exists(filePath))
            {
                throw new ArgumentException($"ファイルが存在しないか、通常のファイルではありません: {filePath}");
            }

            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                var url = new Uri(preSignedUrl);
                var conn = (HttpWebRequest)WebRequest.Create(url);
                conn.Method = "PUT";
                conn.ContentType = headers["Content-Type"];
                conn.Headers.Add("X-bailian-extra", headers["X-bailian-extra"]);

                byte[] buffer = new byte[4096];
                int bytesRead;
                using (var requestStream = conn.GetRequestStream())
                {
                    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }
                }

                using (var response = (HttpWebResponse)conn.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception($"アップロードに失敗しました: {response.StatusCode}");
                    }
                }
            }
        }

        /// <summary>
        /// ファイルをカテゴリに追加します。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="leaseId">リース ID。</param>
        /// <param name="parser">ファイルに使用するパーサー。</param>
        /// <param name="categoryId">カテゴリ ID。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <returns>Alibaba Cloud Model Studio からのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.AddFileResponse AddFile(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string leaseId,
            string parser,
            string categoryId,
            string workspaceId)
        {
            var headers = new Dictionary<string, string>() { };
            var addFileRequest = new AlibabaCloud.SDK.Bailian20231229.Models.AddFileRequest
            {
                LeaseId = leaseId,
                Parser = parser,
                CategoryId = categoryId
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.AddFileWithOptions(workspaceId, addFileRequest, headers, runtime);
        }

        /// <summary>
        /// ファイルの基本情報をクエリします。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="fileId">ファイル ID。</param>
        /// <returns>Alibaba Cloud Model Studio からのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.DescribeFileResponse DescribeFile(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string fileId)
        {
            var headers = new Dictionary<string, string>() { };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.DescribeFileWithOptions(workspaceId, fileId, headers, runtime);
        }

        /// <summary>
        /// Alibaba Cloud Model Studio でナレッジベースを作成します (インデックスを初期化します)。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="fileId">ファイル ID。</param>
        /// <param name="name">ナレッジベースの名前。</param>
        /// <param name="structureType">ナレッジベースのデータ構造。</param>
        /// <param name="sourceType">データソースのタイプ。`category` と `file` がサポートされています。</param>
        /// <param name="sinkType">ナレッジベースのベクターストレージタイプ。</param>
        /// <returns>Alibaba Cloud Model Studio からのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexResponse CreateIndex(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string fileId,
            string name,
            string structureType,
            string sourceType,
            string sinkType)
        {
            var headers = new Dictionary<string, string>() { };
            var createIndexRequest = new AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexRequest
            {
                StructureType = structureType,
                Name = name,
                SourceType = sourceType,
                SinkType = sinkType,
                DocumentIds = new List<string> { fileId }
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.CreateIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
        }

        /// <summary>
        /// Alibaba Cloud Model Studio にインデックス作成タスクを送信します。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="indexId">ナレッジベース ID。</param>
        /// <returns>Alibaba Cloud Model Studio からのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobResponse SubmitIndex(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string indexId)
        {
            var headers = new Dictionary<string, string>() { };
            var submitIndexJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobRequest
            {
                IndexId = indexId
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.SubmitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
        }

        /// <summary>
        /// インデックス作成タスクのステータスをクエリします。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="jobId">タスク ID。</param>
        /// <param name="indexId">ナレッジベース ID。</param>
        /// <returns>Alibaba Cloud Model Studio からのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string jobId,
            string indexId)
        {
            var headers = new Dictionary<string, string>() { };
            var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest
            {
                IndexId = indexId,
                JobId = jobId
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
        }

        /// <summary>
        /// Alibaba Cloud Model Studio でナレッジベースを作成します。
        /// </summary>
        /// <param name="filePath">ファイルのローカルパス。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="name">ナレッジベースの名前。</param>
        /// <returns>作成されたナレッジベースの ID、操作が失敗した場合は null。</returns>
        public static string CreateKnowledgeBase(string filePath, string workspaceId, string name)
        {
            // デフォルト値を設定します。
            string categoryId = "default";
            string parser = "DASHSCOPE_DOCMIND";
            string sourceType = "DATA_CENTER_FILE";
            string structureType = "unstructured";
            string sinkType = "DEFAULT";

            try
            {
                Console.WriteLine("ステップ 1: クライアントを初期化します。");
                AlibabaCloud.SDK.Bailian20231229.Client client = CreateClient();

                Console.WriteLine("ステップ 2: ファイル情報を準備します。");
                var fileInfo = new FileInfo(filePath);
                string fileName = fileInfo.Name;
                string fileMd5 = CalculateMD5(filePath);
                string fileSize = GetFileSize(filePath);

                Console.WriteLine("ステップ 3: Alibaba Cloud Model Studio からアップロードリースをリクエストします。");
                var leaseResponse = ApplyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
                string leaseId = leaseResponse.Body.Data.FileUploadLeaseId;
                string uploadUrl = leaseResponse.Body.Data.Param.Url;
                var uploadHeaders = leaseResponse.Body.Data.Param.Headers;

                Console.WriteLine("ステップ 4: ファイルを Alibaba Cloud Model Studio にアップロードします。");
                // Newtonsoft.Json パッケージが必要です。
                var uploadHeadersMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(uploadHeaders));
                UploadFile(uploadUrl, uploadHeadersMap, filePath);

                Console.WriteLine("ステップ 5: ファイルを Alibaba Cloud Model Studio に追加します。");
                var addResponse = AddFile(client, leaseId, parser, categoryId, workspaceId);
                string fileId = addResponse.Body.Data.FileId;

                Console.WriteLine("ステップ 6: Alibaba Cloud Model Studio でファイルステータスを確認します。");
                while (true)
                {
                    var describeResponse = DescribeFile(client, workspaceId, fileId);
                    string status = describeResponse.Body.Data.Status;
                    Console.WriteLine($"現在のファイルステータス: {status}");

                    if (status == "INIT")
                    {
                        Console.WriteLine("ファイルは解析待ちです。お待ちください...");
                    }
                    else if (status == "PARSING")
                    {
                        Console.WriteLine("ファイルは解析中です。お待ちください...");
                    }
                    else if (status == "PARSE_SUCCESS")
                    {
                        Console.WriteLine("ファイルの解析が完了しました。");
                        break;
                    }
                    else
                    {
                        Console.WriteLine($"不明なファイルステータス: {status}。テクニカルサポートにお問い合わせください。");
                        return null;
                    }
                    System.Threading.Thread.Sleep(5000);
                }

                Console.WriteLine("ステップ 7: Alibaba Cloud Model Studio でナレッジベースを作成します。");
                var indexResponse = CreateIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType);
                string indexId = indexResponse.Body.Data.Id;

                Console.WriteLine("ステップ 8: Alibaba Cloud Model Studio にインデックス作成タスクを送信します。");
                var submitResponse = SubmitIndex(client, workspaceId, indexId);
                string jobId = submitResponse.Body.Data.Id;

                Console.WriteLine("ステップ 9: Alibaba Cloud Model Studio でインデックス作成タスクのステータスを確認します。");
                while (true)
                {
                    var getStatusResponse = GetIndexJobStatus(client, workspaceId, jobId, indexId);
                    string status = getStatusResponse.Body.Data.Status;
                    Console.WriteLine($"現在のインデックス作成タスクのステータス: {status}");

                    if (status == "COMPLETED")
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(5000);
                }

                Console.WriteLine("ナレッジベースが正常に作成されました。");
                return indexId;

            }
            catch (Exception ex)
            {
                Console.WriteLine($"エラーが発生しました: {ex.Message}");
                Console.WriteLine("エラー詳細: " + ex.StackTrace);
                return null;
            }
        }

        /// <summary>
        /// アプリケーションのメインエントリポイント。
        /// </summary>
        public static void Main(string[] args)
        {
            if (!CheckEnvironmentVariables())
            {
                return;
            }

            Console.Write("アップロードするファイルのローカルパスを入力してください (例: Linux の場合 /path/to/Product_Introduction_for_Model_Studio_Phone_Series.docx): ");
            string filePath = Console.ReadLine();

            Console.Write("ナレッジベースの名前を入力してください: ");
            string kbName = Console.ReadLine();

            string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
            string result = CreateKnowledgeBase(filePath, workspaceId, kbName);
            if (result != null)
            {
                Console.WriteLine($"ナレッジベース ID: {result}");
            }
        }
    }
}

Go

// このサンプルコードは参照用です。本番環境では使用しないでください。
package main

import (
	"bufio"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"

	bailian20231229 "github.com/alibabacloud-go/bailian-20231229/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/go-resty/resty/v2"
)

// CheckEnvironmentVariables は、必要な環境変数をチェックし、設定を促します。
func CheckEnvironmentVariables() bool {
	// 必要な環境変数とその説明。
	requiredVars := map[string]string{
		"ALIBABA_CLOUD_ACCESS_KEY_ID":     "Alibaba Cloud AccessKey ID",
		"ALIBABA_CLOUD_ACCESS_KEY_SECRET": "Alibaba Cloud AccessKey secret",
		"WORKSPACE_ID":                    "Alibaba Cloud Model Studio workspace ID",
	}

	var missingVars []string
	for varName, desc := range requiredVars {
		if os.Getenv(varName) == "" {
			fmt.Printf("エラー: %s 環境変数を設定してください (%s)\n", varName, desc)
			missingVars = append(missingVars, varName)
		}
	}

	return len(missingVars) == 0
}

// CalculateMD5 は、ファイルの MD5 ハッシュを計算します。
//
// パラメータ:
//   - filePath (string): ファイルのローカルパス。
//
// 戻り値:
//   - string: ファイルの MD5 ハッシュ。
//   - error: エラーメッセージ。
func CalculateMD5(filePath string) (_result string, _err error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	md5Hash := md5.New()
	_, err = io.Copy(md5Hash, file)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%x", md5Hash.Sum(nil)), nil
}

// GetFileSize は、ファイルサイズをバイト単位で取得します。
//
// パラメータ:
//   - filePath (string): ファイルのローカルパス。
//
// 戻り値:
//   - string: ファイルサイズ (バイト単位)。
//   - error: エラーメッセージ。
func GetFileSize(filePath string) (_result string, _err error) {
	info, err := os.Stat(filePath)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%d", info.Size()), nil
}

// CreateClient は、クライアントを作成して設定します。
//
// 戻り値:
//   - *bailian20231229.Client: 設定済みのクライアント。
//   - error: エラーメッセージ。
func CreateClient() (_result *bailian20231229.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// 以下のエンドポイントはパブリックエンドポイントです。必要に応じて変更できます。
	config.Endpoint = tea.String("bailian.ap-southeast-1.aliyuncs.com")
	_result = &bailian20231229.Client{}
	_result, _err = bailian20231229.NewClient(config)
	return _result, _err
}

// ApplyLease は、Alibaba Cloud Model Studio サービスからファイルアップロードリースをリクエストします。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - categoryId (string): カテゴリ ID。
//   - fileName (string): ファイル名。
//   - fileMD5 (string): ファイルの MD5 ハッシュ。
//   - fileSize (string): ファイルサイズ (バイト単位)。
//   - workspaceId (string): ワークスペース ID。
//
// 戻り値:
//   - *bailian20231229.ApplyFileUploadLeaseResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func ApplyLease(client *bailian20231229.Client, categoryId, fileName, fileMD5 string, fileSize string, workspaceId string) (_result *bailian20231229.ApplyFileUploadLeaseResponse, _err error) {
	headers := make(map[string]*string)
	applyFileUploadLeaseRequest := &bailian20231229.ApplyFileUploadLeaseRequest{
		FileName:    tea.String(fileName),
		Md5:         tea.String(fileMD5),
		SizeInBytes: tea.String(fileSize),
	}
	runtime := &util.RuntimeOptions{}
	return client.ApplyFileUploadLeaseWithOptions(tea.String(categoryId), tea.String(workspaceId), applyFileUploadLeaseRequest, headers, runtime)
}

// UploadFile は、ファイルを Alibaba Cloud Model Studio サービスにアップロードします。
//
// パラメータ:
//   - preSignedUrl (string): ファイルアップロードリース内の URL。
//   - headers (map[string]string): アップロード用のリクエストヘッダー。
//   - filePath (string): ファイルのローカルパス。
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	body, err := io.ReadAll(file)
	if err != nil {
		return err
	}

	client := resty.New()
	uploadHeaders := map[string]string{
		"X-bailian-extra": headers["X-bailian-extra"],
		"Content-Type":    headers["Content-Type"],
	}

	resp, err := client.R().
		SetHeaders(uploadHeaders).
		SetBody(body).
		Put(preSignedUrl)

	if err != nil {
		return err
	}

	if resp.IsError() {
		return fmt.Errorf("HTTP エラー: %d", resp.StatusCode())
	}

	return nil
}

// AddFile は、Alibaba Cloud Model Studio サービスの指定されたカテゴリにファイルを追加します。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - leaseId (string): リース ID。
//   - parser (string): ファイルのパーサー。
//   - categoryId (string): カテゴリ ID。
//   - workspaceId (string): ワークスペース ID。
//
// 戻り値:
//   - *bailian20231229.AddFileResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func AddFile(client *bailian20231229.Client, leaseId, parser, categoryId, workspaceId string) (_result *bailian20231229.AddFileResponse, _err error) {
	headers := make(map[string]*string)
	addFileRequest := &bailian20231229.AddFileRequest{
		LeaseId:    tea.String(leaseId),
		Parser:     tea.String(parser),
		CategoryId: tea.String(categoryId),
	}
	runtime := &util.RuntimeOptions{}
	return client.AddFileWithOptions(tea.String(workspaceId), addFileRequest, headers, runtime)
}

// DescribeFile は、ファイルに関する基本情報を取得します。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - fileId (string): ファイル ID。
//
// 戻り値:
//   - *bailian20231229.DescribeFileResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func DescribeFile(client *bailian20231229.Client, workspaceId, fileId string) (_result *bailian20231229.DescribeFileResponse, _err error) {
	headers := make(map[string]*string)
	runtime := &util.RuntimeOptions{}
	return client.DescribeFileWithOptions(tea.String(workspaceId), tea.String(fileId), headers, runtime)
}

// CreateIndex は、Alibaba Cloud Model Studio サービスでナレッジベースを作成します (インデックスを初期化します)。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - fileId (string): ファイル ID。
//   - name (string): ナレッジベース名。
//   - structureType (string): ナレッジベースのデータの型。
//   - sourceType (string): データソースのタイプ。カテゴリとファイルタイプをサポートします。
//   - sinkType (string): ナレッジベースのベクターストレージタイプ。
//
// 戻り値:
//   - *bailian20231229.CreateIndexResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func CreateIndex(client *bailian20231229.Client, workspaceId, fileId, name, structureType, sourceType, sinkType string) (_result *bailian20231229.CreateIndexResponse, _err error) {
	headers := make(map[string]*string)
	createIndexRequest := &bailian20231229.CreateIndexRequest{
		StructureType: tea.String(structureType),
		Name:          tea.String(name),
		SourceType:    tea.String(sourceType),
		SinkType:      tea.String(sinkType),
		DocumentIds:   []*string{tea.String(fileId)},
	}
	runtime := &util.RuntimeOptions{}
	return client.CreateIndexWithOptions(tea.String(workspaceId), createIndexRequest, headers, runtime)
}

// SubmitIndex は、インデックス作成タスクを送信します。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): ナレッジベース ID。
//
// 戻り値:
//   - *bailian20231229.SubmitIndexJobResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func SubmitIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.SubmitIndexJobResponse, _err error) {
	headers := make(map[string]*string)
	submitIndexJobRequest := &bailian20231229.SubmitIndexJobRequest{
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.SubmitIndexJobWithOptions(tea.String(workspaceId), submitIndexJobRequest, headers, runtime)
}

// GetIndexJobStatus は、インデックス作成タスクのステータスをクエリします。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - jobId (string): タスク ID。
//   - indexId (string): ナレッジベース ID。
//
// 戻り値:
//   - *bailian20231229.GetIndexJobStatusResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) {
	headers := make(map[string]*string)
	getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{
		JobId:   tea.String(jobId),
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime)
}

// CreateKnowledgeBase は、ローカルファイルからナレッジベースを作成します。
//
// パラメータ:
//   - filePath (string): ファイルのローカルパス。
//   - workspaceId (string): ワークスペース ID。
//   - name (string): ナレッジベース名。
//
// 戻り値:
//   - string: 作成されたナレッジベースの ID。
//   - error: エラーメッセージ。
func CreateKnowledgeBase(filePath, workspaceId, name string) (_result string, _err error) {
	categoryId := "default"
	parser := "DASHSCOPE_DOCMIND"
	sourceType := "DATA_CENTER_FILE"
	structureType := "unstructured"
	sinkType := "DEFAULT"

	fmt.Println("ステップ 1: クライアントを初期化しています。")
	client, err := CreateClient()
	if err != nil {
		return "", err
	}

	fmt.Println("ステップ 2: ファイル情報を準備しています。")
	fileName := filepath.Base(filePath)
	fileMD5, err := CalculateMD5(filePath)
	if err != nil {
		return "", err
	}
	fileSizeStr, err := GetFileSize(filePath)
	if err != nil {
		return "", err
	}

	fmt.Println("ステップ 3: ファイルアップロードリースをリクエストしています。")
	leaseResponse, err := ApplyLease(client, categoryId, fileName, fileMD5, fileSizeStr, workspaceId)
	if err != nil {
		return "", err
	}

	leaseId := tea.StringValue(leaseResponse.Body.Data.FileUploadLeaseId)
	uploadURL := tea.StringValue(leaseResponse.Body.Data.Param.Url)
	uploadHeaders := leaseResponse.Body.Data.Param.Headers

	jsonData, err := json.Marshal(uploadHeaders)
	if err != nil {
		return "", err
	}

	var uploadHeadersMap map[string]string
	err = json.Unmarshal(jsonData, &uploadHeadersMap)
	if err != nil {
		return "", err
	}

	fmt.Println("ステップ 4: ファイルをアップロードしています。")
	err = UploadFile(uploadURL, uploadHeadersMap, filePath)
	if err != nil {
		return "", err
	}

	fmt.Println("ステップ 5: サービスにファイルを追加しています。")
	addResponse, err := AddFile(client, leaseId, parser, categoryId, workspaceId)
	if err != nil {
		return "", err
	}
	fileID := tea.StringValue(addResponse.Body.Data.FileId)

	fmt.Println("ステップ 6: ファイルの解析ステータスを確認しています。")
	for {
		describeResponse, err := DescribeFile(client, workspaceId, fileID)
		if err != nil {
			return "", err
		}

		status := tea.StringValue(describeResponse.Body.Data.Status)
		fmt.Printf("ファイルステータス: %s\n", status)

		if status == "INIT" {
			fmt.Println("ファイルは解析待ちです。お待ちください...")
		} else if status == "PARSING" {
			fmt.Println("ファイルは解析中です。お待ちください...")
		} else if status == "PARSE_SUCCESS" {
			fmt.Println("ファイルは正常に解析されました。")
			break
		} else {
			fmt.Printf("不明なファイルステータス: %s。テクニカルサポートにお問い合わせください。\n", status)
			return "", fmt.Errorf("不明なドキュメントステータス: %s", status)
		}
		time.Sleep(5 * time.Second)
	}

	fmt.Println("ステップ 7: ナレッジベースを作成しています。")
	indexResponse, err := CreateIndex(client, workspaceId, fileID, name, structureType, sourceType, sinkType)
	if err != nil {
		return "", err
	}
	indexID := tea.StringValue(indexResponse.Body.Data.Id)

	fmt.Println("ステップ 8: インデックス作成タスクを送信しています。")
	submitResponse, err := SubmitIndex(client, workspaceId, indexID)
	if err != nil {
		return "", err
	}
	jobID := tea.StringValue(submitResponse.Body.Data.Id)

	fmt.Println("ステップ 9: インデックス作成タスクのステータスをポーリングしています。")
	for {
		getIndexJobStatusResponse, err := GetIndexJobStatus(client, workspaceId, jobID, indexID)
		if err != nil {
			return "", err
		}

		status := tea.StringValue(getIndexJobStatusResponse.Body.Data.Status)
		fmt.Printf("インデックス作成タスクのステータス: %s\n", status)

		if status == "COMPLETED" {
			break
		}
		time.Sleep(5 * time.Second)
	}

	fmt.Println("ナレッジベースが正常に作成されました!")
	return indexID, nil
}

func main() {
	if !CheckEnvironmentVariables() {
		fmt.Println("環境変数チェックに失敗しました。")
		return
	}
	// ユーザー入力用のリーダーを作成します。
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("アップロードするファイルのローカルパスを入力してください (例: /path/to/your/file.docx):")
	filePath, _ := reader.ReadString('\n')
	filePath = strings.TrimSpace(filePath)
	fmt.Print("ナレッジベースの名前を入力してください:")
	kbName, _ := reader.ReadString('\n')
	kbName = strings.TrimSpace(kbName)
	workspaceID := os.Getenv("WORKSPACE_ID")
	indexID, err := CreateKnowledgeBase(filePath, workspaceID, kbName)
	if err != nil {
		fmt.Printf("エラーが発生しました: %v\n", err)
		return
	}
	fmt.Printf("ナレッジベースが正常に作成されました。ID: %s\n", indexID)
}

ナレッジベースからの取得

重要
  • この例を呼び出す前に、前提条件を完了してください。RAM ユーザーは、AliyunBailianDataFullAccess ポリシーを取得する必要もあります。

  • IDE やその他の開発プラグインを使用する場合、開発環境で ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET、および WORKSPACE_ID の各変数を設定してください。

Python

# このサンプルコードは参照用です。本番環境で直接使用しないでください。
import os

from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


def check_environment_variables():
    """必要な環境変数を確認し、不足しているものを報告します。"""
    required_vars = {
        'ALIBABA_CLOUD_ACCESS_KEY_ID': 'ご利用の Alibaba Cloud AccessKey ID',
        'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'ご利用の Alibaba Cloud AccessKey secret',
        'WORKSPACE_ID': 'ご利用の Model Studio ワークスペース ID'
    }
    missing_vars = []
    for var, description in required_vars.items():
        if not os.environ.get(var):
            missing_vars.append(var)
            print(f"エラー: {var} 環境変数を設定してください ({description})。")
    
    return len(missing_vars) == 0


def create_client() -> bailian20231229Client:
    """
    クライアントを作成して設定します。

    Returns:
        bailian20231229Client: 設定済みのクライアント。
    """
    config = open_api_models.Config(
        access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
        # これはパブリッククラウドのエンドポイントです。必要に応じて変更できます。
    config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
    return bailian20231229Client(config)


def retrieve_index(client, workspace_id, index_id, query):
    """
    指定されたナレッジベースから情報を取得します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        query (str): 検索クエリ。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    retrieve_request = bailian_20231229_models.RetrieveRequest(
        index_id=index_id,
        query=query
    )
    runtime = util_models.RuntimeOptions()
    return client.retrieve_with_options(workspace_id, retrieve_request, headers, runtime)


def main():
    """
    Model Studio サービスを使用してナレッジベースから取得します。

    Returns:
        str or None: 呼び出しが成功した場合、取得されたテキストセグメント。それ以外の場合は None が返されます。
    """
    if not check_environment_variables():
        print("環境変数の検証に失敗しました。")
        return
    try:
        print("ステップ 1: クライアントを作成します。")
        client = create_client()
        print("ステップ 2: ナレッジベースから取得します。")
        index_id = input("ナレッジベース ID を入力してください: ")  # これは CreateIndex 操作によって返される Data.Id 値です。Model Studio コンソールのナレッジベースページからも取得できます。
        query = input("検索クエリを入力してください: ")
        workspace_id = os.environ.get('WORKSPACE_ID')
        resp = retrieve_index(client, workspace_id, index_id, query)
        result = UtilClient.to_jsonstring(resp.body)
        print(result)
    except Exception as e:
        print(f"エラーが発生しました: {e}")
        return None


if __name__ == '__main__':
    main()

Java

// このサンプルコードは参照用です。本番環境で直接使用しないでください。
import com.aliyun.bailian20231229.models.RetrieveRequest;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

public class KnowledgeBaseRetrieve {

    /**
     * 必要な環境変数を確認し、不足しているものを報告します。
     *
     * @return 必要な環境変数がすべて設定されていれば true、そうでなければ false。
     */
    public static boolean checkEnvironmentVariables() {
        Map<String, String> requiredVars = new HashMap<>();
        requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_ID", "ご利用の Alibaba Cloud AccessKey ID");
        requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "ご利用の Alibaba Cloud AccessKey secret");
        requiredVars.put("WORKSPACE_ID", "ご利用の Model Studio ワークスペース ID");

        List<String> missingVars = new ArrayList<>();
        for (Map.Entry<String, String> entry : requiredVars.entrySet()) {
            String value = System.getenv(entry.getKey());
            if (value == null || value.isEmpty()) {
                missingVars.add(entry.getKey());
                System.out.println("エラー: " + entry.getKey() + " 環境変数を設定してください (" + entry.getValue() + ")。");
            }
        }

        return missingVars.isEmpty();
    }

    /**
     * クライアントを初期化します。
     *
     * @return 設定済みのクライアントオブジェクト。
     */
    public static com.aliyun.bailian20231229.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // これはパブリッククラウドのエンドポイントです。必要に応じて変更できます。
        config.endpoint = "bailian.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.bailian20231229.Client(config);
    }

    /**
     * 指定されたナレッジベースから情報を取得します。
     *
     * @param client         クライアントオブジェクト。
     * @param workspaceId    ワークスペース ID。
     * @param indexId        ナレッジベース ID。
     * @param query          検索クエリ。
     * @return               Model Studio サービスからのレスポンス。
     */
    public static RetrieveResponse retrieveIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String query) throws Exception {
        RetrieveRequest retrieveRequest = new RetrieveRequest();
        retrieveRequest.setIndexId(indexId);
        retrieveRequest.setQuery(query);
        RuntimeOptions runtime = new RuntimeOptions();
        return client.retrieveWithOptions(workspaceId, retrieveRequest, null, runtime);
    }

    /**
     * Model Studio サービスを使用してナレッジベースから取得します。
     */
    public static void main(String[] args) {
        if (!checkEnvironmentVariables()) {
            System.out.println("環境変数の検証に失敗しました。");
            return;
        }

        try {
            // ステップ 1: クライアントを作成します。
            System.out.println("ステップ 1: クライアントを作成します。");
            com.aliyun.bailian20231229.Client client = createClient();

            // ステップ 2: ナレッジベースから取得します。
            System.out.println("ステップ 2: ナレッジベースから取得します。");
            Scanner scanner = new Scanner(System.in);
            System.out.print("ナレッジベース ID を入力してください: "); // これは CreateIndex 操作によって返される Data.Id 値です。Model Studio コンソールのナレッジベースページからも取得できます。
            String indexId = scanner.nextLine();
            System.out.print("検索クエリを入力してください: ");
            String query = scanner.nextLine();
            String workspaceId = System.getenv("WORKSPACE_ID");
            RetrieveResponse resp = retrieveIndex(client, workspaceId, indexId, query);

            // jackson-databind をインストールして、レスポンスボディを JSON 文字列に変換します。
            ObjectMapper mapper = new ObjectMapper();
            String result = mapper.writeValueAsString(resp.getBody());
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("エラーが発生しました: " + e.getMessage());
        }
    }
}

PHP

<?php
// このサンプルコードは参照用です。本番環境で直接使用しないでください。
namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\SDK\Bailian\V20231229\Bailian;
use \Exception;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Bailian\V20231229\Models\RetrieveRequest;

class KnowledgeBaseRetrieve {

    /**
    * 必要な環境変数を確認し、不足しているものを報告します。
    *
    * @return bool 必要な環境変数がすべて設定されていれば true、そうでなければ false を返します。
    */
    public static function checkEnvironmentVariables() {
        $requiredVars = [
            'ALIBABA_CLOUD_ACCESS_KEY_ID' => 'ご利用の Alibaba Cloud AccessKey ID',
            'ALIBABA_CLOUD_ACCESS_KEY_SECRET' => 'ご利用の Alibaba Cloud AccessKey secret',
            'WORKSPACE_ID' => 'ご利用の Model Studio ワークスペース ID'
        ];
        $missingVars = [];
        foreach ($requiredVars as $var => $description) {
            if (!getenv($var)) {
                $missingVars[] = $var;
                echo "エラー: $var 環境変数を設定してください ($description)。\n";
            }
        }
        return count($missingVars) === 0;
    }

    /**
     * クライアントを初期化します。
     *
     * @return Bailian 設定済みのクライアントオブジェクト。
     */
    public static function createClient(){
        $config = new Config([
            "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
            "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        ]);
        // これはパブリッククラウドのエンドポイントです。必要に応じて変更できます。
        $config->endpoint = 'bailian.ap-southeast-1.aliyuncs.com';
        return new Bailian($config);
    }

     /**
     * 指定されたナレッジベースから情報を取得します。
     *
     * @param Bailian $client クライアントオブジェクト。
     * @param string $workspaceId ワークスペース ID。
     * @param string $indexId ナレッジベース ID。
     * @param string $query 検索クエリ。
     * @return RetrieveResponse Model Studio サービスからのレスポンス。
     * @throws Exception
     */
    public static function retrieveIndex($client, $workspaceId, $indexId, $query) {
        $headers = [];
        $retrieveRequest = new RetrieveRequest([
            "query" => $query,
            "indexId" => $indexId
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->retrieveWithOptions($workspaceId, $retrieveRequest, $headers, $runtime);
    }

    /**
     * Model Studio サービスを使用してナレッジベースから取得します。
     */
    public static function main($args){
        if (!self::checkEnvironmentVariables()) {
            echo "環境変数の検証に失敗しました。\n";
            return;
        }

        try {
            // ステップ 1: クライアントを作成します。
            echo "ステップ 1: クライアントを作成します。\n";
            $client = self::createClient();

            // ステップ 2: ナレッジベースから取得します。
            echo "ステップ 2: ナレッジベースから取得します。\n";
            $indexId = readline("ナレッジベース ID を入力してください: "); // これは CreateIndex 操作によって返される Data.Id 値です。Model Studio コンソールのナレッジベースページからも取得できます。
            $query = readline("検索クエリを入力してください: "); 
            $workspaceId = getenv("WORKSPACE_ID");
            $resp = self::retrieveIndex($client, $workspaceId, $indexId, $query);
            $result = json_encode($resp->body, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
            echo $result . "\n";
        } catch (Exception $e) {
            echo "エラーが発生しました: " . $e->getMessage() . "\n";
        }
    }
}
// autoload.php が現在のコードファイルの親ディレクトリにあると仮定します。プロジェクトの構造に基づいてパスを調整してください。
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
KnowledgeBaseRetrieve::main(array_slice($argv, 1));

Node.js

// このサンプルコードは参照用です。本番環境で直接使用しないでください。
'use strict';

const bailian20231229 = require('@alicloud/bailian20231229');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');

class KbRetrieve {

    /**
     * 必要な環境変数を確認し、不足しているものを報告します。
     * @returns {boolean} - 必要な環境変数がすべて設定されていれば true、そうでなければ false を返します。
     */
    static checkEnvironmentVariables() {
        const requiredVars = {
            'ALIBABA_CLOUD_ACCESS_KEY_ID': 'ご利用の Alibaba Cloud AccessKey ID',
            'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'ご利用の Alibaba Cloud AccessKey secret',
            'WORKSPACE_ID': 'ご利用の Model Studio ワークスペース ID'
        };

        const missing = [];
        for (const [varName, desc] of Object.entries(requiredVars)) {
            if (!process.env[varName]) {
                console.error(`エラー: ${varName} 環境変数を設定してください (${desc})。`);
                missing.push(varName);
            }
        }
        return missing.length === 0;
    }

    /**
     * クライアントを作成して設定します。
     * @return Client
     * @throws Exception
     */
    static createClient() {
        const config = new OpenApi.Config({
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
        });
        // これはパブリッククラウドのエンドポイントです。必要に応じて変更できます。
        config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com';
        return new bailian20231229.default(config);
    }

    /**
     * 指定されたナレッジベースから情報を取得します。
     * @param {bailian20231229.Client} client クライアント。
     * @param {string} workspaceId ワークスペース ID。
     * @param {string} indexId ナレッジベース ID。
     * @param {string} query 検索クエリ。
     * @returns {Promise<bailian20231229.RetrieveResponse>} Model Studio サービスからのレスポンス。
     */
    static async retrieveIndex(client, workspaceId, indexId, query) {
        const headers = {};
        const req = new bailian20231229.RetrieveRequest({
            indexId,
            query
        });
        const runtime = new Util.RuntimeOptions({});
        return await client.retrieveWithOptions(workspaceId, req, headers, runtime);
    }

    /**
     * Model Studio サービスを使用してナレッジベースから取得します。
     */
    static async main(args) {
        if (!this.checkEnvironmentVariables()) {
            console.log("環境変数の検証に失敗しました。");
            return;
        }

        const readline = require('readline').createInterface({
            input: process.stdin,
            output: process.stdout
        });

        try {
            console.log("ステップ 1: クライアントを作成します。")
            const client = this.createClient();
            
            console.log("ステップ 2: ナレッジベースから取得します。")
            const indexId = await new Promise((resolve, reject) => {
                // ナレッジベース ID は、CreateIndex 操作によって返される Data.Id 値です。Model Studio コンソールのナレッジベースページからも取得できます。
                readline.question("ナレッジベース ID を入力してください: ", (ans) => {
                    ans.trim() ? resolve(ans) : reject(new Error("ナレッジベース ID は空にできません。"));
                });
            });
            const query = await new Promise((resolve, reject) => {
                readline.question("検索クエリを入力してください: ", (ans) => {
                    ans.trim() ? resolve(ans) : reject(new Error("検索クエリは空にできません。"));
                });
            });
            const workspaceId = process.env.WORKSPACE_ID;
            const resp = await this.retrieveIndex(client, workspaceId, indexId, query);
            const result = JSON.stringify(resp.body);
            console.log(result);
        } catch (err) {
            console.error(`エラーが発生しました: ${err.message}`);
            return;
        } finally {
            readline.close();
        }
    }
}

exports.KbRetrieve = KbRetrieve;
KbRetrieve.main(process.argv.slice(2));

C#

// このサンプルコードは参照用です。本番環境で直接使用しないでください。
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Newtonsoft.Json;
using Tea;
using Tea.Utils;


namespace AlibabaCloud.SDK.KnowledgeBase
{
    public class KnowledgeBaseRetrieve
    {
        /// <summary>
        /// 必要な環境変数を確認し、不足しているものを報告します。
        /// </summary>
        /// <returns>必要な環境変数がすべて設定されていれば true、そうでなければ false を返します。</returns>
        public static bool CheckEnvironmentVariables()
        {
            var requiredVars = new Dictionary<string, string>
            {
                { "ALIBABA_CLOUD_ACCESS_KEY_ID", "ご利用の Alibaba Cloud AccessKey ID" },
                { "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "ご利用の Alibaba Cloud AccessKey secret" },
                { "WORKSPACE_ID", "ご利用の Model Studio ワークスペース ID" }
            };

            var missingVars = new List<string>();
            foreach (var entry in requiredVars)
            {
                string value = Environment.GetEnvironmentVariable(entry.Key);
                if (string.IsNullOrEmpty(value))
                {
                    missingVars.Add(entry.Key);
                    Console.WriteLine($"エラー: {entry.Key} 環境変数を設定してください ({entry.Value})。");
                }
            }

            return missingVars.Count == 0;
        }

        /// <summary>
        /// クライアントを初期化します。
        /// </summary>
        /// <returns>設定済みのクライアントオブジェクト。</returns>
        /// <exception cref="Exception">初期化中にエラーが発生した場合に例外がスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
        {
            var config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
            // これはパブリッククラウドのエンドポイントです。必要に応じて変更できます。
            config.Endpoint = "bailian.ap-southeast-1.aliyuncs.com";
            return new AlibabaCloud.SDK.Bailian20231229.Client(config);
        }

        /// <summary>
        /// 指定されたナレッジベースから情報を取得します。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="indexId">ナレッジベース ID。</param>
        /// <param name="query">検索クエリ。</param>
        /// <returns>Model Studio サービスからのレスポンス。</returns>
        /// <exception cref="Exception">呼び出しが失敗した場合に例外がスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.RetrieveResponse RetrieveIndex(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string indexId,
            string query)
        {
            var headers = new Dictionary<string, string>() { };
            var retrieveRequest = new AlibabaCloud.SDK.Bailian20231229.Models.RetrieveRequest
            {
                IndexId = indexId,
                Query = query
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.RetrieveWithOptions(workspaceId, retrieveRequest, headers, runtime);
        }

        /// <summary>
        /// Model Studio サービスを使用してナレッジベースから取得します。
        /// </summary>
        public static void Main(string[] args)
        {
            if (!CheckEnvironmentVariables())
            {
                Console.WriteLine("環境変数の検証に失敗しました。");
                return;
            }

            try
            {
                // ステップ 1: クライアントを作成します。
                Console.WriteLine("ステップ 1: クライアントを作成します。");
                AlibabaCloud.SDK.Bailian20231229.Client client = CreateClient();

                // ステップ 2: ナレッジベースから取得します。
                Console.WriteLine("ステップ 2: ナレッジベースから取得します。");
                Console.Write("ナレッジベース ID を入力してください: "); // これは CreateIndex 操作によって返される Data.Id 値です。Model Studio コンソールのナレッジベースページからも取得できます。
                string indexId = Console.ReadLine();
                Console.Write("検索クエリを入力してください: ");
                string query = Console.ReadLine();
                string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
                AlibabaCloud.SDK.Bailian20231229.Models.RetrieveResponse resp = RetrieveIndex(client, workspaceId, indexId, query);

                // Newtonsoft.Json をインストールして、レスポンスボディを JSON 文字列に変換します。
                var mapper = new JsonSerializerSettings { Formatting = Formatting.Indented };
                string result = JsonConvert.SerializeObject(resp.Body, mapper);
                Console.WriteLine(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("エラーが発生しました: " + e.Message);
            }
        }
    }
}

Go

// このサンプルコードは参照用です。本番環境で直接使用しないでください。
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	bailian20231229 "github.com/alibabacloud-go/bailian-20231229/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

// checkEnvironmentVariables は、必要な環境変数を確認し、不足しているものを報告します。
func checkEnvironmentVariables() bool {
	// 必要な環境変数とその説明。
	requiredVars := map[string]string{
		"ALIBABA_CLOUD_ACCESS_KEY_ID":     "ご利用の Alibaba Cloud AccessKey ID",
		"ALIBABA_CLOUD_ACCESS_KEY_SECRET": "ご利用の Alibaba Cloud AccessKey secret",
		"WORKSPACE_ID":                    "ご利用の Model Studio ワークスペース ID",
	}

	var missingVars []string
	for varName, desc := range requiredVars {
		if os.Getenv(varName) == "" {
			fmt.Printf("エラー: %s 環境変数を設定してください。\n", varName, desc)
			missingVars = append(missingVars, varName)
		}
	}

	return len(missingVars) == 0
}

// createClient は、クライアントを作成して設定します。
//
// 戻り値:
//   - *bailian20231229.Client: 設定済みのクライアント。
//   - error: エラーメッセージ。
func createClient() (_result *bailian20231229.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// これはパブリッククラウドのエンドポイントです。必要に応じて変更できます。
	config.Endpoint = tea.String("bailian.ap-southeast-1.aliyuncs.com")
	_result = &bailian20231229.Client{}
	_result, _err = bailian20231229.NewClient(config)
	return _result, _err
}

// retrieveIndex は、指定されたナレッジベースから情報を取得します。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): ナレッジベース ID。
//   - query (string): 検索クエリ。
//
// 戻り値:
//   - *bailian20231229.RetrieveResponse: Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func retrieveIndex(client *bailian20231229.Client, workspaceId, indexId, query string) (*bailian20231229.RetrieveResponse, error) {
	headers := make(map[string]*string)
	request := &bailian20231229.RetrieveRequest{
		IndexId: tea.String(indexId),
		Query:   tea.String(query),
	}
	runtime := &util.RuntimeOptions{}
	return client.RetrieveWithOptions(tea.String(workspaceId), request, headers, runtime)
}

// main は、プログラムのエントリポイントです。
func main() {
	if !checkEnvironmentVariables() {
		fmt.Println("環境変数の検証に失敗しました。")
		return
	}

	// ステップ 1: クライアントを作成します。
	fmt.Println("ステップ 1: クライアントを作成します。")
	client, err := createClient()
	if err != nil {
		fmt.Println("クライアントの作成に失敗しました:", err)
		return
	}

	// ステップ 2: ナレッジベースから取得します。
	fmt.Println("ステップ 2: ナレッジベースから取得します。")
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("ナレッジベース ID を入力してください: ") // これは CreateIndex 操作によって返される Data.Id 値です。Model Studio コンソールのナレッジベースページからも取得できます。
	indexId, _ := reader.ReadString('\n')
	indexId = strings.TrimSpace(indexId)
	fmt.Print("検索クエリを入力してください: ")
	query, _ := reader.ReadString('\n')
	query = strings.TrimSpace(query)
	workspaceId := os.Getenv("WORKSPACE_ID")
	resp, err := retrieveIndex(client, workspaceId, indexId, query)
	if err != nil {
		fmt.Printf("取得に失敗しました: %v\n", err)
		return
	}
        jsonStr, _ := util.ToJSONString(resp.Body)
        fmt.Println(tea.StringValue(jsonStr))
}

ナレッジベースの更新

重要
  • この例を呼び出す前に、前提条件を完了してください。RAM ユーザーを使用する場合は、AliyunBailianDataFullAccess ポリシーを RAM ユーザーに付与してください。

  • IDE またはその他の開発プラグインを使用する場合は、ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET、および WORKSPACE_ID 環境変数を設定してください。

Python

# このサンプルコードは参照用です。本番環境では使用しないでください。
import hashlib
import os
import time

import requests
from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models


def check_environment_variables():
    """必要な環境変数を確認し、不足しているものがあればプロンプトを表示します。"""
    required_vars = {
        'ALIBABA_CLOUD_ACCESS_KEY_ID': 'Alibaba Cloud AccessKey ID',
        'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'Alibaba Cloud AccessKey secret',
        'WORKSPACE_ID': 'Model Studio workspace ID'
    }
    missing_vars = []
    for var, description in required_vars.items():
        if not os.environ.get(var):
            missing_vars.append(var)
            print(f"エラー: {var} 環境変数を設定してください ({description})。")
    
    return len(missing_vars) == 0


# クライアントを作成します。
def create_client() -> bailian20231229Client:
    """
    クライアントを作成して設定します。

    Returns:
        bailian20231229Client: 設定済みのクライアント。
    """
    config = open_api_models.Config(
        access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
    # これはパブリックエンドポイントです。必要に応じて変更できます。
    config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
    return bailian20231229Client(config)


def calculate_md5(file_path: str) -> str:
    """
    ファイルの MD5 ハッシュを計算します。

    Args:
        file_path (str): ファイルのローカルパス。

    Returns:
        str: ファイルの MD5 ハッシュ。
    """
    md5_hash = hashlib.md5()

    # ファイルをバイナリモードで読み込みます。
    with open(file_path, "rb") as f:
        # 大きなファイルの場合、メモリ使用量を抑えるためにチャンクで読み込みます。
        for chunk in iter(lambda: f.read(4096), b""):
            md5_hash.update(chunk)

    return md5_hash.hexdigest()


def get_file_size(file_path: str) -> int:
    """
    ファイルのサイズをバイト単位で取得します。
    Args:
        file_path (str): ファイルのローカルパス。
    Returns:
        int: ファイルサイズ (バイト単位)。
    """
    return os.path.getsize(file_path)


# ファイルアップロードリースを申請します。
def apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id):
    """
    Model Studio サービスからファイルアップロードリースを申請します。

    Args:
        client (bailian20231229Client): クライアント。
        category_id (str): カテゴリ ID。
        file_name (str): ファイルの名前。
        file_md5 (str): ファイルの MD5 ハッシュ。
        file_size (int): ファイルサイズ (バイト単位)。
        workspace_id (str): ワークスペース ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    request = bailian_20231229_models.ApplyFileUploadLeaseRequest(
        file_name=file_name,
        md_5=file_md5,
        size_in_bytes=file_size,
    )
    runtime = util_models.RuntimeOptions()
    return client.apply_file_upload_lease_with_options(category_id, workspace_id, request, headers, runtime)


# ファイルを一時ストレージにアップロードします。
def upload_file(pre_signed_url, headers, file_path):
    """
    Model Studio サービスにファイルをアップロードします。
    Args:
        pre_signed_url (str): アップロードリースからの URL。
        headers (dict): アップロード用のリクエストヘッダー。
        file_path (str): ファイルのローカルパス。
    """
    with open(file_path, 'rb') as f:
        file_content = f.read()
    upload_headers = {
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type": headers["Content-Type"]
    }
    response = requests.put(pre_signed_url, data=file_content, headers=upload_headers)
    response.raise_for_status()


# ファイルをカテゴリに追加します。
def add_file(client: bailian20231229Client, lease_id: str, parser: str, category_id: str, workspace_id: str):
    """
    Model Studio サービスの指定されたカテゴリにファイルを追加します。

    Args:
        client (bailian20231229Client): クライアント。
        lease_id (str): リース ID。
        parser (str): ファイルに使用するパーサー。
        category_id (str): カテゴリ ID。
        workspace_id (str): ワークスペース ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    request = bailian_20231229_models.AddFileRequest(
        lease_id=lease_id,
        parser=parser,
        category_id=category_id,
    )
    runtime = util_models.RuntimeOptions()
    return client.add_file_with_options(workspace_id, request, headers, runtime)


# ファイルの解析ステータスをクエリします。
def describe_file(client, workspace_id, file_id):
    """
    ファイルの解析ステータスをクエリします。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        file_id (str): ファイル ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    runtime = util_models.RuntimeOptions()
    return client.describe_file_with_options(workspace_id, file_id, headers, runtime)


# ドキュメントを追加するジョブを送信します。
def submit_index_add_documents_job(client, workspace_id, index_id, file_id, source_type):
    """
    解析済みのファイルをナレッジベースに追加します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        file_id (str): ファイル ID。
        source_type(str): データの型。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    submit_index_add_documents_job_request = bailian_20231229_models.SubmitIndexAddDocumentsJobRequest(
        index_id=index_id,
        document_ids=[file_id],
        source_type=source_type
    )
    runtime = util_models.RuntimeOptions()
    return client.submit_index_add_documents_job_with_options(workspace_id, submit_index_add_documents_job_request,
                                                              headers, runtime)


# ドキュメント追加ジョブが完了するのを待ちます。
def get_index_job_status(client, workspace_id, job_id, index_id):
    """
    インデックスジョブのステータスをクエリします。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        job_id (str): ジョブ ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
        index_id=index_id,
        job_id=job_id
    )
    runtime = util_models.RuntimeOptions()
    return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)


# 古いファイルを削除します。
def delete_index_document(client, workspace_id, index_id, file_id):
    """
    指定されたナレッジベースから 1 つ以上のファイルを永久に削除します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        file_id (str): ファイル ID。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    delete_index_document_request = bailian_20231229_models.DeleteIndexDocumentRequest(
        index_id=index_id,
        document_ids=[file_id]
    )
    runtime = util_models.RuntimeOptions()
    return client.delete_index_document_with_options(workspace_id, delete_index_document_request, headers, runtime)


def update_knowledge_base(
        file_path: str,
        workspace_id: str,
        index_id: str,
        old_file_id: str
):
    """
    Model Studio のナレッジベースを更新します。
    Args:
        file_path (str): 更新されたファイルのローカルパス。
        workspace_id (str): ワークスペース ID。
        index_id (str): 更新するナレッジベースの ID。
        old_file_id (str): 置き換えられるファイルの FileId。
    Returns:
        str or None: 成功した場合はナレッジベース ID、それ以外の場合は None。
    """
    # デフォルト値を設定します。
    category_id = 'default'
    parser = 'DASHSCOPE_DOCMIND'
    source_type = 'DATA_CENTER_FILE'
    try:
        # ステップ 1: クライアントを作成します。
        print("ステップ 1: クライアントを作成します。")
        client = create_client()
        # ステップ 2: ファイル情報を準備します。
        print("ステップ 2: ファイル情報を準備します。")
        file_name = os.path.basename(file_path)
        file_md5 = calculate_md5(file_path)
        file_size = get_file_size(file_path)
        # ステップ 3: Model Studio からアップロードリースを申請します。
        print("ステップ 3: Model Studio からアップロードリースを申請します。")
        lease_response = apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id)
        lease_id = lease_response.body.data.file_upload_lease_id
        upload_url = lease_response.body.data.param.url
        upload_headers = lease_response.body.data.param.headers
        # ステップ 4: ファイルを一時ストレージにアップロードします。
        print("ステップ 4: ファイルを一時ストレージにアップロードします。")
        upload_file(upload_url, upload_headers, file_path)
        # ステップ 5: ファイルをカテゴリに追加します。
        print("ステップ 5: ファイルをカテゴリに追加します。")
        add_response = add_file(client, lease_id, parser, category_id, workspace_id)
        file_id = add_response.body.data.file_id
        # ステップ 6: Model Studio でファイルステータスを確認します。
        print("ステップ 6: Model Studio でファイルステータスを確認します。")
        while True:
            describe_response = describe_file(client, workspace_id, file_id)
            status = describe_response.body.data.status
            print(f"現在のファイルステータス: {status}")
            if status == 'INIT':
                print("ファイルは解析待ちです。お待ちください...")
            elif status == 'PARSING':
                print("ファイルは解析中です。お待ちください...")
            elif status == 'PARSE_SUCCESS':
                print("ファイルの解析が正常に完了しました。")
                break
            else:
                print(f"不明なファイルステータス: {status}。テクニカルサポートにお問い合わせください。")
                return None
            time.sleep(5)
        # ステップ 7: ドキュメントを追加するジョブを送信します。
        print("ステップ 7: ドキュメントを追加するジョブを送信します。")
        index_add_response = submit_index_add_documents_job(client, workspace_id, index_id, file_id, source_type)
        job_id = index_add_response.body.data.id
        # ステップ 8: インデックス作成ジョブが完了するのを待ちます。
        print("ステップ 8: インデックス作成ジョブが完了するのを待ちます。")
        while True:
            get_index_job_status_response = get_index_job_status(client, workspace_id, job_id, index_id)
            status = get_index_job_status_response.body.data.status
            print(f"現在のインデックスジョブのステータス: {status}")
            if status == 'COMPLETED':
                break
            time.sleep(5)
        # ステップ 9: 古いファイルを削除します。
        print("ステップ 9: 古いファイルを削除します。")
        delete_index_document(client, workspace_id, index_id, old_file_id)
        print("Model Studio ナレッジベースが正常に更新されました。")
        return index_id
    except Exception as e:
        print(f"エラーが発生しました: {e}")
        return None


def main():
    if not check_environment_variables():
        print("環境変数チェックに失敗しました。")
        return
    file_path = input("更新されたファイルのローカルパスを入力してください (例: Linux システムの場合 /path/to/Model_Studio_Phone_Series_Introduction.docx):")
    index_id = input("更新するナレッジベースの ID を入力してください: ")  # これは CreateIndex 操作によって返される Data.Id です。Model Studio コンソールのナレッジベースページからも取得できます。
    old_file_id = input("置き換えられるファイルの FileId を入力してください: ")  # これは AddFile 操作によって返される FileId です。Model Studio コンソールのアプリケーションデータページでファイル名の横にある ID アイコンをクリックして取得することもできます。
    workspace_id = os.environ.get('WORKSPACE_ID')
    update_knowledge_base(file_path, workspace_id, index_id, old_file_id)


if __name__ == '__main__':
    main()

Java

indexId// このサンプルコードは参照用です。本番環境では使用しないでください。
import com.aliyun.bailian20231229.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.*;

public class KnowledgeBaseUpdate {

    /**
     * 必須の環境変数を確認し、不足している場合はプロンプトを表示します。
     *
     * @return 必須の環境変数がすべて設定されている場合は true、それ以外の場合は false。
     */
    public static boolean checkEnvironmentVariables() {
        Map<String, String> requiredVars = new HashMap<>();
        requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_ID", "Alibaba Cloud AccessKey ID");
        requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "Alibaba Cloud AccessKey Secret");
        requiredVars.put("WORKSPACE_ID", "Alibaba Cloud Model Studio ワークスペース ID");

        List<String> missingVars = new ArrayList<>();
        for (Map.Entry<String, String> entry : requiredVars.entrySet()) {
            String value = System.getenv(entry.getKey());
            if (value == null || value.isEmpty()) {
                missingVars.add(entry.getKey());
                System.out.println("エラー: " + entry.getKey() + " 環境変数を設定してください (" + entry.getValue() + ")");
            }
        }

        return missingVars.isEmpty();
    }

    /**
     * クライアントを作成して設定します。
     *
     * @return 設定済みのクライアント。
     */
    public static com.aliyun.bailian20231229.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // 以下はパブリックエンドポイントです。お使いのリージョンに合わせて変更してください。
        config.endpoint = "bailian.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.bailian20231229.Client(config);
    }

    /**
     * ファイルの MD5 ハッシュを計算します。
     *
     * @param filePath ファイルのローカルパス。
     * @return ファイルの MD5 ハッシュ。
     */
    public static String calculateMD5(String filePath) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : md.digest()) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }

    /**
     * ファイルのサイズをバイト単位で取得します。
     *
     * @param filePath ファイルのローカルパス。
     * @return ファイルサイズ (バイト単位)。
     */
    public static String getFileSize(String filePath) {
        File file = new File(filePath);
        long fileSize = file.length();
        return String.valueOf(fileSize);
    }

    /**
     * ファイルアップロードリースをリクエストします。
     *
     * @param client クライアントオブジェクト。
     * @param categoryId カテゴリ ID。
     * @param fileName ファイル名。
     * @param fileMd5 ファイルの MD5 ハッシュ。
     * @param fileSize ファイルサイズ (バイト単位)。
     * @param workspaceId ワークスペース ID。
     * @return ファイルアップロードリースを含む応答。
     */
    public static ApplyFileUploadLeaseResponse applyLease(com.aliyun.bailian20231229.Client client, String categoryId, String fileName, String fileMd5, String fileSize, String workspaceId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = new com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest();
        applyFileUploadLeaseRequest.setFileName(fileName);
        applyFileUploadLeaseRequest.setMd5(fileMd5);
        applyFileUploadLeaseRequest.setSizeInBytes(fileSize);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        ApplyFileUploadLeaseResponse applyFileUploadLeaseResponse = null;
        applyFileUploadLeaseResponse = client.applyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
        return applyFileUploadLeaseResponse;
    }

    /**
     * ファイルを一時ストレージにアップロードします。
     *
     * @param preSignedUrl アップロードリースからの署名付き URL。
     * @param headers アップロード用のリクエストヘッダー。
     * @param filePath ファイルのローカルパス。
     * @throws Exception アップロード中にエラーが発生した場合。
     */
    public static void uploadFile(String preSignedUrl, Map<String, String> headers, String filePath) throws Exception {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IllegalArgumentException("ファイルが存在しないか、通常のファイルではありません: " + filePath);
        }

        try (FileInputStream fis = new FileInputStream(file)) {
            URL url = new URL(preSignedUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("PUT");
            conn.setDoOutput(true);

            // アップロードリクエストヘッダーを設定します。
            conn.setRequestProperty("X-bailian-extra", headers.get("X-bailian-extra"));
            conn.setRequestProperty("Content-Type", headers.get("Content-Type"));

            // ファイルをチャンクで読み取り、アップロードします。
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                conn.getOutputStream().write(buffer, 0, bytesRead);
            }

            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new RuntimeException("アップロードに失敗しました: " + responseCode);
            }
        }
    }

    /**
     * ファイルをカテゴリに追加します。
     *
     * @param client クライアントオブジェクト。
     * @param leaseId リース ID。
     * @param parser ファイルのパーサー。
     * @param categoryId カテゴリ ID。
     * @param workspaceId ワークスペース ID。
     * @return 新しいファイルの ID を含む応答。
     */
    public static AddFileResponse addFile(com.aliyun.bailian20231229.Client client, String leaseId, String parser, String categoryId, String workspaceId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.AddFileRequest addFileRequest = new com.aliyun.bailian20231229.models.AddFileRequest();
        addFileRequest.setLeaseId(leaseId);
        addFileRequest.setParser(parser);
        addFileRequest.setCategoryId(categoryId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.addFileWithOptions(workspaceId, addFileRequest, headers, runtime);
    }

    /**
     * ファイルの基本情報を取得します。
     *
     * @param client クライアントオブジェクト。
     * @param workspaceId ワークスペース ID。
     * @param fileId ファイル ID。
     * @return ファイルの情報を含む応答。
     */
    public static DescribeFileResponse describeFile(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
    }

    /**
     * ドキュメントをナレッジベースインデックスに追加するジョブを送信します。
     *
     * @param client クライアント。
     * @param workspaceId ワークスペース ID。
     * @param indexId ナレッジベース ID。
     * @param fileId ファイル ID。
     * @param sourceType データの型。
     * @return ジョブ ID を含む応答。
     */
    public static SubmitIndexAddDocumentsJobResponse submitIndexAddDocumentsJob(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String fileId, String sourceType) throws Exception {
        Map<String, String> headers = new HashMap<>();
        SubmitIndexAddDocumentsJobRequest submitIndexAddDocumentsJobRequest = new SubmitIndexAddDocumentsJobRequest();
        submitIndexAddDocumentsJobRequest.setIndexId(indexId);
        submitIndexAddDocumentsJobRequest.setDocumentIds(Collections.singletonList(fileId));
        submitIndexAddDocumentsJobRequest.setSourceType(sourceType);
        RuntimeOptions runtime = new RuntimeOptions();
        return client.submitIndexAddDocumentsJobWithOptions(workspaceId, submitIndexAddDocumentsJobRequest, headers, runtime);
    }

    /**
     * インデックスジョブのステータスを照会します。
     *
     * @param client クライアントオブジェクト。
     * @param workspaceId ワークスペース ID。
     * @param jobId ジョブ ID。
     * @param indexId ナレッジベース ID。
     * @return インデックスジョブのステータスを含む応答。
     */
    public static GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest();
        getIndexJobStatusRequest.setIndexId(indexId);
        getIndexJobStatusRequest.setJobId(jobId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        GetIndexJobStatusResponse getIndexJobStatusResponse = null;
        getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
        return getIndexJobStatusResponse;
    }

    /**
     * ナレッジベースインデックスからドキュメントを削除します。
     *
     * @param client クライアント。
     * @param workspaceId ワークスペース ID。
     * @param indexId ナレッジベース ID。
     * @param fileId ファイル ID。
     * @return Alibaba Cloud Model Studio サービスからの応答。
     */
    public static DeleteIndexDocumentResponse deleteIndexDocument(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String fileId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        DeleteIndexDocumentRequest deleteIndexDocumentRequest = new DeleteIndexDocumentRequest();
        deleteIndexDocumentRequest.setIndexId(indexId);
        deleteIndexDocumentRequest.setDocumentIds(Collections.singletonList(fileId));
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.deleteIndexDocumentWithOptions(workspaceId, deleteIndexDocumentRequest, headers, runtime);
    }

    /**
     * Alibaba Cloud Model Studio サービスを使用してナレッジベースを更新します。
     *
     * @param filePath 更新されたファイルのローカルパス。
     * @param workspaceId ワークスペース ID。
     * @param indexId 更新するナレッジベースの ID。
     * @param oldFileId 置き換えられるファイルの ID。
     * @return 更新が成功した場合は <code data-tag="inlineCode" id="f2f7a6c754l0e">indexId

PHP

<?php
// このサンプルコードは参照用です。本番環境では使用しないでください。
namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\SDK\Bailian\V20231229\Bailian;
use AlibabaCloud\SDK\Bailian\V20231229\Models\AddFileRequest;
use \Exception;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Bailian\V20231229\Models\ApplyFileUploadLeaseRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\DeleteIndexDocumentRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\GetIndexJobStatusRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\SubmitIndexAddDocumentsJobRequest;

class KnowledgeBaseUpdate {

    /**
    * 必要な環境変数が設定されているか確認します。
    *
    * @return bool 必要な環境変数がすべて設定されていれば true、そうでなければ false を返します。
    */
    public static function checkEnvironmentVariables() {
        $requiredVars = [
            'ALIBABA_CLOUD_ACCESS_KEY_ID' => 'Alibaba Cloud AccessKey ID',
            'ALIBABA_CLOUD_ACCESS_KEY_SECRET' => 'Alibaba Cloud AccessKey secret',
            'WORKSPACE_ID' => 'Alibaba Cloud Model Studio workspace ID'
        ];
        $missingVars = [];
        foreach ($requiredVars as $var => $description) {
            if (!getenv($var)) {
                $missingVars[] = $var;
                echo "エラー: {$var} 環境変数を設定してください ({$description})\n";
            }
        }
        return count($missingVars) === 0;
    }

    /**
     * ファイルの MD5 ハッシュを計算します。
     *
     * @param string $filePath ファイルのローカルパス。
     * @return string ファイルの MD5 ハッシュ。
     */
    public static function calculateMd5($filePath) {
        $md5Hash = hash_init("md5");
        $handle = fopen($filePath, "rb");
        while (!feof($handle)) {
            $chunk = fread($handle, 4096);
            hash_update($md5Hash, $chunk);
        }
        fclose($handle);
        return hash_final($md5Hash);
    }

    /**
     * ファイルのサイズをバイト単位で取得します。
     *
     * @param string $filePath ファイルのローカルパス。
     * @return int ファイルサイズ (バイト単位)。
     */
    public static function getFileSize($filePath) {
        return (string)filesize($filePath);
    }

    /**
     * クライアントを初期化します。
     *
     * @return Bailian 設定済みのクライアントオブジェクト。
     */
    public static function createClient(){
        $config = new Config([
            "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
            "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        ]);
        // 以下のエンドポイントはアジアパシフィック SE 1 (シンガポール) リージョン用です。必要に応じてエンドポイントを変更できます。
        $config->endpoint = 'bailian.ap-southeast-1.aliyuncs.com';
        return new Bailian($config);
    }

    /**
     * ファイルアップロードリースをリクエストします。
     *
     * @param Bailian $client クライアント。
     * @param string $categoryId カテゴリ ID。
     * @param string $fileName ファイル名。
     * @param string $fileMd5 ファイルの MD5 ハッシュ。
     * @param int $fileSize ファイルサイズ (バイト単位)。
     * @param string $workspaceId ワークスペース ID。
     * @return ApplyFileUploadLeaseResponse Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static function applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId) {
        $headers = [];
        $applyFileUploadLeaseRequest = new ApplyFileUploadLeaseRequest([
            "fileName" => $fileName,
            "md5" => $fileMd5,
            "sizeInBytes" => $fileSize
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->applyFileUploadLeaseWithOptions($categoryId, $workspaceId, $applyFileUploadLeaseRequest, $headers, $runtime);
    }

    /**
     * ファイルを一時ストレージにアップロードします。
    *
    * @param string $preSignedUrl アップロードリース内の URL。
    * @param array $headers アップロード用のリクエストヘッダー。
    * @param string $filePath ファイルのローカルパス。
    */
    public static function uploadFile($preSignedUrl, $headers, $filePath) {
        $fileContent = file_get_contents($filePath);
        // アップロードリクエストヘッダーを設定します。
        $uploadHeaders = [
            "X-bailian-extra" => $headers["X-bailian-extra"],
            "Content-Type" => $headers["Content-Type"]
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function($key, $value) {
            return "$key: $value";
        }, array_keys($uploadHeaders), $uploadHeaders));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            throw new Exception("アップロードに失敗しました: " . curl_error($ch));
        }
        curl_close($ch);
    }

    /**
     * ファイルをカテゴリに追加します。
     *
     * @param Bailian $client クライアント。
     * @param string $leaseId リース ID。
     * @param string $parser ファイルのパーサー。
     * @param string $categoryId カテゴリ ID。
     * @param string $workspaceId ワークスペース ID。
     * @return AddFileResponse Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static function addFile($client, $leaseId, $parser, $categoryId, $workspaceId) {
        $headers = [];
        $addFileRequest = new AddFileRequest([
            "leaseId" => $leaseId,
            "parser" => $parser,
            "categoryId" => $categoryId
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->addFileWithOptions($workspaceId, $addFileRequest, $headers, $runtime);
    }

    /**
     * ファイルに関する情報を取得します。
     *
     * @param Bailian $client クライアント。
     * @param string $workspaceId ワークスペース ID。
     * @param string $fileId ファイル ID。
     * @return DescribeFileResponse Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static function describeFile($client, $workspaceId, $fileId) {
        $headers = [];
        $runtime = new RuntimeOptions([]);
        return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
    }

    /**
     * 解析済みのファイルをナレッジベースに追加します。
     *
     * @param Bailian $client クライアントオブジェクト。
     * @param string $workspaceId ワークスペース ID。
     * @param string $indexId ナレッジベース ID。
     * @param string $fileId ファイル ID。
     * @param string $sourceType データの型。
     * @return SubmitIndexAddDocumentsJobResponse Alibaba Cloud Model Studio サービスからのレスポンス。
     * @throws Exception
     */
    public static function submitIndexAddDocumentsJob($client, $workspaceId, $indexId, $fileId, $sourceType) {
        $headers = [];
        $submitIndexAddDocumentsJobRequest = new SubmitIndexAddDocumentsJobRequest([
            "indexId" =>$indexId,
            "sourceType" => $sourceType,
            "documentIds" => [
                $fileId
            ]
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->submitIndexAddDocumentsJobWithOptions($workspaceId, $submitIndexAddDocumentsJobRequest, $headers, $runtime);
    }

    /**
     * インデックスジョブのステータスをクエリします。
     *
     * @param Bailian $client クライアント。
     * @param string $workspaceId ワークスペース ID。
     * @param string $indexId ナレッジベース ID。
     * @param string $jobId ジョブ ID。
     * @return GetIndexJobStatusResponse Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    public static function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
        $headers = [];
        $getIndexJobStatusRequest = new GetIndexJobStatusRequest([
            'indexId' => $indexId,
            'jobId' => $jobId
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
    }

    /**
     * ナレッジベースからファイルを永久に削除します。
     *
     * @param Bailian $client クライアントオブジェクト。
     * @param string $workspaceId ワークスペース ID。
     * @param string $indexId ナレッジベース ID。
     * @param string $fileId ファイル ID。
     * @return mixed Alibaba Cloud Model Studio サービスからのレスポンス。
     * @throws Exception
     */
    public static function deleteIndexDocument($client, $workspaceId, $indexId, $fileId) {
        $headers = [];
        $deleteIndexDocumentRequest = new DeleteIndexDocumentRequest([
            "indexId" => $indexId,
            "documentIds" => [
                $fileId
            ]
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->deleteIndexDocumentWithOptions($workspaceId, $deleteIndexDocumentRequest, $headers, $runtime);
    }

    /**
     * ナレッジベースを更新します。
     *
     * @param string $filePath 更新されたファイルのローカルパス。
     * @param string $workspaceId ワークスペース ID。
     * @param string $indexId 更新するナレッジベースの ID。
     * @param string $oldFileId 更新するファイルの FileID。
     * @return string| null 成功した場合はナレッジベース ID、失敗した場合は null。
     */
    public static function updateKnowledgeBase($filePath, $workspaceId, $indexId, $oldFileId) {
        $categoryId = "default";
        $parser = "DASHSCOPE_DOCMIND";
        $sourceType = "DATA_CENTER_FILE";

        try {
            // ステップ 1: クライアントを作成します。
            echo "ステップ 1: クライアントを作成します。\n";
            $client = self::createClient();

            // ステップ 2: ファイル情報を準備します。
            echo "ステップ 2: ファイル情報を準備します。\n";
            $fileName = basename($filePath);
            $fileMd5 = self::calculateMD5($filePath);
            $fileSize = self::getFileSize($filePath);

            // ステップ 3: アップロードリースをリクエストします。
            echo "ステップ 3: アップロードリースをリクエストします。\n";
            $leaseResponse = self::applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId);
            $leaseId = $leaseResponse->body->data->fileUploadLeaseId;
            $uploadUrl = $leaseResponse->body->data->param->url;
            $uploadHeaders = $leaseResponse->body->data->param->headers;
            $uploadHeadersMap = json_decode(json_encode($uploadHeaders), true);

            // ステップ 4: ファイルを一時ストレージにアップロードします。
            echo "ステップ 4: ファイルを一時ストレージにアップロードします。\n";
            self::uploadFile($uploadUrl, $uploadHeadersMap, $filePath);

            // ステップ 5: ファイルをカテゴリに追加します。
            echo "ステップ 5: ファイルをカテゴリに追加します。\n";
            $addResponse = self::addFile($client, $leaseId, $parser, $categoryId, $workspaceId);
            $fileId = $addResponse->body->data->fileId;

            // ステップ 6: ファイルステータスを確認します。
            echo "ステップ 6: ファイルステータスを確認します。\n";
            while (true) {
                $describeResponse = self::describeFile($client, $workspaceId, $fileId);
                $status = $describeResponse->body->data->status;
                echo "現在のファイルステータス: " . $status . "\n";

                if ($status === "INIT") {
                    echo "ファイルは解析待ちです。お待ちください...\n";
                } elseif ($status === "PARSING") {
                    echo "ファイルは解析中です。お待ちください...\n";
                } elseif ($status === "PARSE_SUCCESS") {
                    echo "ファイルは正常に解析されました。\n";
                    break;
                } else {
                    echo "不明なファイルステータス: " . $status . "。テクニカルサポートにお問い合わせください。\n";
                    return null;
                }
                sleep(5);
            }

            // ステップ 7: ファイルを追加するインデックスジョブを送信します。
            echo "ステップ 7: ファイルを追加するインデックスジョブを送信します。\n";
            $indexAddResponse = self::submitIndexAddDocumentsJob($client, $workspaceId, $indexId, $fileId, $sourceType);
            $jobId = $indexAddResponse->body->data->id;

            // ステップ 8: インデックスジョブが完了するのを待ちます。
            echo "ステップ 8: インデックスジョブが完了するのを待ちます。\n";
            while (true) {
                $jobStatusResponse = self::getIndexJobStatus($client, $workspaceId, $jobId, $indexId);
                $status = $jobStatusResponse->body->data->status;
                echo "現在のインデックスジョブのステータス: " . $status . "\n";

                if ($status === "COMPLETED") {
                    break;
                }
                sleep(5);
            }

            // ステップ 9: 古いファイルを削除します。
            echo "ステップ 9: 古いファイルを削除します。\n";
            self::deleteIndexDocument($client, $workspaceId, $indexId, $oldFileId);

            echo "ナレッジベースが正常に更新されました。\n";
            return $indexId;

        } catch (Exception $e) {
            echo "エラーが発生しました: " . $e->getMessage() . "\n";
            return null;
        }
    }


    /**
     * ナレッジベース更新プロセスを調整するためのメイン関数。
     */
    public static function main($args){
        if (!self::checkEnvironmentVariables()) {
            echo "環境変数チェックに失敗しました。\n";
            return;
        }
        $filePath = readline("アップロードするファイルのローカルパスを入力してください (例: /path/to/your_file.docx):");
        $indexId = readline("更新するナレッジベースの ID を入力してください:"); // これは CreateIndex 操作によって返される Data.Id です。Model Studio コンソールのナレッジベースページでも ID を確認できます。
        $oldFileId = readline("更新するファイルの FileID を入力してください:"); // これは AddFile 操作によって返される FileId です。Model Studio コンソールのアプリケーションデータページでファイル名の横にある ID アイコンをクリックしてファイル ID を確認することもできます。
        $workspaceId = getenv('WORKSPACE_ID');
        $result = self::updateKnowledgeBase($filePath, $workspaceId, $indexId, $oldFileId);

        if ($result !== null) {
            echo "ナレッジベースが正常に更新されました。ID: " . $result . "\n";
        } else {
            echo "ナレッジベースの更新に失敗しました。\n";
        }
    }
}
// このスクリプトは、autoload.php が親ディレクトリにあることを前提としています。プロジェクトの構造に合わせてパスを調整してください。
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
KnowledgeBaseUpdate::main(array_slice($argv, 1));

Node.js

// このサンプルコードは参照用です。本番環境では使用しないでください。
'use strict';

const fs = require('fs');
const path = require('path');
const axios = require('axios');
const crypto = require('crypto');

const bailian20231229 = require('@alicloud/bailian20231229');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');

class KbUpdate {

    /**
     * 必要な環境変数が設定されていることを確認します。
     * @returns {boolean} - 必要な環境変数がすべて設定されていれば true、そうでなければ false を返します。
     */
    static checkEnvironmentVariables() {
        const requiredVars = {
            'ALIBABA_CLOUD_ACCESS_KEY_ID': 'Alibaba Cloud AccessKey ID',
            'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'Alibaba Cloud AccessKey Secret',
            'WORKSPACE_ID': 'Alibaba Cloud Model Studio workspace ID'
        };

        const missing = [];
        for (const [varName, desc] of Object.entries(requiredVars)) {
            if (!process.env[varName]) {
                console.error(`エラー: ${varName} 環境変数を設定してください (${desc})。`);
                missing.push(varName);
            }
        }
        return missing.length === 0;
    }

    /**
     * ファイルの MD5 ハッシュを計算します。
     * @param {string} filePath - ファイルのローカルパス。
     * @returns {Promise<string>} - ファイルの MD5 ハッシュ。
     */
    static async calculateMD5(filePath) {
        const hash = crypto.createHash('md5');
        const stream = fs.createReadStream(filePath);

        return new Promise((resolve, reject) => {
            stream.on('data', chunk => hash.update(chunk));
            stream.on('end', () => resolve(hash.digest('hex')));
            stream.on('error', reject);
        });
    }

    /**
     * ファイルのサイズをバイト単位で取得し、文字列として返します。
     * @param {string} filePath - ファイルのローカルパス。
     * @returns {string} - ファイルサイズ (例: "123456")。
     */
    static getFileSize(filePath) {
        try {
            const stats = fs.statSync(filePath);
            return stats.size.toString();
        } catch (err) {
            console.error(`ファイルサイズの取得に失敗しました: ${err.message}`);
            throw err;
        }
    }

    /**
     * クライアントを作成して設定します。
     * @return Client
     * @throws Exception
     */
    static createClient() {
        const config = new OpenApi.Config({
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
        });
        // このエンドポイントは、アジアパシフィック SE 1 (シンガポール) リージョンのパブリッククラウド用です。必要に応じて変更してください。
        config.endpoint = `bailian.ap-southeast-1.aliyuncs.com`;
        return new bailian20231229.default(config);
    }

    /**
     * ファイルアップロードリースをリクエストします。
     * @param {Bailian20231229Client} client - クライアント。
     * @param {string} categoryId - カテゴリ ID。
     * @param {string} fileName - ファイル名。
     * @param {string} fileMd5 - ファイルの MD5 ハッシュ。
     * @param {string} fileSize - ファイルサイズ (バイト単位)。
     * @param {string} workspaceId - ワークスペース ID。
     * @returns {Promise<bailian20231229.ApplyFileUploadLeaseResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    static async applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId) {
        const headers = {};
        const req = new bailian20231229.ApplyFileUploadLeaseRequest({
            md5: fileMd5,
            fileName,
            sizeInBytes: fileSize
        });
        const runtime = new Util.RuntimeOptions({});
        return await client.applyFileUploadLeaseWithOptions(
            categoryId,
            workspaceId,
            req,
            headers,
            runtime
        );
    }

    /**
     * ファイルを一時ストレージにアップロードします。
     * @param {string} preSignedUrl - アップロードリースからの署名付き URL。
     * @param {Object} headers - アップロード用のリクエストヘッダー。
     * @param {string} filePath - ファイルのローカルパス。
     */
    static async uploadFile(preSignedUrl, headers, filePath) {
        const uploadHeaders = {
            "X-bailian-extra": headers["X-bailian-extra"],
            "Content-Type": headers["Content-Type"]
        };
        const stream = fs.createReadStream(filePath);
        try {
            await axios.put(preSignedUrl, stream, { headers: uploadHeaders });
        } catch (e) {
            throw new Error(`アップロードに失敗しました: ${e.message}`);
        }
    }

    /**
     * ファイルをカテゴリに追加します。
     * @param {Bailian20231229Client} client - クライアント。
     * @param {string} leaseId - リース ID。
     * @param {string} parser - ファイルのパーサー。
     * @param {string} categoryId - カテゴリ ID。
     * @param {string} workspaceId - ワークスペース ID。
     * @returns {Promise<bailian20231229.AddFileResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    static async addFile(client, leaseId, parser, categoryId, workspaceId) {
        const headers = {};
        const req = new bailian20231229.AddFileRequest({
            leaseId,
            parser,
            categoryId
        });
        const runtime = new Util.RuntimeOptions({});
        return await client.addFileWithOptions(workspaceId, req, headers, runtime);
    }

    /**
     * ファイルの解析ステータスをクエリします。
     * @param {Bailian20231229Client} client - クライアント。
     * @param {string} workspaceId - ワークスペース ID。
     * @param {string} fileId - ファイル ID。
     * @returns {Promise<bailian20231229.DescribeFileResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    static async describeFile(client, workspaceId, fileId) {
        const headers = {};
        const runtime = new Util.RuntimeOptions({});
        return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
    }

    /**
     * インデックスにドキュメントを追加するジョブを送信します。
     * @param {Bailian20231229Client} client - クライアント。
     * @param {string} workspaceId - ワークスペース ID。
     * @param {string} indexId - ナレッジベース ID。
     * @param {string} fileId - ファイル ID。
     * @param {string} sourceType - データの型。
     * @returns {Promise<bailian20231229.SubmitIndexAddDocumentsJobResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    static async submitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType) {
        const headers = {};
        const req = new bailian20231229.SubmitIndexAddDocumentsJobRequest({
            indexId,
            documentIds: [fileId],
            sourceType,
        });
        const runtime = new Util.RuntimeOptions({});
        return await client.submitIndexAddDocumentsJobWithOptions(workspaceId, req, headers, runtime);
    }

    /**
     * インデックスジョブのステータスをクエリします。
     * @param {Bailian20231229Client} client - クライアント。
     * @param {string} workspaceId - ワークスペース ID。
     * @param {string} jobId - ジョブ ID。
     * @param {string} indexId - ナレッジベース ID。
     * @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    static async getIndexJobStatus(client, workspaceId, jobId, indexId) {
        const headers = {};
        const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId });
        const runtime = new Util.RuntimeOptions({});
        return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime);
    }

    /**
     * ナレッジベースインデックスからドキュメントを削除します。
     * @param {Bailian20231229Client} client - クライアント。
     * @param {string} workspaceId - ワークスペース ID。
     * @param {string} indexId - ナレッジベース ID。
     * @param {string} fileId - 削除するドキュメントの ID。
     * @returns {Promise<bailian20231229.DeleteIndexDocumentResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
     */
    static async deleteIndexDocument(client, workspaceId, indexId, fileId) {
        const headers = {};
        const req = new bailian20231229.DeleteIndexDocumentRequest({
            indexId,
            documentIds: [fileId],
        });
        const runtime = new Util.RuntimeOptions({});
        return await client.deleteIndexDocumentWithOptions(workspaceId, req, headers, runtime);
    }

    /**
     * Alibaba Cloud Model Studio のナレッジベースを更新します。
     * @param {string} filePath - 更新されたファイルのローカルパス。
     * @param {string} workspaceId - ワークスペース ID。
     * @param {string} indexId - 更新するナレッジベースの ID。
     * @param {string} oldFileId - 置き換えるファイルの ID。
     * @returns {Promise<string | null>} - 成功した場合はナレッジベース ID、それ以外の場合は null。
     */
    static async updateKnowledgeBase(filePath, workspaceId, indexId, oldFileId) {
        const categoryId = 'default';
        const parser = 'DASHSCOPE_DOCMIND';
        const sourceType = 'DATA_CENTER_FILE';

        try {
            console.log("ステップ 1: クライアントを作成しています。");
            const client = this.createClient();

            console.log("ステップ 2: ファイル情報を準備しています。");
            const fileName = path.basename(filePath);
            const fileMd5 = await this.calculateMD5(filePath);
            const fileSize = this.getFileSize(filePath);

            console.log("ステップ 3: Alibaba Cloud Model Studio からファイルアップロードリースを申請しています。");
            const leaseRes = await this.applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
            const leaseId = leaseRes.body.data.fileUploadLeaseId;
            const uploadUrl = leaseRes.body.data.param.url;
            const uploadHeaders = leaseRes.body.data.param.headers;

            console.log("ステップ 4: ファイルを一時ストレージにアップロードしています。");
            await this.uploadFile(uploadUrl, uploadHeaders, filePath);

            console.log("ステップ 5: ファイルをカテゴリに追加しています。");
            const addRes = await this.addFile(client, leaseId, parser, categoryId, workspaceId);
            const fileId = addRes.body.data.fileId;

            console.log("ステップ 6: Alibaba Cloud Model Studio でファイルステータスを確認しています。");
            while (true) {
                const descRes = await this.describeFile(client, workspaceId, fileId);
                const status = descRes.body.data.status;
                console.log(`現在のファイルステータス: ${status}`);

                if (status === 'INIT') {
                    console.log("ファイルは解析待ちです。お待ちください...");
                } else if (status === 'PARSING') {
                    console.log("ファイルは解析中です。お待ちください...");
                } else if (status === 'PARSE_SUCCESS') {
                    console.log("ファイルは正常に解析されました。");
                    break;
                } else {
                    console.error(`不明なファイルステータス: ${status}。テクニカルサポートにお問い合わせください。`);
                    return null;
                }
                await this.sleep(5);
            }

            console.log("ステップ 7: インデックスにドキュメントを追加するジョブを送信しています。");
            const indexAddResponse = await this.submitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType);
            const jobId = indexAddResponse.body.data.id;

            console.log("ステップ 8: インデックス作成ジョブが完了するのを待っています。");
            while (true) {
                const getJobStatusResponse = await this.getIndexJobStatus(client, workspaceId, jobId, indexId);
                const status = getJobStatusResponse.body.data.status;
                console.log(`現在のインデックス作成ジョブのステータス: ${status}`);
                if (status === 'COMPLETED') {
                    break;
                }
                await this.sleep(5);
            }

            console.log("ステップ 9: インデックスから古いドキュメントを削除しています。");
            await this.deleteIndexDocument(client, workspaceId, indexId, oldFileId);

            console.log("ナレッジベースが正常に更新されました。");
            return indexId;
        } catch (e) {
            console.error(`エラーが発生しました: ${e.message}`);
            return null;
        }
    }

    /**
     * 指定された秒数待機します。
     * @param {number} seconds - 待機時間 (秒)。
     * @returns {Promise<void>}
     */
    static sleep(seconds) {
        return new Promise(resolve => setTimeout(resolve, seconds * 1000));
    }

    static async main(args) {
        if (!this.checkEnvironmentVariables()) {
            console.log("環境変数チェックに失敗しました。");
            return;
        }

        const readline = require('readline').createInterface({
            input: process.stdin,
            output: process.stdout
        });

        try {
            const filePath = await new Promise((resolve, reject) => {
                readline.question("更新されたファイルのローカルパスを入力してください (例: Linux の場合 /home/user/Alibaba_Cloud_Model_Studio_Phone_Series_Introduction.docx):", (ans) => {
                    ans.trim() ? resolve(ans) : reject(new Error("パスは空にできません。"));
                });
            });
            const indexId = await new Promise((resolve, reject) => {
                // ナレッジベース ID は、CreateIndex 操作によって返される Data.Id です。Model Studio コンソールのナレッジベースページでもこの ID を確認できます。
                readline.question("更新するナレッジベース ID を入力してください:", (ans) => {
                    ans.trim() ? resolve(ans) : reject(new Error("ナレッジベース ID は空にできません。"));
                });
            });
            const oldFileId = await new Promise((resolve, reject) => {
                // ファイル ID は、AddFile 操作によって返される FileId です。Model Studio コンソールのアプリケーションデータページでファイル名の横にある ID アイコンをクリックしてファイル ID を確認することもできます。
                readline.question("置き換えるファイルの ID を入力してください:", (ans) => {
                    ans.trim() ? resolve(ans) : reject(new Error("ファイル ID は空にできません。"));
                });
            });
            const workspaceId = process.env.WORKSPACE_ID;

            const result = await this.updateKnowledgeBase(filePath, workspaceId, indexId, oldFileId);
            if (result) console.log(`ナレッジベース ID: ${result}`);
            else console.log("ナレッジベースの更新に失敗しました。");
        } catch (err) {
            console.error(err.message);
        } finally {
            readline.close();
        }
    }
}

exports.KbUpdate = KbUpdate;
KbUpdate.main(process.argv.slice(2));

C#

// このサンプルコードは参照用です。本番環境では使用しないでください。
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.KnowledgeBase
{
    public class KnowledgeBaseUpdate
    {
        /// <summary>
        /// 必要な環境変数が設定されているか確認します。
        /// </summary>
        /// <returns>必要な環境変数がすべて設定されていれば <see langword="true"/>、そうでなければ <see langword="false"/> を返します。</returns>
        public static bool CheckEnvironmentVariables()
        {
            var requiredVars = new Dictionary<string, string>
            {
                { "ALIBABA_CLOUD_ACCESS_KEY_ID", "Alibaba Cloud AccessKey ID" },
                { "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "Alibaba Cloud AccessKey Secret" },
                { "WORKSPACE_ID", "Alibaba Cloud Model Studio workspace ID" }
            };

            var missingVars = new List<string>();
            foreach (var entry in requiredVars)
            {
                string value = Environment.GetEnvironmentVariable(entry.Key);
                if (string.IsNullOrEmpty(value))
                {
                    missingVars.Add(entry.Key);
                    Console.WriteLine($"エラー: {entry.Key} ({entry.Value}) 環境変数を設定してください。");
                }
            }

            return missingVars.Count == 0;
        }

        /// <summary>
        /// ファイルの MD5 ハッシュを計算します。
        /// </summary>
        /// <param name="filePath">ファイルのローカルパス。</param>
        /// <returns>ファイルの MD5 ハッシュ。</returns>
        /// <exception cref="Exception">計算中にエラーが発生した場合にスローされます。</exception>
        public static string CalculateMD5(string filePath)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] hashBytes = md5.ComputeHash(stream);
                    StringBuilder sb = new StringBuilder();
                    foreach (byte b in hashBytes)
                    {
                        sb.Append(b.ToString("x2"));
                    }
                    return sb.ToString();
                }
            }
        }

        /// <summary>
        /// ファイルのサイズをバイト単位で取得します。
        /// </summary>
        /// <param name="filePath">ファイルのローカルパス。</param>
        /// <returns>ファイルサイズ (バイト単位)。</returns>
        public static string GetFileSize(string filePath)
        {
            var file = new FileInfo(filePath);
            return file.Length.ToString();
        }

        /// <summary>
        /// クライアントを初期化します。
        /// </summary>
        /// <returns>設定済みのクライアントオブジェクト。</returns>
        /// <exception cref="Exception">初期化中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
        {
            var config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
            // 以下のエンドポイントは、アジアパシフィック SE 1 (シンガポール) リージョンのパブリックエンドポイントです。必要に応じて変更できます。
            config.Endpoint = "bailian.ap-southeast-1.aliyuncs.com";
            return new AlibabaCloud.SDK.Bailian20231229.Client(config);
        }

        /// <summary>
        /// ファイルアップロードリースをリクエストします。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="categoryId">カテゴリ ID。</param>
        /// <param name="fileName">ファイルの名前。</param>
        /// <param name="fileMd5">ファイルの MD5 ハッシュ。</param>
        /// <param name="fileSize">ファイルサイズ (バイト単位)。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <returns>サービスからのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseResponse ApplyLease(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string categoryId,
            string fileName,
            string fileMd5,
            string fileSize,
            string workspaceId)
        {
            var headers = new Dictionary<string, string>() { };
            var applyFileUploadLeaseRequest = new AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseRequest
            {
                FileName = fileName,
                Md5 = fileMd5,
                SizeInBytes = fileSize
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.ApplyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
        }

        /// <summary>
        /// ファイルを一時ストレージにアップロードします。
        /// </summary>
        /// <param name="preSignedUrl">アップロードリースからの署名付き URL。</param>
        /// <param name="headers">アップロード用のリクエストヘッダー。</param>
        /// <param name="filePath">ファイルのローカルパス。</param>
        /// <exception cref="Exception">アップロード中にエラーが発生した場合にスローされます。</exception>
        public static void UploadFile(string preSignedUrl, Dictionary<string, string> headers, string filePath)
        {
            var file = new FileInfo(filePath);
            if (!File.Exists(filePath))
            {
                throw new ArgumentException($"ファイルが存在しないか、通常のファイルではありません: {filePath}");
            }

            using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                var url = new Uri(preSignedUrl);
                var conn = (HttpWebRequest)WebRequest.Create(url);
                conn.Method = "PUT";
                conn.ContentType = headers["Content-Type"];
                conn.Headers.Add("X-bailian-extra", headers["X-bailian-extra"]);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    conn.GetRequestStream().Write(buffer, 0, bytesRead);
                }

                using (var response = (HttpWebResponse)conn.GetResponse())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception($"アップロードに失敗しました。ステータスコード: {response.StatusCode}");
                    }
                }
            }
        }

        /// <summary>
        /// ファイルをカテゴリに追加します。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="leaseId">リース ID。</param>
        /// <param name="parser">ファイルに使用するパーサー。</param>
        /// <param name="categoryId">カテゴリ ID。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <returns>サービスからのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.AddFileResponse AddFile(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string leaseId,
            string parser,
            string categoryId,
            string workspaceId)
        {
            var headers = new Dictionary<string, string>() { };
            var addFileRequest = new AlibabaCloud.SDK.Bailian20231229.Models.AddFileRequest
            {
                LeaseId = leaseId,
                Parser = parser,
                CategoryId = categoryId
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.AddFileWithOptions(workspaceId, addFileRequest, headers, runtime);
        }

        /// <summary>
        /// ファイルの基本情報を取得します。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="fileId">ファイル ID。</param>
        /// <returns>サービスからのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.DescribeFileResponse DescribeFile(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string fileId)
        {
            var headers = new Dictionary<string, string>() { };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.DescribeFileWithOptions(workspaceId, fileId, headers, runtime);
        }

        /// <summary>
        /// 解析済みのファイルをドキュメント検索ナレッジベースに追加します。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="indexId">インデックス ID。</param>
        /// <param name="fileId">ファイル ID。</param>
        /// <param name="sourceType">データのソースタイプ。</param>
        /// <returns>サービスからのレスポンス。</returns>
        public static AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexAddDocumentsJobResponse SubmitIndexAddDocumentsJob(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string indexId,
            string fileId,
            string sourceType)
        {
            var headers = new Dictionary<string, string>() { };
            var submitIndexAddDocumentsJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexAddDocumentsJobRequest
            {
                IndexId = indexId,
                DocumentIds = new List<string> { fileId },
                SourceType = sourceType
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.SubmitIndexAddDocumentsJobWithOptions(workspaceId, submitIndexAddDocumentsJobRequest, headers, runtime);
        }

        /// <summary>
        /// インデックスジョブのステータスをクエリします。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="jobId">ジョブ ID。</param>
        /// <param name="indexId">インデックス ID。</param>
        /// <returns>サービスからのレスポンス。</returns>
        /// <exception cref="Exception">API 呼び出し中にエラーが発生した場合にスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string jobId,
            string indexId)
        {
            var headers = new Dictionary<string, string>() { };
            var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest
            {
                IndexId = indexId,
                JobId = jobId
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
        }

        /// <summary>
        /// ナレッジベースインデックスから 1 つ以上のドキュメントを削除します。
        /// </summary>
        /// <param name="client">クライアントオブジェクト。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="indexId">インデックス ID。</param>
        /// <param name="fileId">ファイル ID。</param>
        /// <returns>サービスからのレスポンス。</returns>
        public static AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexDocumentResponse DeleteIndexDocument(
            AlibabaCloud.SDK.Bailian20231229.Client client,
            string workspaceId,
            string indexId,
            string fileId)
        {
            var headers = new Dictionary<string, string>() { };
            var deleteIndexDocumentRequest = new AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexDocumentRequest
            {
                IndexId = indexId,
                DocumentIds = new List<string> { fileId }
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.DeleteIndexDocumentWithOptions(workspaceId, deleteIndexDocumentRequest, headers, runtime);
        }

        /// <summary>
        /// ナレッジベースを更新します。
        /// </summary>
        /// <param name="filePath">更新されたファイルのローカルパス。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="indexId">更新するインデックスの ID。</param>
        /// <param name="oldFileId">置き換えられるファイルのファイル ID。</param>
        /// <returns>成功した場合はインデックスの ID、それ以外の場合は <see langword="null"/>。</returns>
        public static string UpdateKnowledgeBase(string filePath, string workspaceId, string indexId, string oldFileId)
        {
            // デフォルト値を設定します。
            string categoryId = "default";
            string parser = "DASHSCOPE_DOCMIND";
            string sourceType = "DATA_CENTER_FILE";

            try
            {
                Console.WriteLine("ステップ 1: クライアントを作成します。");
                var client = CreateClient();

                Console.WriteLine("ステップ 2: ファイル情報を準備します。");
                string fileName = Path.GetFileName(filePath);
                string fileMd5 = CalculateMD5(filePath);
                string fileSize = GetFileSize(filePath);

                Console.WriteLine("ステップ 3: アップロードリースをリクエストします。");
                Bailian20231229.Models.ApplyFileUploadLeaseResponse leaseResponse = ApplyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId);
                string leaseId = leaseResponse.Body.Data.FileUploadLeaseId;
                string uploadUrl = leaseResponse.Body.Data.Param.Url;
                var uploadHeaders = leaseResponse.Body.Data.Param.Headers;

                Console.WriteLine("ステップ 4: ファイルを一時ストレージにアップロードします。");
                // Newtonsoft.Json パッケージがインストールされていることを確認してください。
                var uploadHeadersMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(uploadHeaders));
                UploadFile(uploadUrl, uploadHeadersMap, filePath);

                Console.WriteLine("ステップ 5: ファイルをカテゴリに追加します。");
                Bailian20231229.Models.AddFileResponse addResponse = AddFile(client, leaseId, parser, categoryId, workspaceId);
                string fileId = addResponse.Body.Data.FileId;

                Console.WriteLine("ステップ 6: ファイルステータスを確認します。");
                while (true)
                {
                    Bailian20231229.Models.DescribeFileResponse describeResponse = DescribeFile(client, workspaceId, fileId);
                    string status = describeResponse.Body.Data.Status;
                    Console.WriteLine("現在のファイルステータス: " + status);
                    if ("INIT".Equals(status))
                    {
                        Console.WriteLine("ファイルは解析待ちです。お待ちください...");
                    }
                    else if ("PARSING".Equals(status))
                    {
                        Console.WriteLine("ファイルの解析が進行中です。お待ちください...");
                    }
                    else if ("PARSE_SUCCESS".Equals(status))
                    {
                        Console.WriteLine("ファイルの解析が完了しました!");
                        break;
                    }
                    else
                    {
                        Console.WriteLine("不明なファイルステータス: " + status + "。テクニカルサポートにお問い合わせください。");
                        return null;
                    }
                    System.Threading.Thread.Sleep(5000);
                }

                Console.WriteLine("ステップ 7: ファイルをインデックスに追加するジョブを送信します。");
                Bailian20231229.Models.SubmitIndexAddDocumentsJobResponse indexAddResponse = SubmitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType);
                string jobId = indexAddResponse.Body.Data.Id;

                Console.WriteLine("ステップ 8: インデックス作成ジョブが完了するのを待ちます。");
                while (true)
                {
                    Bailian20231229.Models.GetIndexJobStatusResponse jobStatusResponse = GetIndexJobStatus(client, workspaceId, jobId, indexId);
                    string status = jobStatusResponse.Body.Data.Status;
                    Console.WriteLine("現在のインデックスジョブのステータス: " + status);
                    if ("COMPLETED".Equals(status))
                    {
                        break;
                    }
                    System.Threading.Thread.Sleep(5000);
                }

                Console.WriteLine("ステップ 9: 古いファイルを削除します。");
                DeleteIndexDocument(client, workspaceId, indexId, oldFileId);

                Console.WriteLine("ナレッジベースは正常に更新されました!");
                return indexId;
            }
            catch (Exception e)
            {
                Console.WriteLine("エラーが発生しました: " + e.Message);
                return null;
            }
        }

        /// <summary>
        /// アプリケーションのメインエントリポイント。
        /// </summary>
        public static void Main(string[] args)
        {
            if (!CheckEnvironmentVariables())
            {
                Console.WriteLine("環境変数の検証に失敗しました。");
                return;
            }

            Console.Write("アップロードするファイルのローカルパスを入力してください (例: /path/to/YourDocument.docx): ");
            string filePath = Console.ReadLine();

            Console.Write("更新するナレッジベースの ID を入力してください: "); // これは `CreateIndex` API 呼び出しによって返される `Data.Id` です。または、Alibaba Cloud Model Studio コンソールのナレッジベースページで確認できます。
            string indexId = Console.ReadLine();

            Console.Write("置き換えられるファイルのファイル ID を入力してください: "); // これは `AddFile` API 呼び出しによって返される `FileId` です。または、Alibaba Cloud Model Studio コンソールのアプリケーションデータページでファイル名の横にある ID アイコンをクリックして確認できます。
            string oldFileId = Console.ReadLine();

            string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
            string result = UpdateKnowledgeBase(filePath, workspaceId, indexId, oldFileId);
            if (result != null)
            {
                Console.WriteLine("ナレッジベースは正常に更新されました。ナレッジベース ID: " + result);
            }
            else
            {
                Console.WriteLine("ナレッジベースの更新に失敗しました。");
            }
        }
    }
}

Go

// このサンプルコードは参照用です。本番環境では使用しないでください。
package main

import (
	"bufio"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"

	bailian20231229 "github.com/alibabacloud-go/bailian-20231229/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/go-resty/resty/v2"
)

// CheckEnvironmentVariables は、必要な環境変数をチェックし、設定を促します。
func CheckEnvironmentVariables() bool {
	// 必要な環境変数とその説明。
	requiredVars := map[string]string{
		"ALIBABA_CLOUD_ACCESS_KEY_ID":     "Alibaba Cloud AccessKey ID",
		"ALIBABA_CLOUD_ACCESS_KEY_SECRET": "Alibaba Cloud AccessKey Secret",
		"WORKSPACE_ID":                    "Alibaba Cloud Model Studio workspace ID",
	}

	var missingVars []string
	for varName, desc := range requiredVars {
		if os.Getenv(varName) == "" {
			fmt.Printf("エラー: %s 環境変数を設定してください。\n", varName, desc)
			missingVars = append(missingVars, varName)
		}
	}

	return len(missingVars) == 0
}

// CalculateMD5 は、ファイルの MD5 ハッシュを計算します。
//
// パラメータ:
//   - filePath (string): ファイルのローカルパス。
//
// 戻り値:
//   - string: ファイルの MD5 ハッシュ。
//   - error: エラーメッセージ。
func CalculateMD5(filePath string) (_result string, _err error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	md5Hash := md5.New()
	_, err = io.Copy(md5Hash, file)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%x", md5Hash.Sum(nil)), nil
}

// GetFileSize は、ファイルのサイズをバイト単位で取得します。
//
// パラメータ:
//   - filePath (string): ファイルのローカルパス。
//
// 戻り値:
//   - string: ファイルサイズ (バイト単位)。
//   - error: エラーメッセージ。
func GetFileSize(filePath string) (_result string, _err error) {
	info, err := os.Stat(filePath)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%d", info.Size()), nil
}

// CreateClient は、クライアントを作成して設定します。
//
// 戻り値:
//   - *bailian20231229.Client: 設定済みのクライアント。
//   - error: エラーメッセージ。
func CreateClient() (_result *bailian20231229.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// この例では、アジアパシフィック SE 1 (シンガポール) リージョンのパブリックエンドポイントを使用しています。必要に応じてエンドポイントを変更できます。
	config.Endpoint = tea.String("bailian.ap-southeast-1.aliyuncs.com")
	_result = &bailian20231229.Client{}
	_result, _err = bailian20231229.NewClient(config)
	return _result, _err
}

// ApplyLease は、Alibaba Cloud Model Studio サービスからファイルアップロードリースをリクエストします。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - categoryId (string): カテゴリ ID。
//   - fileName (string): ファイル名。
//   - fileMD5 (string): ファイルの MD5 ハッシュ。
//   - fileSize (string): ファイルサイズ (バイト単位)。
//   - workspaceId (string): ワークスペース ID。
//
// 戻り値:
//   - *bailian20231229.ApplyFileUploadLeaseResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func ApplyLease(client *bailian20231229.Client, categoryId, fileName, fileMD5 string, fileSize string, workspaceId string) (_result *bailian20231229.ApplyFileUploadLeaseResponse, _err error) {
	headers := make(map[string]*string)
	applyFileUploadLeaseRequest := &bailian20231229.ApplyFileUploadLeaseRequest{
		FileName:    tea.String(fileName),
		Md5:         tea.String(fileMD5),
		SizeInBytes: tea.String(fileSize),
	}
	runtime := &util.RuntimeOptions{}
	return client.ApplyFileUploadLeaseWithOptions(tea.String(categoryId), tea.String(workspaceId), applyFileUploadLeaseRequest, headers, runtime)
}

// UploadFile は、Alibaba Cloud Model Studio サービスにファイルをアップロードします。
//
// パラメータ:
//   - preSignedUrl (string): アップロードリース内の URL。
//   - headers (map[string]string): アップロード用のリクエストヘッダー。
//   - filePath (string): ファイルのローカルパス。
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	body, err := io.ReadAll(file)
	if err != nil {
		return err
	}

	client := resty.New()
	uploadHeaders := map[string]string{
		"X-bailian-extra": headers["X-bailian-extra"],
		"Content-Type":    headers["Content-Type"],
	}

	resp, err := client.R().
		SetHeaders(uploadHeaders).
		SetBody(body).
		Put(preSignedUrl)

	if err != nil {
		return err
	}

	if resp.IsError() {
		return fmt.Errorf("HTTP エラー: %d", resp.StatusCode())
	}

	return nil
}

// AddFile は、Alibaba Cloud Model Studio サービスの指定されたカテゴリにファイルを追加します。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - leaseId (string): リース ID。
//   - parser (string): ファイルのパーサー。
//   - categoryId (string): カテゴリ ID。
//   - workspaceId (string): ワークスペース ID。
//
// 戻り値:
//   - *bailian20231229.AddFileResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func AddFile(client *bailian20231229.Client, leaseId, parser, categoryId, workspaceId string) (_result *bailian20231229.AddFileResponse, _err error) {
	headers := make(map[string]*string)
	addFileRequest := &bailian20231229.AddFileRequest{
		LeaseId:    tea.String(leaseId),
		Parser:     tea.String(parser),
		CategoryId: tea.String(categoryId),
	}
	runtime := &util.RuntimeOptions{}
	return client.AddFileWithOptions(tea.String(workspaceId), addFileRequest, headers, runtime)
}

// DescribeFile は、ファイルの基本情報を取得します。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - fileId (string): ファイル ID。
//
// 戻り値:
//   - *bailian20231229.DescribeFileResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func DescribeFile(client *bailian20231229.Client, workspaceId, fileId string) (_result *bailian20231229.DescribeFileResponse, _err error) {
	headers := make(map[string]*string)
	runtime := &util.RuntimeOptions{}
	return client.DescribeFileWithOptions(tea.String(workspaceId), tea.String(fileId), headers, runtime)
}

// SubmitIndexAddDocumentsJob は、解析済みのファイルをナレッジベースに追加します。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): ナレッジベース ID。
//   - fileId (string): ファイル ID。
//   - sourceType (string): データの型。
//
// 戻り値:
//   - *bailian20231229.SubmitIndexAddDocumentsJobResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func SubmitIndexAddDocumentsJob(client *bailian20231229.Client, workspaceId, indexId, fileId, sourceType string) (_result *bailian20231229.SubmitIndexAddDocumentsJobResponse, _err error) {
	headers := make(map[string]*string)
	submitIndexAddDocumentsJobRequest := &bailian20231229.SubmitIndexAddDocumentsJobRequest{
		IndexId:     tea.String(indexId),
		SourceType:  tea.String(sourceType),
		DocumentIds: []*string{tea.String(fileId)},
	}
	runtime := &util.RuntimeOptions{}
	return client.SubmitIndexAddDocumentsJobWithOptions(tea.String(workspaceId), submitIndexAddDocumentsJobRequest, headers, runtime)
}

// GetIndexJobStatus は、インデックスジョブのステータスをクエリします。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - jobId (string): ジョブ ID。
//   - indexId (string): ナレッジベース ID。
//
// 戻り値:
//   - *bailian20231229.GetIndexJobStatusResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) {
	headers := make(map[string]*string)
	getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{
		JobId:   tea.String(jobId),
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime)
}

// DeleteIndexDocument は、指定されたナレッジベースから 1 つ以上のファイルを永久に削除します。
//
// パラメータ:
//   - client (*bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): ナレッジベース ID。
//   - fileId (string): ファイル ID。
//
// 戻り値:
//   - *bailian20231229.DeleteIndexDocumentResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func DeleteIndexDocument(client *bailian20231229.Client, workspaceId, indexId, fileId string) (*bailian20231229.DeleteIndexDocumentResponse, error) {
	headers := make(map[string]*string)
	deleteIndexDocumentRequest := &bailian20231229.DeleteIndexDocumentRequest{
		IndexId:     tea.String(indexId),
		DocumentIds: []*string{tea.String(fileId)},
	}
	runtime := &util.RuntimeOptions{}
	return client.DeleteIndexDocumentWithOptions(tea.String(workspaceId), deleteIndexDocumentRequest, headers, runtime)
}

// UpdateKnowledgeBase は、ナレッジベースを更新します。
//
// パラメータ:
//   - filePath (string): 更新されたファイルのローカルパス。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): 更新するナレッジベースの ID。
//   - oldFileId (string): 更新するファイルのファイル ID。
//
// 戻り値:
//   - string: 更新が成功した場合はナレッジベースの ID、それ以外の場合は空の文字列。
//   - error: エラーメッセージ。
func UpdateKnowledgeBase(filePath, workspaceId, indexId, oldFileId string) (_result string, _err error) {
	// デフォルト値を設定します。
	categoryId := "default"
	parser := "DASHSCOPE_DOCMIND"
	sourceType := "DATA_CENTER_FILE"

	fmt.Println("ステップ 1: クライアントを作成します。")
	client, err := CreateClient()
	if err != nil {
		return "", err
	}

	fmt.Println("ステップ 2: ファイル情報を準備します。")
	fileName := filepath.Base(filePath)
	fileMD5, err := CalculateMD5(filePath)
	if err != nil {
		return "", err
	}
	fileSizeStr, err := GetFileSize(filePath)
	if err != nil {
		return "", err
	}

	fmt.Println("ステップ 3: Alibaba Cloud Model Studio からアップロードリースをリクエストします。")
	leaseResponse, err := ApplyLease(client, categoryId, fileName, fileMD5, fileSizeStr, workspaceId)
	if err != nil {
		return "", err
	}

	leaseId := tea.StringValue(leaseResponse.Body.Data.FileUploadLeaseId)
	uploadURL := tea.StringValue(leaseResponse.Body.Data.Param.Url)
	uploadHeaders := leaseResponse.Body.Data.Param.Headers

	jsonData, err := json.Marshal(uploadHeaders)
	if err != nil {
		return "", err
	}

	var uploadHeadersMap map[string]string
	err = json.Unmarshal(jsonData, &uploadHeadersMap)
	if err != nil {
		return "", err
	}

	fmt.Println("ステップ 4: ファイルを一時ストレージにアップロードします。")
	err = UploadFile(uploadURL, uploadHeadersMap, filePath)
	if err != nil {
		return "", err
	}

	fmt.Println("ステップ 5: ファイルをカテゴリに追加します。")
	addResponse, err := AddFile(client, leaseId, parser, categoryId, workspaceId)
	if err != nil {
		return "", err
	}
	fileId := tea.StringValue(addResponse.Body.Data.FileId)

	fmt.Println("ステップ 6: Alibaba Cloud Model Studio でファイルステータスを確認します。")
	for {
		describeResponse, err := DescribeFile(client, workspaceId, fileId)
		if err != nil {
			return "", err
		}

		status := tea.StringValue(describeResponse.Body.Data.Status)
		fmt.Printf("現在のファイルステータス: %s\n", status)

		if status == "INIT" {
			fmt.Println("ファイルは解析待ちです。お待ちください...")
		} else if status == "PARSING" {
			fmt.Println("ファイルは解析中です。お待ちください...")
		} else if status == "PARSE_SUCCESS" {
			fmt.Println("ファイルは正常に解析されました。")
			break
		} else {
			fmt.Printf("不明なファイルステータス: %s。テクニカルサポートにお問い合わせください。\n", status)
			return "", fmt.Errorf("不明なファイルステータス: %s", status)
		}
		time.Sleep(5 * time.Second)
	}

	// ファイルを追加するタスクを送信します。
	fmt.Println("ステップ 7: ファイルを追加するタスクを送信します。")
	indexAddResponse, err := SubmitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType)
	if err != nil {
		return "", err
	}
	jobId := tea.StringValue(indexAddResponse.Body.Data.Id)

	// タスクが完了するのを待ちます。
	fmt.Println("ステップ 8: 追加タスクが完了するのを待ちます。")
	for {
		getIndexJobStatusResponse, err := GetIndexJobStatus(client, workspaceId, jobId, indexId)
		if err != nil {
			return "", err
		}

		status := tea.StringValue(getIndexJobStatusResponse.Body.Data.Status)
		fmt.Printf("現在のインデックスジョブのステータス: %s\n", status)

		if status == "COMPLETED" {
			break
		}
		time.Sleep(5 * time.Second)
	}

	// 古いファイルを削除します。
	fmt.Println("ステップ 9: 古いファイルを削除します。")
	_, err = DeleteIndexDocument(client, workspaceId, indexId, oldFileId)
	if err != nil {
		return "", err
	}

	fmt.Println("Alibaba Cloud Model Studio ナレッジベースは正常に更新されました。")
	return indexId, nil
}

func main() {
	if !CheckEnvironmentVariables() {
		fmt.Println("環境変数チェックに失敗しました。")
		return
	}
	// 入力を読み取るためのスキャナーを作成します。
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("アップロードする更新済みファイルのローカルパスを入力してください (例: Linux システムの場合 /path/to/product_introduction.docx):")
	filePath, _ := reader.ReadString('\n')
	filePath = strings.TrimSpace(filePath)

	fmt.Print("更新するナレッジベースの ID を入力してください:") // これは CreateIndex 操作によって返される Data.Id です。Model Studio コンソールのナレッジベースページでも ID を取得できます。
	indexId, _ := reader.ReadString('\n')
	indexId = strings.TrimSpace(indexId)

	fmt.Print("更新するファイルのファイル ID を入力してください:") // これは AddFile 操作によって返される FileId です。Model Studio コンソールのアプリケーションデータページでファイル名の横にある ID アイコンをクリックしてファイル ID を取得することもできます。
	oldFileId, _ := reader.ReadString('\n')
	oldFileId = strings.TrimSpace(oldFileId)

	workspaceId := os.Getenv("WORKSPACE_ID")
	result, err := UpdateKnowledgeBase(filePath, workspaceId, indexId, oldFileId)
	if err != nil {
		fmt.Printf("エラーが発生しました: %v\n", err)
		return
	}

	if result != "" {
		fmt.Printf("ナレッジベースは正常に更新されました。ナレッジベース ID は: %s\n", result)
	} else {
		fmt.Println("ナレッジベースの更新に失敗しました。")
	}
}

ナレッジベースの管理

重要
  • この例を実行する前に、前提条件を完了してください。RAM ユーザーには、AliyunBailianDataFullAccess ポリシーが付与されている必要もあります。

  • IDE やその他の開発プラグインを使用する場合、開発環境で ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET、および WORKSPACE_ID 環境変数を設定してください。

Python

# このサンプルコードは参照用です。本番環境では使用しないでください。
import os

from alibabacloud_bailian20231229 import models as bailian_20231229_models
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


def check_environment_variables():
    """必要な環境変数が設定されていることを確認します。"""
    required_vars = {
        'ALIBABA_CLOUD_ACCESS_KEY_ID': 'Alibaba Cloud AccessKey ID',
        'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'Alibaba Cloud AccessKey secret',
        'WORKSPACE_ID': 'Alibaba Cloud Model Studio workspace ID'
    }
    missing_vars = []
    for var, description in required_vars.items():
        if not os.environ.get(var):
            missing_vars.append(var)
            print(f"エラー: {var} 環境変数を設定してください ({description})")

    return len(missing_vars) == 0


# クライアントを作成します。
def create_client() -> bailian20231229Client:
    """
    クライアントを作成して設定します。

    Returns:
        bailian20231229Client: 設定済みのクライアント。
    """
    config = open_api_models.Config(
        access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
    # 以下のエンドポイントはシンガポールリージョンのパブリッククラウド用です。必要に応じて変更してください。
    config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
    return bailian20231229Client(config)


# ナレッジベースを一覧表示します。
def list_indices(client, workspace_id):
    """
    指定されたワークスペース内のナレッジベースを一覧表示します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。

    Returns:
        Alibaba Cloud Model Studio サービスからのレスポンス。
    """
    headers = {}
    list_indices_request = bailian_20231229_models.ListIndicesRequest()
    runtime = util_models.RuntimeOptions()
    return client.list_indices_with_options(workspace_id, list_indices_request, headers, runtime)


# ナレッジベースを削除します。
def delete_index(client, workspace_id, index_id):
    """
    指定されたナレッジベースを永久に削除します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。

    Returns:
        Alibaba Cloud Model Studio サービスからのレスポンス。
    """
    headers = {}
    delete_index_request = bailian_20231229_models.DeleteIndexRequest(
        index_id=index_id
    )
    runtime = util_models.RuntimeOptions()
    return client.delete_index_with_options(workspace_id, delete_index_request, headers, runtime)


def main():
    if not check_environment_variables():
        print("環境変数チェックに失敗しました。")
        return
    try:
        start_option = input(
            "実行する操作を選択してください:\n1. ナレッジベースを一覧表示\n2. ナレッジベースを削除\nオプションを入力 (1 または 2):")
        if start_option == '1':
            # ナレッジベースを一覧表示します。
            print("\nナレッジベースを一覧表示しています...")
            workspace_id = os.environ.get('WORKSPACE_ID')
            client = create_client()
            list_indices_response = list_indices(client, workspace_id)
            print(UtilClient.to_jsonstring(list_indices_response.body.data))
        elif start_option == '2':
            print("\nナレッジベースを削除しています...")
            workspace_id = os.environ.get('WORKSPACE_ID')
            index_id = input("ナレッジベース ID を入力してください: ")  # これは `CreateIndex` レスポンスの `Data.Id` 値です。Model Studio コンソールのナレッジベースページでも確認できます。
            # 削除前に確認します。
            while True:
                confirm = input(f"ナレッジベース {index_id} を永久に削除してもよろしいですか? (y/n): ").strip().lower()
                if confirm == 'y':
                    break
                elif confirm == 'n':
                    print("削除はキャンセルされました。")
                    return
                else:
                    print("無効な入力です。y または n を入力してください。")
            client = create_client()
            resp = delete_index(client, workspace_id, index_id)
            if resp.body.status == 200:
                print(f"ナレッジベース {index_id} は正常に削除されました。")
            else:
                err_info = UtilClient.to_jsonstring(resp.body)
                print(f"エラーが発生しました: {err_info}")
        else:
            print("無効なオプションです。プログラムを終了します。")
            return
    except Exception as e:
        print(f"エラーが発生しました: {e}")
        return


if __name__ == '__main__':
    main()

Java

// このサンプルコードは参照用です。本番環境では使用しないでください。
import com.aliyun.bailian20231229.models.DeleteIndexResponse;
import com.aliyun.bailian20231229.models.ListIndicesResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

public class KnowledgeBaseManage {

    /**
     * 必要な環境変数が設定されていることを確認します。
     *
     * @return 必要な環境変数がすべて設定されていれば true、そうでなければ false。
     */
    public static boolean checkEnvironmentVariables() {
        Map<String, String> requiredVars = new HashMap<>();
        requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_ID", "Alibaba Cloud AccessKey ID");
        requiredVars.put("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "Alibaba Cloud AccessKey secret");
        requiredVars.put("WORKSPACE_ID", "Alibaba Cloud Model Studio workspace ID");

        List<String> missingVars = new ArrayList<>();
        for (Map.Entry<String, String> entry : requiredVars.entrySet()) {
            String value = System.getenv(entry.getKey());
            if (value == null || value.isEmpty()) {
                missingVars.add(entry.getKey());
                System.out.println("エラー: " + entry.getKey() + " 環境変数を設定してください (" + entry.getValue() + ")");
            }
        }

        return missingVars.isEmpty();
    }

    /**
     * クライアントを作成して設定します。
     *
     * @return 設定済みのクライアント。
     */
    public static com.aliyun.bailian20231229.Client createClient() throws Exception {
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential);
        // これはパブリッククラウドのエンドポイントです。リージョンに合わせて変更してください。
        config.endpoint = "bailian.ap-southeast-1.aliyuncs.com";
        return new com.aliyun.bailian20231229.Client(config);
    }

    /**
     * 指定されたワークスペース内のナレッジベースを一覧表示します。
     *
     * @param client      クライアント。
     * @param workspaceId ワークスペース ID。
     * @return Model Studio サービスからのレスポンス。
     */
    public static ListIndicesResponse listIndices(com.aliyun.bailian20231229.Client client, String workspaceId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.ListIndicesRequest listIndicesRequest = new com.aliyun.bailian20231229.models.ListIndicesRequest();
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.listIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
    }

    /**
     * 指定されたナレッジベースを永久に削除します。
     *
     * @param client      クライアント。
     * @param workspaceId ワークスペース ID。
     * @param indexId     ナレッジベース ID。
     * @return Model Studio サービスからのレスポンス。
     */
    public static DeleteIndexResponse deleteIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception {
        Map<String, String> headers = new HashMap<>();
        com.aliyun.bailian20231229.models.DeleteIndexRequest deleteIndexRequest = new com.aliyun.bailian20231229.models.DeleteIndexRequest();
        deleteIndexRequest.setIndexId(indexId);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        return client.deleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
    }

    /**
     * メイン関数。
     */
    public static void main(String[] args) {
        if (!checkEnvironmentVariables()) {
            System.out.println("環境変数チェックに失敗しました。");
            return;
        }

        try {
            Scanner scanner = new Scanner(System.in);
            System.out.print("実行する操作を選択してください:\n1. ナレッジベースを一覧表示\n2. ナレッジベースを削除\nオプションを入力 (1 または 2): ");
            String startOption = scanner.nextLine();
            com.aliyun.bailian20231229.Client client = createClient();
            if (startOption.equals("1")) {
                // ナレッジベースを一覧表示
                System.out.println("\nナレッジベースを一覧表示しています...");
                String workspaceId = System.getenv("WORKSPACE_ID");
                ListIndicesResponse response = listIndices(client, workspaceId);
                // レスポンスを JSON 文字列に変換するには、jackson-databind ライブラリが必要です。
                ObjectMapper mapper = new ObjectMapper();
                String result = mapper.writeValueAsString(response.getBody().getData());
                System.out.println(result);
            } else if (startOption.equals("2")) {
                System.out.println("\nナレッジベースを削除しています...");
                String workspaceId = System.getenv("WORKSPACE_ID");
                System.out.print("ナレッジベース ID を入力してください: "); // この ID は CreateIndex 操作によって返される Data.Id 値です。Model Studio コンソールのナレッジベースページでも確認できます。
                String indexId = scanner.nextLine();
                // 削除前に確認を求めます。
                boolean confirm = false;
                while (!confirm) {
                    System.out.print("ナレッジベース " + indexId + " を永久に削除してもよろしいですか? (y/n): ");
                    String input = scanner.nextLine().trim().toLowerCase();
                    if (input.equals("y")) {
                        confirm = true;
                    } else if (input.equals("n")) {
                        System.out.println("削除はキャンセルされました。");
                        return;
                    } else {
                        System.out.println("無効な入力です。y または n を入力してください。");
                    }
                }
                DeleteIndexResponse resp = deleteIndex(client, workspaceId, indexId);
                if (resp.getBody().getStatus().equals("200")) {
                    System.out.println("ナレッジベース " + indexId + " は正常に削除されました。");
                } else {
                    ObjectMapper mapper = new ObjectMapper();
                    System.out.println("エラーが発生しました: " + mapper.writeValueAsString(resp.getBody()));
                }
            } else {
                System.out.println("無効なオプションです。プログラムを終了します。");
            }
        } catch (Exception e) {
            System.out.println("エラーが発生しました: " + e.getMessage());
        }
    }
}

PHP

<?php
// このサンプルコードは参照用です。本番環境では使用しないでください。
namespace AlibabaCloud\SDK\KnowledgeBase;

use AlibabaCloud\Dara\Models\RuntimeOptions;
use AlibabaCloud\SDK\Bailian\V20231229\Bailian;
use AlibabaCloud\SDK\Bailian\V20231229\Models\DeleteIndexRequest;
use AlibabaCloud\SDK\Bailian\V20231229\Models\ListIndexDocumentsRequest;
use \Exception;

use Darabonba\OpenApi\Models\Config;

class KnowledgeBaseManage {

    /**
    * 必要な環境変数が設定されていることを確認します。
    *
    * @return bool 必要な環境変数がすべて設定されていれば true、そうでなければ false を返します。
    */
    public static function checkEnvironmentVariables() {
        $requiredVars = [
            'ALIBABA_CLOUD_ACCESS_KEY_ID' => 'Alibaba Cloud AccessKey ID',
            'ALIBABA_CLOUD_ACCESS_KEY_SECRET' => 'Alibaba Cloud AccessKey secret',
            'WORKSPACE_ID' => 'Alibaba Cloud Model Studio workspace ID'
        ];
        $missingVars = [];
        foreach ($requiredVars as $var => $description) {
            if (!getenv($var)) {
                $missingVars[] = $var;
                echo "エラー: $var 環境変数を設定してください ($description)\n";
            }
        }
        return count($missingVars) === 0;
    }

    /**
     * クライアントを初期化します。
     *
     * @return Bailian 設定済みのクライアントオブジェクト。
     */
    public static function createClient(){
        $config = new Config([
            "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
            "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        ]);
        // これはパブリッククラウドのエンドポイントです。必要に応じて変更できます。
        $config->endpoint = 'bailian.ap-southeast-1.aliyuncs.com';
        return new Bailian($config);
    }

     /**
     * 指定されたワークスペース内のナレッジベースを一覧表示します。
     *
     * @param Bailian $client クライアントオブジェクト。
     * @param string $workspaceId ワークスペース ID。
     * @return ListIndicesResponse Model Studio サービスからのレスポンス。
     * @throws Exception
     */
    public static function listIndices($client, $workspaceId) {
        $headers = [];
        $listIndexDocumentsRequest = new ListIndexDocumentsRequest([]);
        $runtime = new RuntimeOptions([]);
        return $client->listIndicesWithOptions($workspaceId, $listIndexDocumentsRequest, $headers, $runtime);
    }

    /**
     * 指定されたナレッジベースを永久に削除します。
     *
     * @param Bailian $client クライアントオブジェクト。
     * @param string $workspaceId ワークスペース ID。
     * @param string $indexId ナレッジベース ID。
     * @return mixed Model Studio サービスからのレスポンス。
     * @throws Exception
     */
    public static function deleteIndex($client, $workspaceId, $indexId) {
        $headers = [];
        $deleteIndexRequest = new DeleteIndexRequest([
            "indexId" => $indexId
        ]);
        $runtime = new RuntimeOptions([]);
        return $client->deleteIndexWithOptions($workspaceId, $deleteIndexRequest, $headers, $runtime);
    }

    /**
     * メイン関数。
     */
    public static function main($args) {
        if (!self::checkEnvironmentVariables()) {
            echo "環境変数チェックに失敗しました。\n";
            return;
        }

        try {
            echo "実行する操作を選択してください:\n1. ナレッジベースを一覧表示\n2. ナレッジベースを削除\nオプションを入力 (1 または 2):";
            $startOption = trim(fgets(STDIN));
            $client = self::createClient();
            if ($startOption === "1") {
                // ナレッジベースを一覧表示します。
                echo "\nナレッジベースを一覧表示\n";
                $workspaceId = getenv("WORKSPACE_ID");
                $response = self::listIndices($client, $workspaceId);
                // レスポンスを JSON 文字列に変換します。
                $result = json_encode($response->body->data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                echo $result . "\n";
            } elseif ($startOption === "2") {
                echo "\nナレッジベースを削除\n";
                $workspaceId = getenv("WORKSPACE_ID");
                $indexId = readline("ナレッジベース ID を入力してください:"); // ID は CreateIndex 操作によって `Data.Id` として返されます。Model Studio コンソールのナレッジベースページでも確認できます。
                // 削除前に確認します。
                while (true) {
                    $confirm = strtolower(trim(readline("ナレッジベース $indexId を永久に削除してもよろしいですか? (y/n): ")));
                    if ($confirm === 'y') {
                        break;
                    } elseif ($confirm === 'n') {
                        echo "削除はキャンセルされました。\n";
                        return;
                    } else {
                        echo "無効な入力です。y または n を入力してください。\n";
                    }
                }
                $response = self::deleteIndex($client, $workspaceId, $indexId);
                if ($response->body->status == "200")
                    echo "ナレッジベース " . $indexId . " は削除されました。\n";
                else 
                    echo "エラーが発生しました: " . json_encode($response->body) . "\n";
            } else {
                echo "無効なオプションです。終了します。\n";
            }
        } catch (Exception $e) {
            echo "エラーが発生しました: " . $e->getMessage() . "\n";
        }
    }
}
// autoload.php がこのファイルの親ディレクトリにあると仮定します。プロジェクトの構造に応じてパスを調整してください。
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
KnowledgeBaseManage::main(array_slice($argv, 1));

Node.js

// このサンプルコードは参照用です。本番環境では使用しないでください。
'use strict';

const bailian20231229 = require('@alicloud/bailian20231229');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Tea = require('@alicloud/tea-typescript');

class KbManage {

    /**
     * 必要な環境変数が設定されていることを確認します。
     * @returns {boolean} 必要な環境変数がすべて設定されていれば true、そうでなければ false。
     */
    static checkEnvironmentVariables() {
        const requiredVars = {
            'ALIBABA_CLOUD_ACCESS_KEY_ID': 'Alibaba Cloud access key ID',
            'ALIBABA_CLOUD_ACCESS_KEY_SECRET': 'Alibaba Cloud access key secret',
            'WORKSPACE_ID': 'Alibaba Cloud Model Studio workspace ID'
        };

        const missing = [];
        for (const [varName, desc] of Object.entries(requiredVars)) {
            if (!process.env[varName]) {
                console.error(`エラー: ${varName} 環境変数を設定してください (${desc})`);
                missing.push(varName);
            }
        }

        return missing.length === 0;
    }

    /**
     * クライアントを作成して設定します。
     * @returns {bailian20231229.default} 設定済みのクライアント。
     * @throws {Error} 認証情報が設定されていない場合にエラーをスローします。
     */
    static createClient() {
        const config = new OpenApi.Config({
            accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
            accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
        });
        // 以下のエンドポイントはパブリッククラウド用です。必要に応じて変更できます。
        config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com';
        return new bailian20231229.default(config);
    }

    /**
     * 指定されたワークスペース内のナレッジベースを一覧表示します。
     * @param {bailian20231229.Client} client リクエストに使用するクライアントインスタンス。
     * @param {string} workspaceId クエリするワークスペースの ID。
     * @returns {Promise<bailian20231229.ListIndicesResponse>} サービスレスポンスで解決される Promise。
     */
    static async listIndices(client, workspaceId) {
        const headers = {};
        const listIndicesRequest = new bailian20231229.ListIndicesRequest();
        const runtime = new Util.RuntimeOptions({});
        return await client.listIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
    }

    /**
     * 指定されたナレッジベースを永久に削除します。
     * @param {bailian20231229.Client} client リクエストに使用するクライアントインスタンス。
     * @param {string} workspaceId ナレッジベースを含むワークスペースの ID。
     * @param {string} indexId 削除するナレッジベースの ID。
     * @returns {Promise<bailian20231229.DeleteIndexResponse>} サービスレスポンスで解決される Promise。
     */
    static async deleteIndex(client, workspaceId, indexId) {
        const headers = {};
        const deleteIndexRequest = new bailian20231229.DeleteIndexRequest({
            indexId
        });
        const runtime = new Util.RuntimeOptions({});
        return await client.deleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
    }

    /**
     * ナレッジベースを一覧表示または削除するためのコマンドラインインターフェイスを提供します。
     */
    static async main(args) {
        if (!this.checkEnvironmentVariables()) {
            console.log("環境変数チェックに失敗しました。");
            return;
        }

        const readline = require('readline').createInterface({
            input: process.stdin,
            output: process.stdout
        });

        try {
            const startOption = await new Promise((resolve) => {
                readline.question("実行する操作を選択してください:\n1. ナレッジベースを一覧表示\n2. ナレッジベースを削除\nオプションを入力 (1 または 2):", (ans) => {
                    resolve(ans.trim());
                });
            });

            if (startOption === '1') {
                console.log("\nナレッジベースを一覧表示しています...");
                const workspaceId = process.env.WORKSPACE_ID;
                const client = this.createClient();
                const response = await this.listIndices(client, workspaceId);
                console.log(JSON.stringify(response.body.data));
            } else if (startOption === '2') {
                console.log("\nナレッジベースを削除しています...");
                const workspaceId = process.env.WORKSPACE_ID;
                const indexId = await new Promise((resolve) => {
                    readline.question("ナレッジベース ID を入力してください: ", (ans) => { // この ID は `CreateIndex` API レスポンスの `Data.Id` 値に対応します。Model Studio コンソールのナレッジベースページでも確認できます。
                        resolve(ans.trim());
                    });
                });
                // 削除前に確認します。
                let confirm = '';
                while (confirm !== 'y' && confirm !== 'n') {
                    confirm = (await new Promise((resolve) => {
                        readline.question(`ナレッジベース ${indexId} を永久に削除してもよろしいですか? (y/n): `, (ans) => {
                            resolve(ans.trim().toLowerCase());
                        });
                    })).toLowerCase();
                    if (confirm === 'n') {
                        console.log("削除はキャンセルされました。");
                        return;
                    } else if (confirm !== 'y') {
                        console.log("無効な入力です。y または n を入力してください。");
                    }
                }
                const client = this.createClient();
                const resp = await this.deleteIndex(client, workspaceId, indexId);
                if (resp.body.status == '200')
                    console.log(`ナレッジベース ${indexId} は正常に削除されました。`);
                else {
                    const errInfo = JSON.stringify(resp.body);
                    console.error(`エラーが発生しました: ${errInfo}`)
                }
            } else {
                console.log("無効なオプションです。終了します。");
            }
        } catch (err) {
            console.error(`エラーが発生しました: ${err.message}`);
        } finally {
            readline.close();
        }
    }
}

exports.KbManage = KbManage;
KbManage.main(process.argv.slice(2));

C#

// このサンプルコードは参照用です。本番環境では使用しないでください。
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

using Newtonsoft.Json;
using Tea;
using Tea.Utils;


namespace AlibabaCloud.SDK.KnowledgeBase
{
    public class KnowledgeBaseManage
    {
        /// <summary>
        /// 必要な環境変数を確認し、不足している場合はプロンプトを表示します。
        /// </summary>
        /// <returns>必要な環境変数がすべて設定されていれば `true`、そうでなければ `false`。</returns>
        public static bool CheckEnvironmentVariables()
        {
            var requiredVars = new Dictionary<string, string>
            {
                { "ALIBABA_CLOUD_ACCESS_KEY_ID", "Alibaba Cloud AccessKey ID" },
                { "ALIBABA_CLOUD_ACCESS_KEY_SECRET", "Alibaba Cloud AccessKey secret" },
                { "WORKSPACE_ID", "Alibaba Cloud Model Studio workspace ID" }
            };

            var missingVars = new List<string>();
            foreach (var entry in requiredVars)
            {
                string value = Environment.GetEnvironmentVariable(entry.Key);
                if (string.IsNullOrEmpty(value))
                {
                    missingVars.Add(entry.Key);
                    Console.WriteLine($"エラー: {entry.Key} 環境変数を設定してください ({entry.Value})");
                }
            }

            return missingVars.Count == 0;
        }

        /// <summary>
        /// クライアントを初期化します。
        /// </summary>
        /// <returns>設定済みのクライアントオブジェクト。</returns>
        /// <exception cref="Exception">初期化中にエラーが発生した場合に例外がスローされます。</exception>
        public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
        {
            var config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            };
            // 以下はパブリックエンドポイントの例です。必要に応じて変更できます。
            config.Endpoint = "bailian.ap-southeast-1.aliyuncs.com";
            return new AlibabaCloud.SDK.Bailian20231229.Client(config);
        }

        /// <summary>
        /// 指定されたワークスペース内のナレッジベースの詳細を取得します。
        /// </summary>
        /// <param name="client">クライアント。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <returns>Model Studio サービスからのレスポンス。</returns>
        public static AlibabaCloud.SDK.Bailian20231229.Models.ListIndicesResponse ListIndices(AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId)
        {
            var headers = new Dictionary<string, string>() { };
            var listIndicesRequest = new Bailian20231229.Models.ListIndicesRequest();
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.ListIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
        }

        /// <summary>
        /// 指定されたナレッジベースを永久に削除します。
        /// </summary>
        /// <param name="client">クライアント。</param>
        /// <param name="workspaceId">ワークスペース ID。</param>
        /// <param name="indexId">ナレッジベース ID。</param>
        /// <returns>Model Studio サービスからのレスポンス。</returns>
        public static AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexResponse DeleteIndex(AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId, string indexId)
        {
            var headers = new Dictionary<string, string>() { };
            var deleteIndexRequest = new Bailian20231229.Models.DeleteIndexRequest
            {
                IndexId = indexId
            };
            var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            return client.DeleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
        }

        /// <summary>
        /// メイン関数。
        /// </summary>
        public static void Main(string[] args)
        {
            if (!CheckEnvironmentVariables())
            {
                Console.WriteLine("環境変数チェックに失敗しました。");
                return;
            }
            try
            {
                Console.Write("実行する操作を選択してください:\n1. ナレッジベースを一覧表示\n2. ナレッジベースを削除\nオプションを入力してください (1 または 2):");
                string startOption = Console.ReadLine();
                if (startOption == "1")
                {
                    Console.WriteLine("\nナレッジベースを一覧表示しています...");
                    string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
                    Bailian20231229.Client client = CreateClient();
                    Bailian20231229.Models.ListIndicesResponse listIndicesResponse = ListIndices(client, workspaceId);
                    // Newtonsoft.Json をインストールして、レスポンスオブジェクトを JSON 文字列にシリアル化します。
                    var json = JsonConvert.SerializeObject(listIndicesResponse.Body.Data, Formatting.Indented);
                    Console.WriteLine(json);
                }
                else if (startOption == "2")
                {
                    Console.WriteLine("\nナレッジベースを削除しています...");
                    string workspaceId = Environment.GetEnvironmentVariable("WORKSPACE_ID");
                    Console.Write("ナレッジベース ID を入力してください: "); // ナレッジベース ID (Data.Id) は、CreateIndex 操作によって返されるか、Model Studio コンソールのナレッジベースページで確認できます。
                    string indexId = Console.ReadLine();
                    // 削除前に確認します。
                    while (true)
                    {
                        Console.Write($"ナレッジベース {indexId} を永久に削除してもよろしいですか? (y/n): ");
                        string confirm = Console.ReadLine()?.ToLower();
                        if (confirm == "y")
                        {
                            break;
                        }
                        else if (confirm == "n")
                        {
                            Console.WriteLine("削除はキャンセルされました。");
                            return;
                        }
                        else
                        {
                            Console.WriteLine("無効な入力です。y または n を入力してください。");
                        }
                    }
                    Bailian20231229.Client client = CreateClient();
                    Bailian20231229.Models.DeleteIndexResponse resp = DeleteIndex(client, workspaceId, indexId);
                    if (resp.Body.Status == "200")
                    {
                        Console.WriteLine($"ナレッジベース {indexId} は正常に削除されました。");
                    }
                    else
                    {
                        var mapper = new JsonSerializerSettings { Formatting = Formatting.Indented };
                        string errInfo = JsonConvert.SerializeObject(resp.Body, mapper);
                        Console.WriteLine($"エラーが発生しました: {errInfo}");
                    }
                }
                else
                {
                    Console.WriteLine("無効なオプションです。終了します。");
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("エラーが発生しました: " + e.Message);
            }
        }
    }
}

Go

// このサンプルコードは参照用です。本番環境では使用しないでください。
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	bailian20231229 "github.com/alibabacloud-go/bailian-20231229/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

// checkEnvironmentVariables は、必要な環境変数が設定されていることを確認し、不足しているものを報告します。
func checkEnvironmentVariables() bool {
	// 必要な環境変数とその説明。
	requiredVars := map[string]string{
		"ALIBABA_CLOUD_ACCESS_KEY_ID":     "Alibaba Cloud AccessKey ID",
		"ALIBABA_CLOUD_ACCESS_KEY_SECRET": "Alibaba Cloud AccessKey secret",
		"WORKSPACE_ID":                    "Alibaba Cloud Model Studio workspace ID",
	}

	var missingVars []string
	for varName, desc := range requiredVars {
		if os.Getenv(varName) == "" {
			fmt.Printf("エラー: %s 環境変数を設定してください (%s)\n", varName, desc)
			missingVars = append(missingVars, varName)
		}
	}

	return len(missingVars) == 0
}

// createClient は、クライアントを作成して設定します。
//
// 戻り値:
//   - *bailian20231229.Client: 設定済みのクライアント。
func createClient() (_result *bailian20231229.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// これはパブリッククラウドのエンドポイントです。リージョンに合わせてこの値を変更してください。
	config.Endpoint = tea.String("bailian.ap-southeast-1.aliyuncs.com")
	_result = &bailian20231229.Client{}
	_result, _err = bailian20231229.NewClient(config)
	return _result, _err
}

// listIndices は、指定されたワークスペース内のナレッジベースを一覧表示します。
//
// パラメータ:
//   - client      *bailian20231229.Client: クライアント。
//   - workspaceId string: ワークスペース ID。
//
// 戻り値:
//   - *bailian20231229.ListIndicesResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラー (発生した場合)。
func listIndices(client *bailian20231229.Client, workspaceId string) (_result *bailian20231229.ListIndicesResponse, _err error) {
	headers := make(map[string]*string)
	listIndicesRequest := &bailian20231229.ListIndicesRequest{}
	runtime := &util.RuntimeOptions{}
	return client.ListIndicesWithOptions(tea.String(workspaceId), listIndicesRequest, headers, runtime)
}

// deleteIndex は、指定されたナレッジベースを永久に削除します。
//
// パラメータ:
//   - client      *bailian20231229.Client: クライアント。
//   - workspaceId string: ワークスペース ID。
//   - indexId     string: ナレッジベース ID。
//
// 戻り値:
//   - *bailian20231229.DeleteIndexResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラー (発生した場合)。
func deleteIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.DeleteIndexResponse, _err error) {
	headers := make(map[string]*string)
	deleteIndexRequest := &bailian20231229.DeleteIndexRequest{
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.DeleteIndexWithOptions(tea.String(workspaceId), deleteIndexRequest, headers, runtime)

}

func main() {
	if !checkEnvironmentVariables() {
		fmt.Println("環境変数チェックに失敗しました。")
		return
	}

	scanner := bufio.NewScanner(os.Stdin)
	fmt.Print("操作を選択してください:\n1. ナレッジベースを一覧表示\n2. ナレッジベースを削除\nオプションを入力 (1 または 2): ")

	if !scanner.Scan() {
		fmt.Println("入力の読み取りに失敗しました。")
		return
	}
	startOption := scanner.Text()

	client, err := createClient()
	if err != nil {
		fmt.Println("クライアントの作成に失敗しました:", err)
		return
	}

	if strings.TrimSpace(startOption) == "1" {
		fmt.Println("\nナレッジベースを一覧表示しています...")
		workspaceId := os.Getenv("WORKSPACE_ID")
		resp, err := listIndices(client, workspaceId)
		if err != nil {
			fmt.Println("ナレッジベースのリストの取得に失敗しました:", err)
			return
		}
		fmt.Printf("ナレッジベース:\n%+v\n", resp.Body.Data)
	} else if strings.TrimSpace(startOption) == "2" {
		fmt.Println("\nナレッジベースを削除しています...")
		workspaceId := os.Getenv("WORKSPACE_ID")
		fmt.Print("ナレッジベース ID を入力してください: ")
		if !scanner.Scan() {
			fmt.Println("ナレッジベース ID の読み取りに失敗しました。")
			return
		}
		indexId := scanner.Text()
		for {
			fmt.Printf("ナレッジベース %s を永久に削除してもよろしいですか? (y/n): ", indexId)
			if !scanner.Scan() {
				fmt.Println("確認の読み取りに失敗しました。")
				return
			}
			confirm := strings.ToLower(strings.TrimSpace(scanner.Text()))

			if confirm == "y" {
				break
			} else if confirm == "n" {
				fmt.Println("削除はキャンセルされました。")
				return
			} else {
				fmt.Println("無効な入力です。y または n を入力してください。")
			}
		}
		resp, err := deleteIndex(client, workspaceId, indexId)
		if err != nil {
			fmt.Println("ナレッジベースの削除に失敗しました:", err)
		} else {
			if tea.StringValue(resp.Body.Status) == "200" {
				fmt.Printf("ナレッジベース %s は正常に削除されました。\n", indexId)
			} else {
				fmt.Println(resp.Body)
			}
		}
	} else {
		fmt.Println("無効なオプションです。プログラムを終了します。")
	}
}

ナレッジベースの作成

指定されたワークスペースにドキュメント検索ナレッジベースを作成します。

1. クライアントの初期化

ファイルをアップロードしてナレッジベースを作成するには、まずクライアントを初期化します。AccessKey と AccessKey Secret を使用して ID を検証し、endpoint を設定します。

  • パブリックエンドポイント

    ご利用のクライアントはインターネットにアクセスできる必要があります。
    • パブリッククラウド: bailian.ap-southeast-1.aliyuncs.com

  • VPC エンドポイント

    ご利用のクライアントが Alibaba Cloud シンガポールリージョン (ap-southeast-1) のパブリッククラウドにデプロイされており、VPC 内にある場合は、以下の VPC エンドポイントを使用できます。リージョン間のアクセスはサポートされていません。
    • パブリッククラウド: bailian-vpc.ap-southeast-1.aliyuncs.com

クライアントを作成すると、後続の API 呼び出しに使用する Client オブジェクトが返されます。

Python

def create_client() -> bailian20231229Client:
    """
    クライアントを作成して設定します。

    Returns:
        bailian20231229Client: 設定済みのクライアント。
    """
    config = open_api_models.Config(
        access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
    # 以下のエンドポイントは、パブリッククラウドのパブリックエンドポイントの例です。必要に応じてエンドポイントを変更できます。
    config.endpoint = 'bailian.ap-southeast-1.aliyuncs.com'
    return bailian20231229Client(config)

Java

/**
* クライアントを初期化します。
*
* @return 設定済みのクライアントオブジェクト。
*/
public static com.aliyun.bailian20231229.Client createClient() throws Exception {
    com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
            .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
            .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
    // 以下のエンドポイントは、パブリッククラウドの VPC エンドポイントの例です。必要に応じてエンドポイントを変更できます。
    config.endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com";
    return new com.aliyun.bailian20231229.Client(config);
}

PHP

/**
 * クライアントを初期化します。
 *
 * @return Bailian 設定済みのクライアントオブジェクト。
 */
public static function createClient(){
    $config = new Config([
        "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
        "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    ]);
    // 以下のエンドポイントは、パブリッククラウドの VPC エンドポイントの例です。必要に応じてエンドポイントを変更できます。
    $config->endpoint = 'bailian-vpc.ap-southeast-1.aliyuncs.com';
    return new Bailian($config);
}

Node.js

/**
 * クライアントを作成して設定します。
 * @return Client
 * @throws Exception
 */
static createClient() {
  const config = new OpenApi.Config({
    accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
  });
  // 以下のエンドポイントは、パブリッククラウドの VPC エンドポイントの例です。必要に応じてエンドポイントを変更できます。
  config.endpoint = `bailian-vpc.ap-southeast-1.aliyuncs.com`;
  return new bailian20231229.default(config);
}

C#

/// <summary>
/// クライアントを初期化します。
/// </summary>
/// <returns>設定済みのクライアントオブジェクト。</returns>
/// <exception cref="Exception">初期化中にエラーが発生した場合にスローされます。</exception>
public static AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
{
    var config = new AlibabaCloud.OpenApiClient.Models.Config
    {
        AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
        AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
    };
    // 以下のエンドポイントは、パブリッククラウドの VPC エンドポイントの例です。必要に応じてエンドポイントを変更できます。
    config.Endpoint = "bailian-vpc.ap-southeast-1.aliyuncs.com";
    return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}

Go

// CreateClient は、クライアントを作成して設定します。
//
// 戻り値:
//   - *client.Bailian20231229Client: 設定済みのクライアント。
//   - error: エラーメッセージ。
func CreateClient() (_result *bailian20231229.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
	}
	// 以下のエンドポイントは、パブリッククラウドの VPC エンドポイントの例です。必要に応じてエンドポイントを変更できます。
	config.Endpoint = tea.String("bailian-vpc.ap-southeast-1.aliyuncs.com")
	_result = &bailian20231229.Client{}
	_result, _err = bailian20231229.NewClient(config)
	return _result, _err
}

2. ナレッジベースファイルのアップロード

2.1. ファイルアップロードリースのリクエスト

ナレッジベースを作成する前に、そのソースファイルを同じワークスペースにアップロードします。これを行うには、ApplyFileUploadLease 操作を呼び出してファイルアップロードリースをリクエストします。リースはファイルをアップロードするための一時的な権限付与であり、数分間有効です。

  • workspace_id:ワークスペース ID の取得方法」をご参照ください。

  • category_id: この例では、default を渡します。 Model Studio は、アップロードされたファイルを管理するためにカテゴリを使用します。 デフォルトのカテゴリは、システムによって自動的に作成されます。 また、AddCategory API を呼び出して新しいカテゴリを作成し、対応する category_id を取得することもできます。

  • file_name: 拡張子を含めて、アップロードするファイル名を渡します。値は実際のファイル名と一致する必要があります。たとえば、図に示されているファイルをアップロードする場合、 Alibaba_Cloud_Model_Studio_Mobile_Phone_Series_Introduction.docx を渡します。

    image

  • file_md5: アップロードするファイルの MD5 ハッシュを渡します。Alibaba Cloud は現在この値を検証しないため、URL からのファイルアップロードが容易になります。

    Python では、hashlib モジュールを使用して MD5 ハッシュを取得できます。他の言語については、完全なサンプルコードをご参照ください。

    コード例

    import hashlib
    
    
    def calculate_md5(file_path):
        """
        ファイルの MD5 ハッシュを計算します。
    
        Args:
            file_path (str): ファイルのローカルパス。
    
        Returns:
            str: ファイルの MD5 ハッシュ。
        """
        md5_hash = hashlib.md5()
    
        # ファイルをバイナリモードで読み込みます。
        with open(file_path, "rb") as f:
            # 大きなファイルの場合、メモリ使用量を抑えるためにチャンクで読み込みます。
            for chunk in iter(lambda: f.read(4096), b""):
                md5_hash.update(chunk)
    
        return md5_hash.hexdigest()
    
    
    # 使用例
    file_path = "これをアップロードするファイルの実際のローカルパスに置き換えてください。例: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
    md5_value = calculate_md5(file_path)
    print(f"ファイルの MD5 ハッシュは: {md5_value}")
    

    コード内の file_path 変数をファイルの実際のローカルパスに置き換え、コードを実行して対象のファイルの MD5 ハッシュを取得します。 以下に値の例を示します。

    ファイルの MD5 ハッシュは: 2ef7361ea907f3a1b91e3b9936f5643a
  • file_size: アップロードするファイルのサイズをバイト単位で渡します。

    Python では、os モジュールを使用してこの値を取得できます。他の言語については、完全なサンプルコードをご参照ください。

    コード例

    import os
    
    
    def get_file_size(file_path: str) -> int:
        """
        ファイルのサイズをバイト単位で取得します。
    
        Args:
            file_path (str): ファイルの実際のローカルパス。
    
        Returns:
            int: ファイルサイズ (バイト単位)。
        """
        return os.path.getsize(file_path)
    
    
    # 使用例
    file_path = "これをアップロードするファイルの実際のローカルパスに置き換えてください。例: /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
    file_size = get_file_size(file_path)
    print(f"ファイルのサイズ (バイト単位) は: {file_size}")
    

    file_path 変数をファイルの実際のローカルパスに置き換えてコードを実行し、対象のファイルのサイズをバイト単位で取得します。 以下に値の例を示します。

    ファイルのサイズ (バイト単位) は: 14015

一時的なアップロードリースのリクエストが成功すると、以下が返されます:

  • 一時的なアップロードパラメータのセット:

    • Data.FileUploadLeaseId

    • Data.Param.Method

    • Data.Param.HeadersX-bailian-extra

    • Data.Param.HeadersContent-Type

  • 一時アップロード URL:Data.Param.Url

重要

Python

def apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id):
    """
    Alibaba Cloud Model Studio からファイルアップロードリースをリクエストします。

    Args:
        client (bailian20231229Client): クライアント。
        category_id (str): カテゴリ ID。
        file_name (str): ファイル名。
        file_md5 (str): ファイルの MD5 ハッシュ。
        file_size (int): ファイルサイズ (バイト単位)。
        workspace_id (str): ワークスペース ID。

    Returns:
        Alibaba Cloud Model Studio からのレスポンス。
    """
    headers = {}
    request = bailian_20231229_models.ApplyFileUploadLeaseRequest(
        file_name=file_name,
        md_5=file_md5,
        size_in_bytes=file_size,
    )
    runtime = util_models.RuntimeOptions()
    return client.apply_file_upload_lease_with_options(category_id, workspace_id, request, headers, runtime)

Java

/**
 * ファイルアップロードリースをリクエストします。
 *
 * @param client      クライアントオブジェクト。
 * @param categoryId  カテゴリ ID。
 * @param fileName    ファイル名。
 * @param fileMd5     ファイルの MD5 ハッシュ。
 * @param fileSize    ファイルサイズ (バイト単位)。
 * @param workspaceId ワークスペース ID。
 * @return Alibaba Cloud Model Studio からのレスポンスオブジェクト。
 */
public ApplyFileUploadLeaseResponse applyLease(com.aliyun.bailian20231229.Client client, String categoryId, String fileName, String fileMd5, String fileSize, String workspaceId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = new com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest();
    applyFileUploadLeaseRequest.setFileName(fileName);
    applyFileUploadLeaseRequest.setMd5(fileMd5);
    applyFileUploadLeaseRequest.setSizeInBytes(fileSize);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    ApplyFileUploadLeaseResponse applyFileUploadLeaseResponse = null;
    applyFileUploadLeaseResponse = client.applyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
    return applyFileUploadLeaseResponse;
}

PHP

/**
 * ファイルアップロードリースをリクエストします。
 *
 * @param Bailian $client クライアント。
 * @param string $categoryId カテゴリ ID。
 * @param string $fileName ファイル名。
 * @param string $fileMd5 ファイルの MD5 ハッシュ。
 * @param int $fileSize ファイルサイズ (バイト単位)。
 * @param string $workspaceId ワークスペース ID。
 * @return ApplyFileUploadLeaseResponse Alibaba Cloud Model Studio からのレスポンス。
 */
public function applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId) {
    $headers = [];
    $applyFileUploadLeaseRequest = new ApplyFileUploadLeaseRequest([
        "fileName" => $fileName,
        "md5" => $fileMd5,
        "sizeInBytes" => $fileSize
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->applyFileUploadLeaseWithOptions($categoryId, $workspaceId, $applyFileUploadLeaseRequest, $headers, $runtime);
}

Node.js

/**
 * ファイルアップロードリースをリクエストします。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} categoryId - カテゴリ ID。
 * @param {string} fileName - ファイル名。
 * @param {string} fileMd5 - ファイルの MD5 ハッシュ。
 * @param {string} fileSize - ファイルサイズ (バイト単位)。
 * @param {string} workspaceId - ワークスペース ID。
 * @returns {Promise<bailian20231229.ApplyFileUploadLeaseResponse>} - Alibaba Cloud Model Studio からのレスポンス。
 */
async function applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId) {
  const headers = {};
  const req = new bailian20231229.ApplyFileUploadLeaseRequest({
    md5: fileMd5,
    fileName,
    sizeInBytes: fileSize
 });
 const runtime = new Util.RuntimeOptions({});
 return await client.applyFileUploadLeaseWithOptions(
    categoryId,
    workspaceId,
    req,
    headers,
    runtime
  );
}

C#

/// <summary>
/// ファイルアップロードリースをリクエストします。
/// </summary>
/// <param name="client">クライアントオブジェクト。</param>
/// <param name="categoryId">カテゴリ ID。</param>
/// <param name="fileName">ファイル名。</param>
/// <param name="fileMd5">ファイルの MD5 ハッシュ。</param>
/// <param name="fileSize">ファイルサイズ (バイト単位)。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <returns>Alibaba Cloud Model Studio からのレスポンスオブジェクト。</returns>
/// <exception cref="Exception">呼び出し中にエラーが発生した場合に例外がスローされます。</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseResponse ApplyLease(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string categoryId,
    string fileName,
    string fileMd5,
    string fileSize,
    string workspaceId)
{
    var headers = new Dictionary<string, string>() { };
    var applyFileUploadLeaseRequest = new AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseRequest
    {
        FileName = fileName,
        Md5 = fileMd5,
        SizeInBytes = fileSize
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.ApplyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
}

Go

// ApplyLease は Alibaba Cloud Model Studio からファイルアップロードリースをリクエストします。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - categoryId (string): カテゴリ ID。
//   - fileName (string): ファイル名。
//   - fileMD5 (string): ファイルの MD5 ハッシュ。
//   - fileSize (string): ファイルサイズ (バイト単位)。
//   - workspaceId (string): ワークスペース ID。
//
// 戻り値:
//   - *bailian20231229.ApplyFileUploadLeaseResponse: Alibaba Cloud Model Studio からのレスポンス。
//   - error: エラーメッセージ。
func ApplyLease(client *bailian20231229.Client, categoryId, fileName, fileMD5 string, fileSize string, workspaceId string) (_result *bailian20231229.ApplyFileUploadLeaseResponse, _err error) {
	headers := make(map[string]*string)
	applyFileUploadLeaseRequest := &bailian20231229.ApplyFileUploadLeaseRequest{
		FileName:    tea.String(fileName),
		Md5:         tea.String(fileMD5),
		SizeInBytes: tea.String(fileSize),
	}
	runtime := &util.RuntimeOptions{}
	return client.ApplyFileUploadLeaseWithOptions(tea.String(categoryId), tea.String(workspaceId), applyFileUploadLeaseRequest, headers, runtime)
}

リクエスト例

{
  "CategoryId": "default",
  "FileName": "Alibaba Cloud Model Studio Product Overview.docx",
  "Md5": "2ef7361ea907f3a1b91e3b9936f5643a",
  "SizeInBytes": "14015",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "RequestId": "778C0B3B-59C2-5FC1-A947-36EDD1XXXXXX",
  "Success": true,
  "Message": "",
  "Code": "success",
  "Status": "200",
  "Data": {
    "FileUploadLeaseId": "1e6a159107384782be5e45ac4759b247.1719325231035",
    "Type": "HTTP",
    "Param": {
      "Method": "PUT",
      "Url": "https://bailian-datahub-data-origin-prod.oss-cn-hangzhou.aliyuncs.com/1005426495169178/10024405/68abd1dea7b6404d8f7d7b9f7fbd332d.1716698936847.pdf?Expires=1716699536&OSSAccessKeyId=TestID&Signature=HfwPUZo4pR6DatSDym0zFKVh9Wg%3D",
      "Headers": "        \"X-bailian-extra\": \"MTAwNTQyNjQ5NTE2OTE3OA==\",\n        \"Content-Type\": \"application/pdf\""
    }
  }
}

2.2. ファイルを一時ストレージにアップロード

アップロードリースを使用して、ローカルストレージまたは一般公開されている URL から Model Studio サーバーにファイルをアップロードします。各ワークスペースは最大 10,000 ファイルをサポートします。サポートされている形式には、PDF、DOCX、DOC、TXT、Markdown、PPTX、PPT、XLSX、XLS、HTML、PNG、JPG、JPEG、BMP、GIF が含まれます。

  • pre_signed_url: ファイルアップロードリースをリクエストする API 応答の Data.Param.Url を指定します。

    これは署名付き URL であり、FormData アップロードをサポートしていません。ファイルをバイナリ形式でアップロードする必要があります。詳細については、サンプルコードをご参照ください。
重要

この例では、オンラインデバッグやサンプルコードの生成はサポートされていません。

ローカルアップロード

Python

import requests
from urllib.parse import urlparse

def upload_file(pre_signed_url, file_path):
    """
    ローカルファイルを一時ストレージにアップロードします。

    Args:
        pre_signed_url (str): アップロードリースからの URL。
        file_path (str): ファイルのローカルパス。
    
    Returns:
        Alibaba Cloud Model Studio からのレスポンス。
    """
    try:
        # リクエストヘッダーを設定します。
        headers = {
            "X-bailian-extra": "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。",
            "Content-Type": "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。"
        }

        # ファイルを読み込んでアップロードします。
        with open(file_path, 'rb') as file:
            # ファイルアップロードのリクエストメソッドは、前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Method フィールドの値と同じでなければなりません。
            response = requests.put(pre_signed_url, data=file, headers=headers)

        # レスポンスのステータスコードを確認します。
        if response.status_code == 200:
            print("ファイルは正常にアップロードされました。")
        else:
            print(f"ファイルのアップロードに失敗しました。ResponseCode: {response.status_code}")

    except Exception as e:
        print(f"エラーが発生しました: {str(e)}")

if __name__ == "__main__":

    pre_signed_url_or_http_url = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。"

    # ローカルファイルを一時ストレージにアップロードします。
    file_path = "アップロードするファイルの実際のローカルパスに置き換えてください。例: Linux の場合 /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"
    upload_file(pre_signed_url_or_http_url, file_path)

Java

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UploadFile {
    public static void uploadFile(String preSignedUrl, String filePath) {
        HttpURLConnection connection = null;
        try {
            // URL オブジェクトを作成します。
            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();
            // ファイルアップロードのリクエストメソッドは、前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Method フィールドの値と同じでなければなりません。
            connection.setRequestMethod("PUT");
            // この接続はファイルのアップロードに使用されるため、接続への出力を許可します。
            connection.setDoOutput(true);
            connection.setRequestProperty("X-bailian-extra", "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。");
            connection.setRequestProperty("Content-Type", "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。");
            // ファイルを読み込み、接続を介してアップロードします。
            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 FileInputStream fileInputStream = new FileInputStream(filePath)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.flush();
            }
            // レスポンスを確認します。
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // ファイルは正常にアップロードされました。
                System.out.println("ファイルは正常にアップロードされました。");
            } else {
                // ファイルのアップロードに失敗しました。
                System.out.println("ファイルのアップロードに失敗しました。ResponseCode: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        String preSignedUrlOrHttpUrl = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。";
        // ローカルファイルを一時ストレージにアップロードします。
        String filePath = "アップロードするファイルの実際のローカルパスに置き換えてください。例: Linux の場合 /path/to/your/Alibaba Cloud Model Studio Product Overview.docx";
        uploadFile(preSignedUrlOrHttpUrl, filePath);
    }
}

PHP

<?php

/**
 * ローカルファイルを一時ストレージにアップロードします。
 *
 * @param string $preSignedUrl ApplyFileUploadLease 操作から取得した署名付き URL または HTTP アドレス。
 * @param array $headers "X-bailian-extra" と "Content-Type" を含むリクエストヘッダーの配列。
 * @param string $filePath ローカルファイルのパス。
 * @throws Exception アップロードが失敗した場合。
 */
function uploadFile($preSignedUrl, $headers, $filePath) {
    // ファイルの内容を読み込みます。
    $fileContent = file_get_contents($filePath);
    if ($fileContent === false) {
        throw new Exception("ファイルを読み取れません: " . $filePath);
    }

    // cURL セッションを初期化します。
    $ch = curl_init();

    // cURL オプションを設定します。
    curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // PUT メソッドを使用します。
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // リクエストボディをファイルの内容に設定します。
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // レスポンスを直接出力するのではなく、返します。

    // リクエストヘッダーを構築します。
    $uploadHeaders = [
        "X-bailian-extra: " . $headers["X-bailian-extra"],
        "Content-Type: " . $headers["Content-Type"]
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);

    // リクエストを実行します。
    $response = curl_exec($ch);

    // HTTP ステータスコードを取得します。
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // cURL セッションを閉じます。
    curl_close($ch);

    // レスポンスコードを確認します。
    if ($httpCode != 200) {
        throw new Exception("アップロードに失敗しました。HTTP ステータスコード: " . $httpCode . ", エラーメッセージ: " . $response);
    }

    // アップロードは成功です。
    echo "ファイルは正常にアップロードされました。\n";
}

/**
 * メイン関数: ローカルファイルをアップロードします。
 */
function main() {
    // これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。
    $preSignedUrl = "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。";

    // これらを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra と Content-Type の値に置き換えてください。
    $headers = [
        "X-bailian-extra" => "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。",
        "Content-Type" => "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。"
    ];

    // ローカルファイルを一時ストレージにアップロードします。
    $filePath = "アップロードするファイルの実際のローカルパスに置き換えてください。例: Linux の場合 /path/to/your/Alibaba Cloud Model Studio Product Overview.docx";

    try {
        uploadFile($preSignedUrl, $headers, $filePath);
    } catch (Exception $e) {
        echo "エラー: " . $e->getMessage() . "\n";
    }
}

// メイン関数を呼び出します。
main();

?>

Node.js

const fs = require('fs');
const axios = require('axios');

/**
 * ローカルファイルを一時ストレージにアップロードします。
 *
 * @param {string} preSignedUrl - アップロードリースからの URL。
 * @param {Object} headers - アップロードリクエストのヘッダー。
 * @param {string} filePath - ファイルのローカルパス。
 * @throws {Error} アップロードが失敗した場合。
 */
async function uploadFile(preSignedUrl, headers, filePath) {
    // アップロードに必要なリクエストヘッダーを構築します。
    const uploadHeaders = {
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type": headers["Content-Type"]
    };

    // ファイル読み取りストリームを作成します。
    const fileStream = fs.createReadStream(filePath);

    try {
        // axios を使用して PUT リクエストを送信します。
        const response = await axios.put(preSignedUrl, fileStream, {
            headers: uploadHeaders
        });

        // レスポンスのステータスコードを確認します。
        if (response.status === 200) {
            console.log("ファイルは正常にアップロードされました。");
        } else {
            console.error(`ファイルのアップロードに失敗しました。ResponseCode: ${response.status}`);
            throw new Error(`アップロードに失敗しました。ステータスコード: ${response.status}`);
        }
    } catch (error) {
        // エラーを処理します。
        console.error("アップロード中のエラー:", error.message);
        throw new Error(`アップロードに失敗しました: ${error.message}`);
    }
}

/**
 * メイン関数: ローカルファイルをアップロードします。
 */
function main() {
    const preSignedUrl = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。";

    const headers = {
        "X-bailian-extra": "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。",
        "Content-Type": "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。"
    };

    // ローカルファイルを一時ストレージにアップロードします。
    const filePath = "アップロードするファイルの実際のローカルパスに置き換えてください。例: Linux の場合 /path/to/your/Alibaba Cloud Model Studio Product Overview.docx";

    uploadFile(preSignedUrl, headers, filePath)
        .then(() => {
            console.log("アップロードが完了しました。");
        })
        .catch((err) => {
            console.error("アップロードに失敗しました:", err.message);
        });
}

// メイン関数を呼び出します。
main();

C#

using System;
using System.IO;
using System.Net;

public class UploadFilExample
{
    public static void UploadFile(string preSignedUrl, string filePath)
    {
        HttpWebRequest connection = null;
        try
        {
            // URL オブジェクトを作成します。
            Uri url = new Uri(preSignedUrl);
            connection = (HttpWebRequest)WebRequest.Create(url);
            // ファイルアップロードのリクエストメソッドは、前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Method フィールドの値と同じでなければなりません。
            connection.Method = "PUT";
            // この接続はファイルのアップロードに使用されるため、接続への出力を許可します。
            connection.AllowWriteStreamBuffering = false;
            connection.SendChunked = false;
            // リクエストヘッダーを、前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers のフィールド値と同じに設定します。
            connection.Headers["X-bailian-extra"] = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。";
            connection.ContentType = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。";
            // ファイルを読み込み、接続を介してアップロードします。
            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (var requestStream = connection.GetRequestStream())
            {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Flush();
            }
            // レスポンスを確認します。
            using (HttpWebResponse response = (HttpWebResponse)connection.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // ファイルは正常にアップロードされました。
                    Console.WriteLine("ファイルは正常にアップロードされました。");
                }
                else
                {
                    // ファイルのアップロードに失敗しました。
                    Console.WriteLine($"ファイルのアップロードに失敗しました。ResponseCode: {response.StatusCode}");
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            e.StackTrace.ToString();
        }
        finally
        {
            if (connection != null)
            {
                connection.Abort();
            }
        }
    }

    public static void Main(string[] args)
    {
        string preSignedUrlOrHttpUrl = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。";
        // ローカルファイルを一時ストレージにアップロードします。
        string filePath = "アップロードするファイルの実際のローカルパスに置き換えてください。例: Linux の場合 /path/to/your/Alibaba Cloud Model Studio Product Overview.docx";
        UploadFile(preSignedUrlOrHttpUrl, filePath);
    }
}

Go

package main

import (
    "fmt"
    "io"
    "os"

    "github.com/go-resty/resty/v2"
)

// UploadFile は、ローカルファイルを一時ストレージにアップロードします。
//
// パラメータ:
//   - preSignedUrl (string): アップロードリースからの URL。
//   - headers (map[string]string): アップロードリクエストのヘッダー。
//   - filePath (string): ファイルのローカルパス。
//
// 戻り値:
//   - error: アップロードが失敗した場合はエラーメッセージ、それ以外は nil。
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
    // ローカルファイルを開きます。
    file, err := os.Open(filePath)
    if err != nil {
        return fmt.Errorf("ファイルのオープンに失敗しました: %w", err)
    }
    defer file.Close()

    // 内容を読み込みます。
    body, err := io.ReadAll(file)
    if err != nil {
        return fmt.Errorf("ファイルの読み込みに失敗しました: %w", err)
    }

    // REST クライアントを作成します。
    client := resty.New()

    // アップロードに必要なリクエストヘッダーを構築します。
    uploadHeaders := map[string]string{
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type":    headers["Content-Type"],
    }

    // PUT リクエストを送信します。
    resp, err := client.R().
        SetHeaders(uploadHeaders).
        SetBody(body).
        Put(preSignedUrl)

    if err != nil {
        return fmt.Errorf("リクエストの送信に失敗しました: %w", err)
    }

    // HTTP レスポンスのステータスコードを確認します。
    if resp.IsError() {
        return fmt.Errorf("HTTP エラー: %d", resp.StatusCode())
    }

    fmt.Println("ファイルは正常にアップロードされました。")
    return nil
}

// main 関数
func main() {
    // これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。
    preSignedUrl := "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。"

    // これらを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra と Content-Type の値に置き換えてください。
    headers := map[string]string{
        "X-bailian-extra": "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。",
        "Content-Type":    "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。",
    }

    // ローカルファイルを一時ストレージにアップロードします。
    filePath := "アップロードするファイルの実際のローカルパスに置き換えてください。例: Linux の場合 /path/to/your/Alibaba Cloud Model Studio Product Overview.docx"

    // アップロード関数を呼び出します。
    err := UploadFile(preSignedUrl, headers, filePath)
    if err != nil {
        fmt.Printf("アップロードに失敗しました: %v\n", err)
    }
}

URL アップロード

URL は一般公開されており、有効なファイルを指している必要があります。

Python

import requests
from urllib.parse import urlparse

def upload_file_link(pre_signed_url, source_url_string):
    """
    公開 URL からファイルを一時ストレージにアップロードします。

    Args:
        pre_signed_url (str): アップロードリースからの URL。
        source_url_string (str): ファイルの URL。
    
    Returns:
        Alibaba Cloud Model Studio からのレスポンス。
    """
    try:
        # リクエストヘッダーを設定します。
        headers = {
            "X-bailian-extra": "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。",
            "Content-Type": "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。"
        }

        # ファイル URL にアクセスするためにリクエストメソッドを GET に設定します。
        source_response = requests.get(source_url_string)
        if source_response.status_code != 200:
            raise RuntimeError("ソースファイルの取得に失敗しました。")

        # ファイルアップロードのリクエストメソッドは、前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Method フィールドの値と同じでなければなりません。
        response = requests.put(pre_signed_url, data=source_response.content, headers=headers)

        # レスポンスのステータスコードを確認します。
        if response.status_code == 200:
            print("ファイルは正常にアップロードされました。")
        else:
            print(f"ファイルのアップロードに失敗しました。ResponseCode: {response.status_code}")

    except Exception as e:
        print(f"エラーが発生しました: {str(e)}")

if __name__ == "__main__":

    pre_signed_url_or_http_url = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。"

    # ファイルの URL。
    source_url = "アップロードするファイルの URL に置き換えてください。"
    upload_file_link(pre_signed_url_or_http_url, source_url)

Java

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UploadFile {
    public static void uploadFileLink(String preSignedUrl, String sourceUrlString) {
        HttpURLConnection connection = null;
        try {
            // URL オブジェクトを作成します。
            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();
            // ファイルアップロードのリクエストメソッドは、前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Method フィールドの値と同じでなければなりません。
            connection.setRequestMethod("PUT");
            // この接続はファイルのアップロードに使用されるため、接続への出力を許可します。
            connection.setDoOutput(true);
            connection.setRequestProperty("X-bailian-extra", "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。");
            connection.setRequestProperty("Content-Type", "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。");
            URL sourceUrl = new URL(sourceUrlString);
            HttpURLConnection sourceConnection = (HttpURLConnection) sourceUrl.openConnection();
            // ファイル URL にアクセスするためにリクエストメソッドを GET に設定します。
            sourceConnection.setRequestMethod("GET");
            // レスポンスコードを取得します。200 はリクエストが成功したことを示します。
            int sourceFileResponseCode = sourceConnection.getResponseCode();
            // URL からファイルを読み込み、接続を介してアップロードします。
            if (sourceFileResponseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("ソースファイルの取得に失敗しました。");
            }
            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 InputStream in = new BufferedInputStream(sourceConnection.getInputStream())) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.flush();
            }
            // レスポンスを確認します。
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // ファイルは正常にアップロードされました。
                System.out.println("ファイルは正常にアップロードされました。");
            } else {
                // ファイルのアップロードに失敗しました。
                System.out.println("ファイルのアップロードに失敗しました。ResponseCode: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        String preSignedUrlOrHttpUrl = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。";
        
        String sourceUrl = "アップロードするファイルの URL に置き換えてください。";
        uploadFileLink(preSignedUrlOrHttpUrl, sourceUrl);
    }
}

PHP

<?php

/**
 * 公開 URL からファイルを一時ストレージにアップロードします。
 *
 * @param string $preSignedUrl ApplyFileUploadLease 操作から取得した署名付き URL または HTTP アドレス。
 * @param array $headers "X-bailian-extra" と "Content-Type" を含むリクエストヘッダーの配列。
 * @param string $sourceUrl ファイルの URL。
 * @throws Exception アップロードが失敗した場合。
 */
function uploadFile($preSignedUrl, $headers, $sourceUrl) {

    $fileContent = file_get_contents($sourceUrl);
    if ($fileContent === false) {
        throw new Exception("指定された URL からファイルをダウンロードできません: " . $sourceUrl);
    }
    // cURL セッションを初期化します。
    $ch = curl_init();

    // cURL オプションを設定します。
    curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // PUT メソッドを使用します。
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // リクエストボディをファイルの内容に設定します。
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // レスポンスを直接出力するのではなく、返します。

    // リクエストヘッダーを構築します。
    $uploadHeaders = [
        "X-bailian-extra: " . $headers["X-bailian-extra"],
        "Content-Type: " . $headers["Content-Type"]
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);

    // リクエストを実行します。
    $response = curl_exec($ch);

    // HTTP ステータスコードを取得します。
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // cURL セッションを閉じます。
    curl_close($ch);

    // レスポンスコードを確認します。
    if ($httpCode != 200) {
        throw new Exception("アップロードに失敗しました。HTTP ステータスコード: " . $httpCode . ", エラーメッセージ: " . $response);
    }

    // アップロードは成功です。
    echo "ファイルは正常にアップロードされました。\n";
}

/**
 * メイン関数: 公開 URL からファイルを一時ストレージにアップロードします。
 */
function main() {
    // これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。
    $preSignedUrl = "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。";

    // これらを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra と Content-Type の値に置き換えてください。
    $headers = [
        "X-bailian-extra" => "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。",
        "Content-Type" => "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。"
    ];

    $sourceUrl = "アップロードするファイルの URL に置き換えてください。";

    try {
        uploadFile($preSignedUrl, $headers, $sourceUrl);
    } catch (Exception $e) {
        echo "エラー: " . $e->getMessage() . "\n";
    }
}

// メイン関数を呼び出します。
main();

?>

Node.js

const axios = require('axios');

/**
 * 公開 URL からファイルを一時ストレージにアップロードします。
 *
 * @param {string} preSignedUrl - アップロードリースからの URL。
 * @param {Object} headers - アップロードリクエストのヘッダー。
 * @param {string} sourceUrl - ファイルの URL。
 * @throws {Error} アップロードが失敗した場合。
 */
async function uploadFileFromUrl(preSignedUrl, headers, sourceUrl) {
    // アップロードに必要なリクエストヘッダーを構築します。
    const uploadHeaders = {
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type": headers["Content-Type"]
    };

    try {
        // 指定された URL からファイルをダウンロードします。
        const response = await axios.get(sourceUrl, {
            responseType: 'stream'
        });

        // axios を使用して PUT リクエストを送信します。
        const uploadResponse = await axios.put(preSignedUrl, response.data, {
            headers: uploadHeaders
        });

        // レスポンスのステータスコードを確認します。
        if (uploadResponse.status === 200) {
            console.log("URL からファイルが正常にアップロードされました。");
        } else {
            console.error(`ファイルのアップロードに失敗しました。ResponseCode: ${uploadResponse.status}`);
            throw new Error(`アップロードに失敗しました。ステータスコード: ${uploadResponse.status}`);
        }
    } catch (error) {
        // エラーを処理します。
        console.error("アップロード中のエラー:", error.message);
        throw new Error(`アップロードに失敗しました: ${error.message}`);
    }
}

/**
 * メイン関数: 公開ダウンロード可能なファイルを一時ストレージにアップロードします。
 */
function main() {
    const preSignedUrl = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。";

    const headers = {
        "X-bailian-extra": "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。",
        "Content-Type": "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。"
    };

    const sourceUrl = "アップロードするファイルの URL に置き換えてください。";

    uploadFileFromUrl(preSignedUrl, headers, sourceUrl)
        .then(() => {
            console.log("アップロードが完了しました。");
        })
        .catch((err) => {
            console.error("アップロードに失敗しました:", err.message);
        });
}

// メイン関数を呼び出します。
main();

C#

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

public class UploadFileExample
{
    public static async Task UploadFileFromUrl(string preSignedUrl, string url)
    {
        try
        {
            // 指定された URL からファイルをダウンロードするための HTTP クライアントを作成します。
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                response.EnsureSuccessStatusCode();

                // ファイルストリームを取得します。
                using (Stream fileStream = await response.Content.ReadAsStreamAsync())
                {
                    // URL オブジェクトを作成します。
                    Uri urlObj = new Uri(preSignedUrl);
                    HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(urlObj);

                    // ファイルアップロードのリクエストメソッドを設定します。
                    connection.Method = "PUT";
                    connection.AllowWriteStreamBuffering = false;
                    connection.SendChunked = false;

                    // リクエストヘッダーを設定します。実際の値に置き換えてください。
                    connection.Headers["X-bailian-extra"] = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。";
                    connection.ContentType = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。";

                    // リクエストストリームを取得し、ファイルストリームを書き込みます。
                    using (Stream requestStream = connection.GetRequestStream())
                    {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            await requestStream.WriteAsync(buffer, 0, bytesRead);
                        }
                        await requestStream.FlushAsync();
                    }

                    // レスポンスを確認します。
                    using (HttpWebResponse responseResult = (HttpWebResponse)connection.GetResponse())
                    {
                        if (responseResult.StatusCode == HttpStatusCode.OK)
                        {
                            Console.WriteLine("URL からファイルが正常にアップロードされました。");
                        }
                        else
                        {
                            Console.WriteLine($"ファイルのアップロードに失敗しました。ResponseCode: {responseResult.StatusCode}");
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }

    public static async Task Main(string[] args)
    {
        string preSignedUrlOrHttpUrl = "前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。";
        string url = "アップロードするファイルの URL に置き換えてください。";   

        await UploadFileFromUrl(preSignedUrlOrHttpUrl, url);
    }
}

Go

package main
 
import (
    "fmt"
    "net/http"
 
    "github.com/go-resty/resty/v2"
)
 
// UploadFileFromUrl は、公開 URL からファイルを一時ストレージにアップロードします。
//
// パラメータ:
//   - preSignedUrl (string): アップロードリースからの URL。
//   - headers (map[string]string): アップロードリクエストのヘッダー。
//   - sourceUrl (string): ファイルの URL。
//
// 戻り値:
//   - error: アップロードが失敗した場合はエラーメッセージ、それ以外は nil。
func UploadFileFromUrl(preSignedUrl string, headers map[string]string, sourceUrl string) error {
    // 指定された URL からファイルをダウンロードします。
    resp, err := http.Get(sourceUrl)
    if err != nil {
        return fmt.Errorf("ファイルの取得に失敗しました: %w", err)
    }
    defer resp.Body.Close()
 
    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("ファイルの取得に失敗しました、ステータスコード: %d", resp.StatusCode)
    }
 
    // REST クライアントを作成します。
    client := resty.New()
 
    // アップロードに必要なリクエストヘッダーを構築します。
    uploadHeaders := map[string]string{
        "X-bailian-extra": headers["X-bailian-extra"],
        "Content-Type":    headers["Content-Type"],
    }
 
    // PUT リクエストを送信します。
    response, err := client.R().
        SetHeaders(uploadHeaders).
        SetBody(resp.Body).
        Put(preSignedUrl)
 
    if err != nil {
        return fmt.Errorf("リクエストの送信に失敗しました: %w", err)
    }
 
    if err != nil {
        return fmt.Errorf("リクエストの送信に失敗しました: %w", err)
    }
 
    // HTTP レスポンスのステータスコードを確認します。
    if response.IsError() {
        return fmt.Errorf("HTTP エラー: %d", response.StatusCode())
    }
 
    fmt.Println("URL からファイルが正常にアップロードされました。")
    return nil
}
 
// main 関数
func main() {
    // これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。
    preSignedUrl := "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param の Url フィールドの値に置き換えてください。"
 
    // これらを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra と Content-Type の値に置き換えてください。
    headers := map[string]string{
        "X-bailian-extra": "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の X-bailian-extra フィールドの値に置き換えてください。",
        "Content-Type":    "これを前の手順の ApplyFileUploadLease 操作によって返された Data.Param.Headers の Content-Type フィールドの値に置き換えてください。null 値が返された場合は、null 値を渡してください。",
    }
 
    sourceUrl := "アップロードするファイルの URL に置き換えてください。"
 
    // アップロード関数を呼び出します。
    err := UploadFileFromUrl(preSignedUrl, headers, sourceUrl)
    if err != nil {
        fmt.Printf("アップロードに失敗しました: %v\n", err)
    }
}

2.3. ファイルをカテゴリに追加

ファイルをアップロードした後、AddFile 操作を呼び出して、同じワークスペース内のカテゴリにファイルを追加します。

  • パーサ: DASHSCOPE_DOCMIND を指定します。

  • lease_id: ファイルアップロードリースをリクエストするときに返される Data.FileUploadLeaseId を設定します。

  • category_id: この例では、default を渡します。アップロードにカスタムカテゴリを使用する場合、対応する category_id を渡す必要があります。

    重要

    ここで渡される CategoryId は、ファイルアップロードリースの申請 ステップで使用される CategoryId と一致する必要があります。一致しない場合、Category is mismatched エラーが表示されます。

ファイルを追加すると、Model Studio によってファイルの FileId が返され、その解析が自動的に開始されます。lease_id は直ちに無効になります。別の送信に同じリース ID を再利用しないでください。

重要

Python

def add_file(client: bailian20231229Client, lease_id: str, parser: str, category_id: str, workspace_id: str):
    """
    Alibaba Cloud Model Studio の指定されたカテゴリにファイルを追加します。

    Args:
        client (bailian20231229Client): クライアント。
        lease_id (str): リース ID。
        parser (str): ファイルのパーサー。
        category_id (str): カテゴリ ID。
        workspace_id (str): ワークスペース ID。

    Returns:
        Alibaba Cloud Model Studio からのレスポンス。
    """
    headers = {}
    request = bailian_20231229_models.AddFileRequest(
        lease_id=lease_id,
        parser=parser,
        category_id=category_id,
    )
    runtime = util_models.RuntimeOptions()
    return client.add_file_with_options(workspace_id, request, headers, runtime)

Java

/**
 * ファイルをカテゴリに追加します。
 *
 * @param client      クライアントオブジェクト。
 * @param leaseId     リース ID。
 * @param parser      ファイルのパーサー。
 * @param categoryId  カテゴリ ID。
 * @param workspaceId ワークスペース ID。
 * @return Alibaba Cloud Model Studio からのレスポンスオブジェクト。
 */
public AddFileResponse addFile(com.aliyun.bailian20231229.Client client, String leaseId, String parser, String categoryId, String workspaceId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.AddFileRequest addFileRequest = new com.aliyun.bailian20231229.models.AddFileRequest();
    addFileRequest.setLeaseId(leaseId);
    addFileRequest.setParser(parser);
    addFileRequest.setCategoryId(categoryId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.addFileWithOptions(workspaceId, addFileRequest, headers, runtime);
}

PHP

/**
 * ファイルをカテゴリに追加します。
 *
 * @param Bailian $client クライアント。
 * @param string $leaseId リース ID。
 * @param string $parser ファイルのパーサー。
 * @param string $categoryId カテゴリ ID。
 * @param string $workspaceId ワークスペース ID。
 * @return AddFileResponse Alibaba Cloud Model Studio からのレスポンス。
 */
public function addFile($client, $leaseId, $parser, $categoryId, $workspaceId) {
    $headers = [];
    $addFileRequest = new AddFileRequest([
        "leaseId" => $leaseId,
        "parser" => $parser,
        "categoryId" => $categoryId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->addFileWithOptions($workspaceId, $addFileRequest, $headers, $runtime);
}

Node.js

/**
 * ファイルをカテゴリに追加します。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} leaseId - リース ID。
 * @param {string} parser - ファイルのパーサー。
 * @param {string} categoryId - カテゴリ ID。
 * @param {string} workspaceId - ワークスペース ID。
 * @returns {Promise<bailian20231229.AddFileResponse>} - Alibaba Cloud Model Studio からのレスポンス。
 */
async function addFile(client, leaseId, parser, categoryId, workspaceId) {
 const headers = {};
 const req = new bailian20231229.AddFileRequest({
  leaseId,
  parser,
  categoryId
});
 const runtime = new Util.RuntimeOptions({});
 return await client.addFileWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// ファイルをカテゴリに追加します。
/// </summary>
/// <param name="client">クライアントオブジェクト。</param>
/// <param name="leaseId">リース ID。</param>
/// <param name="parser">ファイルのパーサー。</param>
/// <param name="categoryId">カテゴリ ID。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <returns>Alibaba Cloud Model Studio からのレスポンスオブジェクト。</returns>
/// <exception cref="Exception">呼び出し中にエラーが発生した場合に例外がスローされます。</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.AddFileResponse AddFile(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string leaseId,
    string parser,
    string categoryId,
    string workspaceId)
{
    var headers = new Dictionary<string, string>() { };
    var addFileRequest = new AlibabaCloud.SDK.Bailian20231229.Models.AddFileRequest
    {
        LeaseId = leaseId,
        Parser = parser,
        CategoryId = categoryId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.AddFileWithOptions(workspaceId, addFileRequest, headers, runtime);
}

Go

// AddFile は、Alibaba Cloud Model Studio の指定されたカテゴリにファイルを追加します。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - leaseId (string): リース ID。
//   - parser (string): ファイルのパーサー。
//   - categoryId (string): カテゴリ ID。
//   - workspaceId (string): ワークスペース ID。
//
// 戻り値:
//   - *bailian20231229.AddFileResponse: Alibaba Cloud Model Studio からのレスポンス。
//   - error: エラーメッセージ。
func AddFile(client *bailian20231229.Client, leaseId, parser, categoryId, workspaceId string) (_result *bailian20231229.AddFileResponse, _err error) {
	headers := make(map[string]*string)
	addFileRequest := &bailian20231229.AddFileRequest{
		LeaseId:    tea.String(leaseId),
		Parser:     tea.String(parser),
		CategoryId: tea.String(categoryId),
	}
	runtime := &util.RuntimeOptions{}
	return client.AddFileWithOptions(tea.String(workspaceId), addFileRequest, headers, runtime)
}

リクエスト例

{
  "CategoryId": "default",
  "LeaseId": "d92bd94fa9b54326a2547415e100c9e2.1742195250069",
  "Parser": "DASHSCOPE_DOCMIND",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "Status": "200",
  "Message": "",
  "RequestId": "5832A1F4-AF91-5242-8B75-35BDC9XXXXXX",
  "Data": {
    "FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
    "Parser": "DASHSCOPE_DOCMIND"
  },
  "Code": "Success",
  "Success": "true"
}

2.4. クエリファイルの解析状態

ファイルは解析されるまでナレッジベースで使用できません。ピーク時には、このプロセスに数時間かかることがあります。DescribeFile 操作を呼び出して、その解析ステータスをクエリできます。

Data.Status フィールドが PARSE_SUCCESS の場合、ファイルの解析は成功しており、ナレッジベースにインポートできます。

重要

Python

def describe_file(client, workspace_id, file_id):
    """
    ファイルの基本情報を取得します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        file_id (str): ファイル ID。

    Returns:
        Alibaba Cloud Model Studio からのレスポンス。
    """
    headers = {}
    runtime = util_models.RuntimeOptions()
    return client.describe_file_with_options(workspace_id, file_id, headers, runtime)

Java

/**
 * ファイルの基本情報をクエリします。
 *
 * @param client      クライアントオブジェクト。
 * @param workspaceId ワークスペース ID。
 * @param fileId      ファイル ID。
 * @return Alibaba Cloud Model Studio からのレスポンスオブジェクト。
 */
public DescribeFileResponse describeFile(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}

PHP

/**
 * ファイルの基本情報をクエリします。
 *
 * @param Bailian $client クライアント。
 * @param string $workspaceId ワークスペース ID。
 * @param string $fileId ファイル ID。
 * @return DescribeFileResponse Alibaba Cloud Model Studio からのレスポンス。
 */
public function describeFile($client, $workspaceId, $fileId) {
    $headers = [];
    $runtime = new RuntimeOptions([]);
    return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
}

Node.js

/**
 * ファイルの解析ステータスをクエリします。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} workspaceId - ワークスペース ID。
 * @param {string} fileId - ファイル ID。
 * @returns {Promise<bailian20231229.DescribeFileResponse>} - Alibaba Cloud Model Studio からのレスポンス。
 */
async function describeFile(client, workspaceId, fileId) {
 const headers = {};
 const runtime = new Util.RuntimeOptions({});
 return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}

C#

/// <summary>
/// ファイルの基本情報をクエリします。
/// </summary>
/// <param name="client">クライアントオブジェクト。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="fileId">ファイル ID。</param>
/// <returns>Alibaba Cloud Model Studio からのレスポンスオブジェクト。</returns>
/// <exception cref="Exception">呼び出し中にエラーが発生した場合に例外がスローされます。</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.DescribeFileResponse DescribeFile(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string fileId)
{
    var headers = new Dictionary<string, string>() { };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}

Go

// DescribeFile は、ファイルの基本情報を取得します。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - fileId (string): ファイル ID。
//
// 戻り値:
//   - *bailian20231229.DescribeFileResponse: Alibaba Cloud Model Studio からのレスポンス。
//   - error: エラーメッセージ。
func DescribeFile(client *bailian20231229.Client, workspaceId, fileId string) (_result *bailian20231229.DescribeFileResponse, _err error) {
	headers := make(map[string]*string)
	runtime := &util.RuntimeOptions{}
	return client.DescribeFileWithOptions(tea.String(workspaceId), tea.String(fileId), headers, runtime)
}

リクエスト例

{
  "FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "Status": "200",
  "Message": "",
  "RequestId": "B9246251-987A-5628-8E1E-17BB39XXXXXX",
  "Data": {
    "CategoryId": "cate_206ea350f0014ea4a324adff1ca13011_10xxxxxx",
    "Status": "PARSE_SUCCESS",
    "FileType": "docx",
    "CreateTime": "2025-03-17 15:47:13",
    "FileName": "Alibaba Cloud Model Studio Product Overview.docx",
    "FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
    "SizeInBytes": "14015",
    "Parser": "DASHSCOPE_DOCMIND"
  },
  "Code": "Success",
  "Success": "true"
}

3. ナレッジベースの作成

3.1. ナレッジベースの初期化

ファイルが解析されたら、同じワークスペース内でそのファイルからナレッジベースを作成できます。まず、CreateIndex 操作を呼び出して、ドキュメント検索ナレッジベースを初期化 (ただし最終化はしない) します。

  • workspace_id:ワークスペース ID の取得方法」をご参照ください。

  • file_id:カテゴリにファイルを追加する際に API によって返される FileId を指定します。

    source_typeDATA_CENTER_FILE に設定されている場合、このパラメーターは必須であり、指定されていない場合は API がエラーを返します。
  • structure_type: この例では、unstructured を渡します。

  • ソースタイプ:この例では、 DATA_CENTER_FILE を指定します。

  • sink_type: この例では、 BUILT_IN を指定します。

この API が返す Data.Id フィールドの値は、後続のインデックス構築に使用されるナレッジベース ID です。

このナレッジベースに関連する後続のすべての API 操作で必要となるため、ナレッジベース ID を安全に保管してください。
重要

Python

def create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type):
    """
    Alibaba Cloud Model Studio でナレッジベースを作成 (初期化) します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        file_id (str): ファイル ID。
        name (str): ナレッジベースの名前。
        structure_type (str): ナレッジベースのデータ構造タイプ。
        source_type (str): データソースのタイプ。カテゴリとファイルタイプがサポートされています。
        sink_type (str): ナレッジベースのベクターストレージタイプ。

    Returns:
        Alibaba Cloud Model Studio からのレスポンス。
    """
    headers = {}
    request = bailian_20231229_models.CreateIndexRequest(
        structure_type=structure_type,
        name=name,
        source_type=source_type,
        sink_type=sink_type,
        document_ids=[file_id]
    )
    runtime = util_models.RuntimeOptions()
    return client.create_index_with_options(workspace_id, request, headers, runtime)

Java

/**
 * Alibaba Cloud Model Studio でナレッジベースを作成 (初期化) します。
 *
 * @param client        クライアントオブジェクト。
 * @param workspaceId   ワークスペース ID。
 * @param fileId        ファイル ID。
 * @param name          ナレッジベースの名前。
 * @param structureType ナレッジベースのデータ構造タイプ。
 * @param sourceType    データソースのタイプ。カテゴリとファイルタイプがサポートされています。
 * @param sinkType      ナレッジベースのベクターストレージタイプ。
 * @return Alibaba Cloud Model Studio からのレスポンスオブジェクト。
 */
public CreateIndexResponse createIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId, String name, String structureType, String sourceType, String sinkType) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.CreateIndexRequest createIndexRequest = new com.aliyun.bailian20231229.models.CreateIndexRequest();
    createIndexRequest.setStructureType(structureType);
    createIndexRequest.setName(name);
    createIndexRequest.setSourceType(sourceType);
    createIndexRequest.setSinkType(sinkType);
    createIndexRequest.setDocumentIds(Collections.singletonList(fileId));
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.createIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
}

PHP

/**
 * Alibaba Cloud Model Studio でナレッジベースを作成 (初期化) します。
 *
 * @param Bailian $client クライアント。
 * @param string $workspaceId ワークスペース ID。
 * @param string $fileId ファイル ID。
 * @param string $name ナレッジベースの名前。
 * @param string $structureType ナレッジベースのデータ構造タイプ。
 * @param string $sourceType データソースのタイプ。カテゴリとファイルタイプがサポートされています。
 * @param string $sinkType ナレッジベースのベクターストレージタイプ。
 * @return CreateIndexResponse Alibaba Cloud Model Studio からのレスポンス。
 */
public function createIndex($client, $workspaceId, $fileId, $name, $structureType, $sourceType, $sinkType) {
    $headers = [];
    $createIndexRequest = new CreateIndexRequest([
        "structureType" => $structureType,
        "name" => $name,
        "sourceType" => $sourceType,
        "documentIds" => [
            $fileId
        ],
        "sinkType" => $sinkType
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->createIndexWithOptions($workspaceId, $createIndexRequest, $headers, $runtime);
}

Node.js

/**
 * ナレッジベース (インデックス) を初期化します。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} workspaceId - ワークスペース ID。
 * @param {string} fileId - ファイル ID。
 * @param {string} name - ナレッジベースの名前。
 * @param {string} structureType - ナレッジベースのデータ構造タイプ。
 * @param {string} sourceType - データソースのタイプ。カテゴリとファイルタイプがサポートされています。
 * @param {string} sinkType - ナレッジベースのベクターストレージタイプ。
 * @returns {Promise<bailian20231229.CreateIndexResponse>} - Alibaba Cloud Model Studio からのレスポンス。
 */
async function createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType) {
 const headers = {};
 const req = new bailian20231229.CreateIndexRequest({
   name,
   structureType,
   documentIds: [fileId],
   sourceType,
   sinkType
 });
 const runtime = new Util.RuntimeOptions({});
 return await client.createIndexWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// Alibaba Cloud Model Studio でナレッジベースを作成 (初期化) します。
/// </summary>
/// <param name="client">クライアントオブジェクト。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="fileId">ファイル ID。</param>
/// <param name="name">ナレッジベースの名前。</param>
/// <param name="structureType">ナレッジベースのデータ構造タイプ。</param>
/// <param name="sourceType">データソースのタイプ。カテゴリとファイルタイプがサポートされています。</param>
/// <param name="sinkType">ナレッジベースのベクターストレージタイプ。</param>
/// <returns>Alibaba Cloud Model Studio からのレスポンスオブジェクト。</returns>
/// <exception cref="Exception">呼び出し中にエラーが発生した場合に例外がスローされます。</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexResponse CreateIndex(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string fileId,
    string name,
    string structureType,
    string sourceType,
    string sinkType)
{
    var headers = new Dictionary<string, string>() { };
    var createIndexRequest = new AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexRequest
    {
        StructureType = structureType,
        Name = name,
        SourceType = sourceType,
        SinkType = sinkType,
        DocumentIds = new List<string> { fileId }
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.CreateIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
}

Go

// CreateIndex は、Alibaba Cloud Model Studio でナレッジベースを作成 (初期化) します。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - fileId (string): ファイル ID。
//   - name (string): ナレッジベースの名前。
//   - structureType (string): ナレッジベースのデータ構造タイプ。
//   - sourceType (string): データソースのタイプ。カテゴリとファイルタイプがサポートされています。
//   - sinkType (string): ナレッジベースのベクターストレージタイプ。
//
// 戻り値:
//   - *bailian20231229.CreateIndexResponse: Alibaba Cloud Model Studio からのレスポンス。
//   - error: エラーメッセージ。
func CreateIndex(client *bailian20231229.Client, workspaceId, fileId, name, structureType, sourceType, sinkType string) (_result *bailian20231229.CreateIndexResponse, _err error) {
	headers := make(map[string]*string)
	createIndexRequest := &bailian20231229.CreateIndexRequest{
		StructureType: tea.String(structureType),
		Name:          tea.String(name),
		SourceType:    tea.String(sourceType),
		SinkType:      tea.String(sinkType),
		DocumentIds:   []*string{tea.String(fileId)},
	}
	runtime := &util.RuntimeOptions{}
	return client.CreateIndexWithOptions(tea.String(workspaceId), createIndexRequest, headers, runtime)
}

リクエスト例

{
  "Name": "Alibaba Cloud Model Studio スマートフォンナレッジベース",
  "SinkType": "BUILT_IN",
  "SourceType": "DATA_CENTER_FILE",
  "StructureType": "unstructured",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
  "DocumentIds": [
    "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
  ]
}

レスポンス例

{
  "Status": "200",
  "Message": "success",
  "RequestId": "87CB0999-F1BB-5290-8C79-A875B2XXXXXX",
  "Data": {
    "Id": "mymxbdxxxx"
  },
  "Code": "Success",
  "Success": "true"
}

3.2. インデックスジョブの送信

ナレッジベースを初期化した後、SubmitIndexJob 操作を呼び出してインデックス構築プロセスを開始します。

送信が完了すると、Model Studio はすぐに非同期タスクとしてインデックスの構築を開始します。この API 呼び出しによって返される Data.Id は、対応するタスク ID です。次のステップでは、この ID を使用してタスクの最新のステータスをクエリします。

重要

Python

def submit_index(client, workspace_id, index_id):
    """
    Alibaba Cloud Model Studio にインデックスジョブを送信します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。

    Returns:
        Alibaba Cloud Model Studio からのレスポンス。
    """
    headers = {}
    submit_index_job_request = bailian_20231229_models.SubmitIndexJobRequest(
        index_id=index_id
    )
    runtime = util_models.RuntimeOptions()
    return client.submit_index_job_with_options(workspace_id, submit_index_job_request, headers, runtime)

Java

/**
 * Alibaba Cloud Model Studio にインデックスジョブを送信します。
 *
 * @param client      クライアントオブジェクト。
 * @param workspaceId ワークスペース ID。
 * @param indexId     ナレッジベース ID。
 * @return Alibaba Cloud Model Studio からのレスポンスオブジェクト。
 */
public SubmitIndexJobResponse submitIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.SubmitIndexJobRequest submitIndexJobRequest = new com.aliyun.bailian20231229.models.SubmitIndexJobRequest();
    submitIndexJobRequest.setIndexId(indexId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.submitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
}

PHP

/**
 * Alibaba Cloud Model Studio にインデックスジョブを送信します。
 *
 * @param Bailian $client クライアント。
 * @param string $workspaceId ワークスペース ID。
 * @param string $indexId ナレッジベース ID。
 * @return SubmitIndexJobResponse Alibaba Cloud Model Studio からのレスポンス。
 */
public static function submitIndex($client, $workspaceId, $indexId) {
    $headers = [];
    $submitIndexJobRequest = new SubmitIndexJobRequest([
        'indexId' => $indexId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->submitIndexJobWithOptions($workspaceId, $submitIndexJobRequest, $headers, $runtime);
}

Node.js

/**
 * インデックスジョブを送信します。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} workspaceId - ワークスペース ID。
 * @param {string} indexId - ナレッジベース ID。
 * @returns {Promise<bailian20231229.SubmitIndexJobResponse>} - Alibaba Cloud Model Studio からのレスポンス。
 */
async function submitIndex(client, workspaceId, indexId) {
  const headers = {};
  const req = new bailian20231229.SubmitIndexJobRequest({ indexId });
  const runtime = new Util.RuntimeOptions({});
  return await client.submitIndexJobWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// Alibaba Cloud Model Studio にインデックスジョブを送信します。
/// </summary>
/// <param name="client">クライアントオブジェクト。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="indexId">ナレッジベース ID。</param>
/// <returns>Alibaba Cloud Model Studio からのレスポンスオブジェクト。</returns>
/// <exception cref="Exception">呼び出し中にエラーが発生した場合に例外がスローされます。</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobResponse SubmitIndex(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string indexId)
{
    var headers = new Dictionary<string, string>() { };
    var submitIndexJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobRequest
    {
           IndexId = indexId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.SubmitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
}

Go

// SubmitIndex はインデックスジョブを送信します。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): ナレッジベース ID。
//
// 戻り値:
//   - *bailian20231229.SubmitIndexJobResponse: Alibaba Cloud Model Studio からのレスポンス。
//   - error: エラーメッセージ。
func SubmitIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.SubmitIndexJobResponse, _err error) {
	headers := make(map[string]*string)
	submitIndexJobRequest := &bailian20231229.SubmitIndexJobRequest{
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.SubmitIndexJobWithOptions(tea.String(workspaceId), submitIndexJobRequest, headers, runtime)
}

リクエスト例

{
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "Status": "200",
  "Message": "success",
  "RequestId": "7774575F-571D-5854-82C2-634AB8XXXXXX",
  "Data": {
    "IndexId": "mymxbdxxxx",
    "Id": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
  },
  "Code": "Success",
  "Success": "true"
}

3.3. インデックスジョブのステータスのクエリ

インデックスジョブの完了には時間がかかります。ピーク時には、このプロセスに数時間かかることがあります。GetIndexJobStatus 操作を呼び出して、その実行ステータスをクエリします。

Data.Status フィールドが COMPLETED の場合、ナレッジベースは作成されています。

重要

Python

def get_index_job_status(client, workspace_id, index_id, job_id):
    """
    インデックスジョブのステータスをクエリします。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        job_id (str): ジョブ ID。

    Returns:
        Alibaba Cloud Model Studio からのレスポンス。
    """
    headers = {}
    get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
        index_id=index_id,
        job_id=job_id
    )
    runtime = util_models.RuntimeOptions()
    return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)

Java

/**
 * インデックスジョブのステータスをクエリします。
 *
 * @param client      クライアントオブジェクト。
 * @param workspaceId ワークスペース ID。
 * @param jobId       ジョブ ID。
 * @param indexId     ナレッジベース ID。
 * @return Alibaba Cloud Model Studio からのレスポンスオブジェクト。
 */
public GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest();
    getIndexJobStatusRequest.setIndexId(indexId);
    getIndexJobStatusRequest.setJobId(jobId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    GetIndexJobStatusResponse getIndexJobStatusResponse = null;
    getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
    return getIndexJobStatusResponse;
}

PHP

/**
 * インデックスジョブのステータスをクエリします。
 *
 * @param Bailian $client クライアント。
 * @param string $workspaceId ワークスペース ID。
 * @param string $indexId ナレッジベース ID。
 * @param string $jobId ジョブ ID。
 * @return GetIndexJobStatusResponse Alibaba Cloud Model Studio からのレスポンス。
 */
public function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
    $headers = [];
    $getIndexJobStatusRequest = new GetIndexJobStatusRequest([
        'indexId' => $indexId,
        'jobId' => $jobId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
}

Node.js

/**
 * インデックスジョブのステータスをクエリします。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} workspaceId - ワークスペース ID。
 * @param {string} jobId - ジョブ ID。
 * @param {string} indexId - ナレッジベース ID。
 * @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - Alibaba Cloud Model Studio からのレスポンス。
 */
async function getIndexJobStatus(client, workspaceId, jobId, indexId) {
  const headers = {};
  const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId });
  const runtime = new Util.RuntimeOptions({});
  return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// インデックスジョブのステータスをクエリします。
/// </summary>
/// <param name="client">クライアントオブジェクト。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="jobId">ジョブ ID。</param>
/// <param name="indexId">ナレッジベース ID。</param>
/// <returns>Alibaba Cloud Model Studio からのレスポンスオブジェクト。</returns>
/// <exception cref="Exception">呼び出し中にエラーが発生した場合に例外がスローされます。</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string jobId,
    string indexId)
{
    var headers = new Dictionary<string, string>() { };
    var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest
    {
        IndexId = indexId,
        JobId = jobId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
}

Go

// GetIndexJobStatus はインデックスジョブのステータスをクエリします。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - jobId (string): ジョブ ID。
//   - indexId (string): ナレッジベース ID。
//
// 戻り値:
//   - *bailian20231229.GetIndexJobStatusResponse: Alibaba Cloud Model Studio からのレスポンス。
//   - error: エラーメッセージ。
func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) {
	headers := make(map[string]*string)
	getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{
		JobId:   tea.String(jobId),
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime)
}

リクエスト例

{
  "IndexId": "mymxbdxxxx",
  "JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "Status": "200",
  "Message": "success",
  "RequestId": "E83423B9-7D6D-5283-836B-CF7EAEXXXXXX",
  "Data": {
    "Status": "COMPLETED",
    "Documents": [
      {
        "Status": "FINISH",
        "DocId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
        "Message": "正常にインポートされました。",
        "DocName": "Alibaba Cloud Model Studio 製品概要",
        "Code": "FINISH"
      }
    ],
    "JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
  },
  "Code": "Success",
  "Success": "true"
}

アップロードされたファイルからナレッジベースが作成されました。

ナレッジベースからの取得

ナレッジベースから情報を取得するには、2 つの方法があります:

  • Alibaba Cloud Model Studio アプリケーションの使用: アプリケーションを呼び出す際、rag_options パラメーターを使用してナレッジベース ID index_id を渡します。これにより、モデルを非公開ナレッジで補完し、最新の情報を提供します。

  • Alibaba Cloud API の使用: Retrieve API を呼び出して、指定されたナレッジベースから情報を取得し、元のテキストセグメントを返します。

最初の方法では、取得したテキストセグメントを設定済みのモデルに送信して最終的な回答を生成しますが、2 番目の方法ではテキストセグメントを直接返します。

このセクションでは、Alibaba Cloud API の使用方法について説明します。

指定されたナレッジベースから情報を取得してテキストセグメントを返すには、Retrieve API を呼び出します。

レスポンスに無関係な情報が過剰に含まれている場合は、リクエストで SearchFilters を指定して、タグなどの基準で結果をフィルタリングします。

重要

Python

def retrieve_index(client, workspace_id, index_id, query):
    """
    指定されたナレッジベースから情報を取得します。
        
    Args:
        client (bailian20231229Client): クライアントオブジェクト。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        query (str): 検索クエリ。

    Returns:
        Model Studio サービスからのレスポンス。
    """
    headers = {}
    retrieve_request = bailian_20231229_models.RetrieveRequest(
        index_id=index_id,
        query=query
    )
    runtime = util_models.RuntimeOptions()
    return client.retrieve_with_options(workspace_id, retrieve_request, headers, runtime)

Java

/**
 * 指定されたナレッジベースから情報を取得します。
 *
 * @param client         クライアントオブジェクト。
 * @param workspaceId    ワークスペース ID。
 * @param indexId        ナレッジベース ID。
 * @param query          検索クエリ。
 * @return               Model Studio サービスからのレスポンス。
 */
public RetrieveResponse retrieveIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String query) throws Exception {
    RetrieveRequest retrieveRequest = new RetrieveRequest();
    retrieveRequest.setIndexId(indexId);
    retrieveRequest.setQuery(query);
    RuntimeOptions runtime = new RuntimeOptions();
    return client.retrieveWithOptions(workspaceId, retrieveRequest, null, runtime);
}

PHP

/**
 * 指定されたナレッジベースから情報を取得します。
 *
 * @param Bailian $client クライアントオブジェクト。
 * @param string $workspaceId ワークスペース ID。
 * @param string $indexId ナレッジベース ID。
 * @param string $query 検索クエリ。
 * @return RetrieveResponse Model Studio サービスからのレスポンス。
 * @throws Exception
 */
public function retrieveIndex($client, $workspaceId, $indexId, $query) {
    $headers = [];
    $retrieveRequest = new RetrieveRequest([
        "query" => $query,
        "indexId" => $indexId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->retrieveWithOptions($workspaceId, $retrieveRequest, $headers, $runtime);
}

Node.js

/**
 * 指定されたナレッジベースから情報を取得します。
 * @param {bailian20231229.Client} client クライアントオブジェクト。
 * @param {string} workspaceId ワークスペース ID。
 * @param {string} indexId ナレッジベース ID。
 * @param {string} query 検索クエリ。
 * @returns {Promise<bailian20231229.RetrieveResponse>} Model Studio サービスからのレスポンス。
 */
async function retrieveIndex(client, workspaceId, indexId, query) {
    const headers = {};
    const req = new bailian20231229.RetrieveRequest({
        indexId,
        query
    });
    const runtime = new Util.RuntimeOptions({});
    return await client.retrieveWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// 指定されたナレッジベースから情報を取得します。
/// </summary>
/// <param name="client">クライアントオブジェクト。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="indexId">ナレッジベース ID。</param>
/// <param name="query">検索クエリ。</param>
/// <returns>Model Studio サービスからのレスポンス。</returns>
/// <exception cref="Exception">呼び出しが失敗した場合にスローされます。</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.RetrieveResponse RetrieveIndex(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string indexId,
    string query)
{
    var headers = new Dictionary<string, string>() { };
    var retrieveRequest = new AlibabaCloud.SDK.Bailian20231229.Models.RetrieveRequest
    {
        IndexId = indexId,
        Query = query
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.RetrieveWithOptions(workspaceId, retrieveRequest, headers, runtime);
}

Go

// retrieveIndex は、指定されたナレッジベースから情報を取得します。
//
// Args:
//   - client (bailian20231229.Client): クライアントオブジェクト。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): ナレッジベース ID。
//   - query (string): 検索クエリ。
//
// Returns:
//   - *bailian20231229.RetrieveResponse: Model Studio サービスからのレスポンス。
//   - error: エラー (もしあれば)。
func retrieveIndex(client *bailian20231229.Client, workspaceId, indexId, query string) (*bailian20231229.RetrieveResponse, error) {
	headers := make(map[string]*string)
	request := &bailian20231229.RetrieveRequest{
		IndexId: tea.String(indexId),
		Query:   tea.String(query),
	}
	runtime := &util.RuntimeOptions{}
	return client.RetrieveWithOptions(tea.String(workspaceId), request, headers, runtime)
}

リクエスト例

{
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
  "Query": "Alibaba Cloud Model Studio X1 スマートフォンを紹介してください。"
}

レスポンス例

{
  "Status": "200",
  "Message": "success",
  "RequestId": "17316EA2-1F4D-55AC-8872-53F6F1XXXXXX",
  "Data": {
    "Nodes": [
      {
        "Score": 0.6294550895690918,
        "Metadata": {
          "file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Model_Studio_Series_Phone_Product_Introduction_1742197778230.json?Expires=1742457465&OSSAccessKeyId=TestID&Signature=ptFkSObdnBrbJNEw8CnlOSP%2FTeI%3D",
          "is_displayed_chunk_content": "true",
          "_rc_v_score": 0.7449869735535081,
          "image_url": [],
          "nid": "9ad347d9e4d7465d2c1e693a08b0077c|d6f7fbf8403e0df796258e5ada1ee1c1|4772257e93ed64ea087ff4be0d5e4620|7ce1370e4a1958842c9268144a452cc7",
          "_q_score": 1,
          "source": "0",
          "_score": 0.6294550895690918,
          "title": "Alibaba Cloud Model Studio スマートフォン製品紹介",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "Alibaba Cloud Model Studio スマートフォン製品紹介\nAlibaba Cloud Model Studio X1 — 究極の視覚体験をお楽しみください: 6.7 インチ 1440 x 3200 ピクセルの超クリアスクリーンと 120 Hz のリフレッシュレートで、滑らかで鮮やかな視覚体験を提供します。256 GB の大容量ストレージと 12 GB の RAM の強力な組み合わせにより、大規模なゲームやマルチタスクも楽々こなします。長持ちする 5000 mAh バッテリーと超高感度クアッドカメラシステムで、人生の素晴らしい瞬間をすべて捉えます。参考価格: 4,599–4,999\nTongyi Vivid 7 — スマート写真の新しい体験: 6.5 インチ 1080 x 2400 ピクセルのフルスクリーンを搭載。AI スマート写真機能により、すべての写真がプロ級の色とディテールで表示されます。8 GB の RAM と 128 GB のストレージでスムーズな操作を保証し、4,500 mAh のバッテリーが日常のニーズを満たします。側面の指紋認証は便利で安全です。参考価格: 2,999–3,299\nStardust S9 Pro — 革新的な視覚の饗宴: 画期的な 6.9 インチ 1440 x 3088 ピクセルのアンダースクリーンカメラデザインにより、ボーダーレスな視覚体験を提供します。512 GB のストレージと 16 GB の RAM を備えた最高級の構成に、6,000 mAh のバッテリーと 100 W の高速充電技術を組み合わせ、パフォーマンスと耐久性の両方を提供し、技術トレンドをリードします。参考価格: 5,999–6,499。",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "Alibaba Cloud Model Studio スマートフォン製品紹介",
          "_rc_t_score": 0.05215025693178177,
          "doc_name": "Alibaba Cloud Model Studio シリーズスマートフォン製品紹介",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_0"
        },
        "Text": "Alibaba Cloud Model Studio スマートフォン製品紹介\nAlibaba Cloud Model Studio X1 — 究極の視覚体験をお楽しみください: 6.7 インチ 1440 x 3200 ピクセルの超クリアスクリーンと 120 Hz のリフレッシュレートで、滑らかで鮮やかな視覚体験を提供します。256 GB の大容量ストレージと 12 GB の RAM の強力な組み合わせにより、大規模なゲームやマルチタスクも楽々こなします。長持ちする 5000 mAh バッテリーと超高感度クアッドカメラシステムで、人生の素晴らしい瞬間をすべて捉えます。参考価格: 4,599–4,999\nTongyi Vivid 7 — スマート写真の新しい体験: 6.5 インチ 1080 x 2400 ピクセルのフルスクリーンを搭載。AI スマート写真機能により、すべての写真がプロ級の色とディテールで表示されます。8 GB の RAM と 128 GB のストレージでスムーズな操作を保証し、4,500 mAh のバッテリーが日常のニーズを満たします。側面の指紋認証は便利で安全です。参考価格: 2,999–3,299\nStardust S9 Pro — 革新的な視覚の饗宴: 画期的な 6.9 インチ 1440 x 3088 ピクセルのアンダースクリーンカメラデザインにより、ボーダーレスな視覚体験を提供します。512 GB のストレージと 16 GB の RAM を備えた最高級の構成に、6,000 mAh のバッテリーと 100 W の高速充電技術を組み合わせ、パフォーマンスと耐久性の両方を提供し、技術トレンドをリードします。参考価格: 5,999–6,499。"
      },
      {
        "Score": 0.5322970747947693,
        "Metadata": {
          "file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Model_Studio_Series_Phone_Product_Introduction_1742197778230.json?Expires=1742457465&OSSAccessKeyId=TestID&Signature=ptFkSObdnBrbJNEw8CnlOSP%2FTeI%3D",
          "is_displayed_chunk_content": "true",
          "_rc_v_score": 0.641660213470459,
          "image_url": [],
          "nid": "00be1864c18b4c39c59f83713af80092|4f2bfb02cc9fc4e85597b2e717699207",
          "_q_score": 0.9948930557644994,
          "source": "0",
          "_score": 0.5322970747947693,
          "title": "Alibaba Cloud Model Studio スマートフォン製品紹介",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "Alibaba Cloud Model Studio Flex Fold+ — 折りたたみ式スクリーンの新時代: 革新と豪華さを兼ね備え、7.6 インチ 1800 x 2400 ピクセルのメインスクリーンと 4.7 インチ 1080 x 2400 ピクセルの外部スクリーンを搭載。マルチアングル自由停止ヒンジ設計は、さまざまなシナリオのニーズに対応します。Alibaba Cloud Model Studio Flex Fold+ — 折りたたみ式スクリーンの新時代: 革新と豪華さを兼ね備え、7.6 インチ 1800 x 2400 ピクセルのメインスクリーンと 4.7 インチ 1080 x 2400 ピクセルの外部スクリーンを搭載。マルチアングル自由停止ヒンジ設計は、さまざまなシナリオのニーズに対応します。512 GB のストレージ、12 GB の RAM、4700 mAh のバッテリー、UTG 超薄型フレキシブルガラスが、折りたたみ式スクリーンの時代の新しい章を開きます。さらに、このスマートフォンはデュアル SIM デュアルスタンバイと衛星通話をサポートし、世界中のどこにいても接続を維持できます。参考小売価格: 9,999–10,999。各スマートフォンは職人技の傑作であり、手の中の技術芸術作品となるように設計されています。スマートな相棒を選んで、未来の技術生活の新しい章を始めましょう。",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "Alibaba Cloud Model Studio スマートフォン製品紹介",
          "_rc_t_score": 0.05188392847776413,
          "doc_name": "Alibaba Cloud Model Studio シリーズスマートフォン製品紹介",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_2"
        },
        "Text": "Alibaba Cloud Model Studio Flex Fold+ — 折りたたみ式スクリーンの新時代: 革新と豪華さを兼ね備え、7.6 インチ 1800 x 2400 ピクセルのメインスクリーンと 4.7 インチ 1080 x 2400 ピクセルの外部スクリーンを搭載。マルチアングル自由停止ヒンジ設計は、さまざまなシナリオのニーズに対応します。Alibaba Cloud Model Studio Flex Fold+ — 折りたたみ式スクリーンの新時代: 革新と豪華さを兼ね備え、7.6 インチ 1800 x 2400 ピクセルのメインスクリーンと 4.7 インチ 1080 x 2400 ピクセルの外部スクリーンを搭載。マルチアングル自由停止ヒンジ設計は、さまざまなシナリオのニーズに対応します。512 GB のストレージ、12 GB の RAM、4700 mAh のバッテリー、UTG 超薄型フレキシブルガラスが、折りたたみ式スクリーンの時代の新しい章を開きます。さらに、このスマートフォンはデュアル SIM デュアルスタンバイと衛星通話をサポートし、世界中のどこにいても接続を維持できます。参考小売価格: 9,999–10,999。各スマートフォンは職人技の傑作であり、手の中の技術芸術作品となるように設計されています。スマートな相棒を選んで、未来の技術生活の新しい章を始めましょう。"
      },
      {
        "Score": 0.5050643086433411,
        "Metadata": {
          "file_path": "https://bailian-datahub-data-prod.oss-cn-beijing.aliyuncs.com/10285263/multimodal/docJson/Model_Studio_Series_Phone_Product_Introduction_1742197778230.json?Expires=1742457465&OSSAccessKeyId=TestID&Signature=ptFkSObdnBrbJNEw8CnlOSP%2FTeI%3D",
          "is_displayed_chunk_content": "true",
          "_rc_v_score": 0.6757396459579468,
          "image_url": [],
          "nid": "f05d1b51eb6b033b32a162d90a9da71b|5cb6b848be8d11eb168c031025415cc5|4f2bfb02cc9fc4e85597b2e717699207",
          "_q_score": 0.9890713450653327,
          "source": "0",
          "_score": 0.5050643086433411,
          "title": "Alibaba Cloud Model Studio スマートフォン製品紹介",
          "doc_id": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
          "content": "512 GB のストレージと 16 GB の RAM を備えた最高級の構成に、6,000 mAh のバッテリーと 100 W の高速充電技術を組み合わせ、パフォーマンスと耐久性の両方を提供し、技術トレンドをリードします。参考価格: 5,999–6,499。Alibaba Cloud Model Studio Ace Ultra — ゲーマーの選択: 6.67 インチ 1080 x 2400 ピクセルのスクリーン、10 GB の RAM、256 GB のストレージを搭載し、シルクのように滑らかなゲームプレイを保証します。液体冷却システムを備えた 5,500 mAh のバッテリーは、長時間のゲームセッションでも涼しく保ちます。高ダイナミックデュアルスピーカーは、没入感のあるサウンドエフェクトでゲーム体験をアップグレードします。参考価格: 3,999–4,299。Alibaba Cloud Model Studio Zephyr Z9 — 薄くてポータブルな芸術: 軽量な 6.4 インチ 1080 x 2340 ピクセルのデザインで、128 GB のストレージと 6 GB の RAM を備え、日常使用には十分すぎるほどです。4,000 mAh のバッテリーは、一日中安心して使用できます。30 倍のデジタルズームレンズで遠くのディテールを捉えます。薄くてもパワフルです。参考価格: 2,499–2,799。Alibaba Cloud Model Studio Flex Fold+ — 折りたたみ式スクリーンの新時代: 革新と豪華さを兼ね備え、7.6 インチ 1800 x 2400 ピクセルのメインスクリーンと 4.7 インチ 1080 x 2400 ピクセルの外部スクリーンを搭載。マルチアングル自由停止ヒンジ設計は、さまざまなシナリオのニーズに対応します。",
          "_rc_score": 0,
          "workspace_id": "llm-4u5xpd1xdjqpxxxx",
          "hier_title": "Alibaba Cloud Model Studio スマートフォン製品紹介",
          "_rc_t_score": 0.05158032476902008,
          "doc_name": "Alibaba Cloud Model Studio シリーズスマートフォン製品紹介",
          "pipeline_id": "mymxbdxxxx",
          "_id": "llm-4u5xpd1xdjqp8itj_mymxbd6172_file_0b21e0a852cd40cd9741c54fefbb61cd_10285263_0_1"
        },
        "Text": "512 GB のストレージと 16 GB の RAM を備えた最高級の構成に、6,000 mAh のバッテリーと 100 W の高速充電技術を組み合わせ、パフォーマンスと耐久性の両方を提供し、技術トレンドをリードします。参考価格: 5,999–6,499。Alibaba Cloud Model Studio Ace Ultra — ゲーマーの選択: 6.67 インチ 1080 x 2400 ピクセルのスクリーン、10 GB の RAM、256 GB のストレージを搭載し、シルクのように滑らかなゲームプレイを保証します。液体冷却システムを備えた 5,500 mAh のバッテリーは、長時間のゲームセッションでも涼しく保ちます。高ダイナミックデュアルスピーカーは、没入感のあるサウンドエフェクトでゲーム体験をアップグレードします。参考価格: 3,999–4,299。Alibaba Cloud Model Studio Zephyr Z9 — 薄くてポータブルな芸術: 軽量な 6.4 インチ 1080 x 2340 ピクセルのデザインで、128 GB のストレージと 6 GB の RAM を備え、日常使用には十分すぎるほどです。4,000 mAh のバッテリーは、一日中安心して使用できます。30 倍のデジタルズームレンズで遠くのディテールを捉えます。薄くてもパワフルです。参考価格: 2,499–2,799。Alibaba Cloud Model Studio Flex Fold+ — 折りたたみ式スクリーンの新時代: 革新と豪華さを兼ね備え、7.6 インチ 1800 x 2400 ピクセルのメインスクリーンと 4.7 インチ 1080 x 2400 ピクセルの外部スクリーンを搭載。マルチアングル自由停止ヒンジ設計は、さまざまなシナリオのニーズに対応します。"
      }
    ]
  },
  "Code": "Success",
  "Success": "true"
}

ナレッジベースの更新

以下の例は、ドキュメント検索ナレッジベースを更新する方法を示しています。ナレッジベースを使用するアプリケーションは、更新をリアルタイムで反映します。新しいコンテンツは取得可能になり、削除されたコンテンツはアクセスできなくなります。

データクエリまたは画像 Q&A ナレッジベースは API を使用して更新することはできません。詳細については、「ナレッジベースの更新」をご参照ください。
  • 増分更新: サポートされている唯一の方法は、更新されたファイルをアップロードし、ファイルをナレッジベースに追加してから古いファイルを削除するという 3 段階のプロセスです。

  • 完全更新: ナレッジベース内の各ファイルについて、3 つのステップを実行して更新を完了します。

  • 自動更新または同期: 詳細については、「ナレッジベースを自動的に更新または同期する方法」をご参照ください。

  • 単一更新のファイル制限: 一度に更新するファイルは 10,000 ファイル以下にすることを推奨します。この制限を超えると、ナレッジベースが正しく更新されない可能性があります。

1. 更新されたファイルのアップロード

ナレッジベースの作成:ステップ 2 の手順に従って、更新されたファイルをナレッジベースを含むワークスペースにアップロードします。

更新されたファイル用に新しいアップロードパラメータのセットを生成するために、新しいファイルアップロードリースをリクエストしてください。

2. ナレッジベースへのファイルの追加

2.1. 追加タスクの送信

アップロードされたファイルが解析された後、SubmitIndexAddDocumentsJob 操作を呼び出して、新しいファイルをナレッジベースに追加し、ナレッジベースインデックスを再構築します。

タスクを送信すると、Model Studio は非同期でナレッジベースを再構築します。この操作では、タスク ID (job_id) である Data.Id が返されます。次のステップでこの ID を使用して、タスクのステータスをクエリします。

重要
  • SubmitIndexAddDocumentsJob 操作を呼び出した後、タスクが完了するまでには時間がかかります。 job_id を使用してタスクのステータスをクエリできます。 タスクが完了する前に再送信しないでください。

重要

Python

def submit_index_add_documents_job(client, workspace_id, index_id, file_id, source_type):
    """
    解析済みのファイルをドキュメント検索ナレッジベースに追加してインポートします。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        file_id (str): ファイル ID。
        source_type(str): データの型。

    Returns:
        Alibaba Cloud Model Studio サービスからのレスポンス。
    """
    headers = {}
    submit_index_add_documents_job_request = bailian_20231229_models.SubmitIndexAddDocumentsJobRequest(
        index_id=index_id,
        document_ids=[file_id],
        source_type=source_type
    )
    runtime = util_models.RuntimeOptions()
    return client.submit_index_add_documents_job_with_options(workspace_id, submit_index_add_documents_job_request, headers, runtime)

Java

/**
 * 解析済みのファイルをドキュメント検索ナレッジベースに追加してインポートします。
 *
 * @param client      クライアント。
 * @param workspaceId ワークスペース ID。
 * @param indexId     ナレッジベース ID。
 * @param fileId      ファイル ID。
 * @param sourceType  データの型。
 * @return Alibaba Cloud Model Studio サービスからのレスポンス。
 */
public SubmitIndexAddDocumentsJobResponse submitIndexAddDocumentsJob(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String fileId, String sourceType) throws Exception {
    Map<String, String> headers = new HashMap<>();
    SubmitIndexAddDocumentsJobRequest submitIndexAddDocumentsJobRequest = new SubmitIndexAddDocumentsJobRequest();
    submitIndexAddDocumentsJobRequest.setIndexId(indexId);
    submitIndexAddDocumentsJobRequest.setDocumentIds(Collections.singletonList(fileId));
    submitIndexAddDocumentsJobRequest.setSourceType(sourceType);
    RuntimeOptions runtime = new RuntimeOptions();
    return client.submitIndexAddDocumentsJobWithOptions(workspaceId, submitIndexAddDocumentsJobRequest, headers, runtime);
}

PHP

/**
 * 解析済みのファイルをドキュメント検索ナレッジベースに追加してインポートします。
 *
 * @param Bailian $client クライアントオブジェクト。
 * @param string $workspaceId ワークスペース ID。
 * @param string $indexId ナレッジベース ID。
 * @param string $fileId ファイル ID。
 * @param string $sourceType データの型。
 * @return SubmitIndexAddDocumentsJobResponse Alibaba Cloud Model Studio サービスからのレスポンス。
 * @throws Exception
 */
public function submitIndexAddDocumentsJob($client, $workspaceId, $indexId, $fileId, $sourceType) {
    $headers = [];
    $submitIndexAddDocumentsJobRequest = new SubmitIndexAddDocumentsJobRequest([
        "indexId" =>$indexId,
        "sourceType" => $sourceType,
        "documentIds" => [
            $fileId
        ]
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->submitIndexAddDocumentsJobWithOptions($workspaceId, $submitIndexAddDocumentsJobRequest, $headers, $runtime);
}

Node.js

/**
 * ファイルを追加するタスクを送信します。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} workspaceId - ワークスペース ID。
 * @param {string} indexId - ナレッジベース ID。
 * @param {string} fileId - ファイル ID。
 * @param {string} sourceType - データの型。
 * @returns {Promise<bailian20231229.SubmitIndexAddDocumentsJobResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
 */
async function submitIndexAddDocumentsJob(client, workspaceId, indexId, fileId, sourceType) {
    const headers = {};
    const req = new bailian20231229.SubmitIndexAddDocumentsJobRequest({
        indexId,
        documentIds: [fileId],
        sourceType,
    });
    const runtime = new Util.RuntimeOptions({});
    return await client.submitIndexAddDocumentsJobWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// 解析済みのファイルをドキュメント検索ナレッジベースに追加してインポートします。
/// </summary>
/// <param name="client">クライアント。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="indexId">ナレッジベース ID。</param>
/// <param name="fileId">ファイル ID。</param>
/// <param name="sourceType">データの型。</param>
/// <returns>Alibaba Cloud Model Studio サービスからのレスポンス。</returns>
public AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexAddDocumentsJobResponse SubmitIndexAddDocumentsJob(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string indexId,
    string fileId,
    string sourceType)
{
    var headers = new Dictionary<string, string>() { };
    var submitIndexAddDocumentsJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexAddDocumentsJobRequest
    {
        IndexId = indexId,
        DocumentIds = new List<string> { fileId },
        SourceType = sourceType
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.SubmitIndexAddDocumentsJobWithOptions(workspaceId, submitIndexAddDocumentsJobRequest, headers, runtime);
}

Go

// SubmitIndexAddDocumentsJob は、解析済みのファイルをドキュメント検索ナレッジベースに追加してインポートします。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): ナレッジベース ID。
//   - fileId(string): ファイル ID。
//   - sourceType(string): データの型。
//
// 戻り値:
//   - *bailian20231229.SubmitIndexAddDocumentsJobResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func SubmitIndexAddDocumentsJob(client *bailian20231229.Client, workspaceId, indexId, fileId, sourceType string) (_result *bailian20231229.SubmitIndexAddDocumentsJobResponse, _err error) {
	headers := make(map[string]*string)
	submitIndexAddDocumentsJobRequest := &bailian20231229.SubmitIndexAddDocumentsJobRequest{
		IndexId:     tea.String(indexId),
		SourceType:  tea.String(sourceType),
		DocumentIds: []*string{tea.String(fileId)},
	}
	runtime := &util.RuntimeOptions{}
	return client.SubmitIndexAddDocumentsJobWithOptions(tea.String(workspaceId), submitIndexAddDocumentsJobRequest, headers, runtime)
}

リクエスト例

{
  "IndexId": "mymxbdxxxx",
  "SourceType": "DATA_CENTER_FILE",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
  "DocumentIds": [
    "file_247a2fd456a349ee87d071404840109b_10xxxxxx"
  ]
}

レスポンス例

{
  "Status": "200",
  "RequestId": "F693EB60-FEFC-559A-BF56-A41F52XXXXXX",
  "Message": "success",
  "Data": {
    "Id": "d8d189a36a3248438dca23c078xxxxxx"
  },
  "Code": "Success",
  "Success": "true"
}

2.2. タスク完了の待機

インデックス作成タスクの完了には時間がかかります。ピーク時には、このプロセスに数時間かかることがあります。GetIndexJobStatus 操作を呼び出して、その実行ステータスをクエリできます。

応答の Data.Status フィールドの値が COMPLETED であることは、更新されたすべてのファイルがナレッジベースに正常に追加されたことを示します。

応答内の Documents リストには、指定した job_id に対応する追加タスク用のすべてのファイルが含まれています。

重要

Python

def get_index_job_status(client, workspace_id, index_id, job_id):
    """
    インデックス作成タスクのステータスをクエリします。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        job_id (str): タスク ID。

    Returns:
        Alibaba Cloud Model Studio サービスからのレスポンス。
    """
    headers = {}
    get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
        index_id=index_id,
        job_id=job_id
    )
    runtime = util_models.RuntimeOptions()
    return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)

Java

/**
 * インデックス作成タスクのステータスをクエリします。
 *
 * @param client      クライアント。
 * @param workspaceId ワークスペース ID。
 * @param jobId       タスク ID。
 * @param indexId     ナレッジベース ID。
 * @return Alibaba Cloud Model Studio サービスからのレスポンス。
 */
public GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest();
    getIndexJobStatusRequest.setIndexId(indexId);
    getIndexJobStatusRequest.setJobId(jobId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    GetIndexJobStatusResponse getIndexJobStatusResponse = null;
    getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
    return getIndexJobStatusResponse;
}

PHP

/**
 * インデックス作成タスクのステータスをクエリします。
 *
 * @param Bailian $client クライアント。
 * @param string $workspaceId ワークスペース ID。
 * @param string $indexId ナレッジベース ID。
 * @param string $jobId タスク ID。
 * @return GetIndexJobStatusResponse Alibaba Cloud Model Studio サービスからのレスポンス。
 */
public function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
    $headers = [];
    $getIndexJobStatusRequest = new GetIndexJobStatusRequest([
        'indexId' => $indexId,
        'jobId' => $jobId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
}

Node.js

/**
 * インデックス作成タスクのステータスをクエリします。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} workspaceId - ワークスペース ID。
 * @param {string} jobId - タスク ID。
 * @param {string} indexId - ナレッジベース ID。
 * @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
 */
static getIndexJobStatus(client, workspaceId, jobId, indexId) {
    const headers = {};
    const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId });
    const runtime = new Util.RuntimeOptions({});
    return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// インデックス作成タスクのステータスをクエリします。
/// </summary>
/// <param name="client">クライアント。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="jobId">タスク ID。</param>
/// <param name="indexId">ナレッジベース ID。</param>
/// <returns>Alibaba Cloud Model Studio サービスからのレスポンス。</returns>
/// <exception cref="Exception">呼び出し中にエラーが発生した場合に例外がスローされます。</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string jobId,
    string indexId)
{
    var headers = new Dictionary<string, string>() { };
    var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest
    {
        IndexId = indexId,
        JobId = jobId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
}

Go

// GetIndexJobStatus は、インデックス作成タスクのステータスをクエリします。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - jobId (string): タスク ID。
//   - indexId (string): ナレッジベース ID。
//
// 戻り値:
//   - *bailian20231229.GetIndexJobStatusResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) {
	headers := make(map[string]*string)
	getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{
		JobId:   tea.String(jobId),
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime)
}

リクエスト例

{
  "IndexId": "mymxbdxxxx",
  "JobId": "76f243b9ee534d59a61f156ff0xxxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "Status": 200,
  "RequestId": "7F727D58-D90E-51E7-B56E-985A42XXXXXX",
  "Message": "success",
  "Data": {
    "Status": "COMPLETED",
    "Documents": [
      {
        "Status": "FINISH",
        "DocId": "file_247a2fd456a349ee87d071404840109b_10xxxxxx",
        "Message": "インポート成功",
        "DocName": "Alibaba Cloud Model Studio スマートフォン製品紹介",
        "Code": "FINISH"
      }
    ],
    "JobId": "76f243b9ee534d59a61f156ff0xxxxxx"
  },
  "Code": "Success",
  "Success": true
}

3. 古いファイルの削除

最後に、DeleteIndexDocument 操作を呼び出して、ナレッジベースから古いバージョンのファイルを永久に削除します。これにより、古い情報が誤って取得されるのを防ぎます。

  • file_id: 古いファイルの FileId を入力します。

説明

インポートに失敗した (INSERT_ERROR) またはインポートに成功した (FINISH) ステータスのファイルのみを削除できます。ナレッジベース内のファイルのステータスをクエリするには、ListIndexDocuments 操作を呼び出すことができます。

重要

Python

def delete_index_document(client, workspace_id, index_id, file_id):
    """
    指定されたドキュメント検索ナレッジベースから 1 つ以上のファイルを永久に削除します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。
        file_id (str): ファイル ID。

    Returns:
        Alibaba Cloud Model Studio サービスからのレスポンス。
    """
    headers = {}
    delete_index_document_request = bailian_20231229_models.DeleteIndexDocumentRequest(
        index_id=index_id,
        document_ids=[file_id]
    )
    runtime = util_models.RuntimeOptions()
    return client.delete_index_document_with_options(workspace_id, delete_index_document_request, headers, runtime)

Java

/**
 * 指定されたドキュメント検索ナレッジベースから 1 つ以上のファイルを永久に削除します。
 *
 * @param client      クライアント。
 * @param workspaceId ワークスペース ID。
 * @param indexId     ナレッジベース ID。
 * @param fileId      ファイル ID。
 * @return Alibaba Cloud Model Studio サービスからのレスポンス。
 */
public DeleteIndexDocumentResponse deleteIndexDocument(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId, String fileId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    DeleteIndexDocumentRequest deleteIndexDocumentRequest = new DeleteIndexDocumentRequest();
    deleteIndexDocumentRequest.setIndexId(indexId);
    deleteIndexDocumentRequest.setDocumentIds(Collections.singletonList(fileId));
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.deleteIndexDocumentWithOptions(workspaceId, deleteIndexDocumentRequest, headers, runtime);
}

PHP

/**
 * 指定されたドキュメント検索ナレッジベースから 1 つ以上のファイルを永久に削除します。
 *
 * @param Bailian $client クライアントオブジェクト。
 * @param string $workspaceId ワークスペース ID。
 * @param string $indexId ナレッジベース ID。
 * @param string $fileId ファイル ID。
 * @return DeleteIndexDocumentResponse Alibaba Cloud Model Studio サービスからのレスポンス。
 * @throws Exception
 */
public function deleteIndexDocument($client, $workspaceId, $indexId, $fileId) {
    $headers = [];
    $deleteIndexDocumentRequest = new DeleteIndexDocumentRequest([
        "indexId" => $indexId,
        "documentIds" => [
            $fileId
        ]
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->deleteIndexDocumentWithOptions($workspaceId, $deleteIndexDocumentRequest, $headers, $runtime);
}

Node.js

/**
 * 指定されたドキュメント検索ナレッジベースから 1 つ以上のファイルを永久に削除します。
 * @param {Bailian20231229Client} client - クライアント。
 * @param {string} workspaceId - ワークスペース ID。
 * @param {string} indexId - ナレッジベース ID。
 * @param {string} fileId - ファイル ID。
 * @returns {Promise<bailian20231229.DeleteIndexDocumentResponse>} - Alibaba Cloud Model Studio サービスからのレスポンス。
 */
async function deleteIndexDocument(client, workspaceId, indexId, fileId) {
    const headers = {};
    const req = new bailian20231229.DeleteIndexDocumentRequest({
        indexId,
        documentIds: [fileId],
    });
    const runtime = new Util.RuntimeOptions({});
    return await client.deleteIndexDocumentWithOptions(workspaceId, req, headers, runtime);
}

C#

/// <summary>
/// 指定されたドキュメント検索ナレッジベースから 1 つ以上のファイルを永久に削除します。
/// </summary>
/// <param name="client">クライアント。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="indexId">ナレッジベース ID。</param>
/// <param name="fileId">ファイル ID。</param>
/// <returns>Alibaba Cloud Model Studio サービスからのレスポンス。</returns>
public AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexDocumentResponse DeleteIndexDocument(
    AlibabaCloud.SDK.Bailian20231229.Client client,
    string workspaceId,
    string indexId,
    string fileId)
{
    var headers = new Dictionary<string, string>() { };
    var deleteIndexDocumentRequest = new AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexDocumentRequest
    {
        IndexId = indexId,
        DocumentIds = new List<string> { fileId }
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.DeleteIndexDocumentWithOptions(workspaceId, deleteIndexDocumentRequest, headers, runtime);
}

Go

// DeleteIndexDocument は、指定されたドキュメント検索ナレッジベースから 1 つ以上のファイルを永久に削除します。
//
// パラメータ:
//   - client (bailian20231229.Client): クライアント。
//   - workspaceId (string): ワークスペース ID。
//   - indexId (string): ナレッジベース ID。
//   - fileId (string): ファイル ID。
//
// 戻り値:
//   - *bailian20231229.DeleteIndexDocumentResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラーメッセージ。
func DeleteIndexDocument(client *bailian20231229.Client, workspaceId, indexId, fileId string) (*bailian20231229.DeleteIndexDocumentResponse, error) {
	headers := make(map[string]*string)
	deleteIndexDocumentRequest := &bailian20231229.DeleteIndexDocumentRequest{
		IndexId:     tea.String(indexId),
		DocumentIds: []*string{tea.String(fileId)},
	}
	runtime := &util.RuntimeOptions{}
	return client.DeleteIndexDocumentWithOptions(tea.String(workspaceId), deleteIndexDocumentRequest, headers, runtime)
}

リクエスト例

{
  "DocumentIds": [
    "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
  ],
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "Status": "200",
  "RequestId": "2D8505EC-C667-5102-9154-00B6FEXXXXXX",
  "Message": "success",
  "Data": {
    "DeletedDocument": [
      "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
    ]
  },
  "Code": "Success",
  "Success": "true"
}

ナレッジベースの管理

ナレッジベースの作成と使用は API を通じてサポートされていません。これらのタスクは Model Studio コンソールで実行する必要があります。

ナレッジベースの表示

指定されたワークスペース内のナレッジベースを表示するには、ListIndices 操作を呼び出します。

重要

Python

def list_indices(client, workspace_id):
    """
    指定されたワークスペース内のナレッジベースの詳細を取得します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。

    Returns:
        Alibaba Cloud Model Studio サービスからのレスポンス。
    """
    headers = {}
    list_indices_request = bailian_20231229_models.ListIndicesRequest()
    runtime = util_models.RuntimeOptions()
    return client.list_indices_with_options(workspace_id, list_indices_request, headers, runtime)

Java

/**
 * 指定されたワークスペース内のナレッジベースの詳細を取得します。
 *
 * @param client      クライアント。
 * @param workspaceId ワークスペース ID。
 * @return Alibaba Cloud Model Studio サービスからのレスポンス。
 */
public ListIndicesResponse listIndices(com.aliyun.bailian20231229.Client client, String workspaceId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.ListIndicesRequest listIndicesRequest = new com.aliyun.bailian20231229.models.ListIndicesRequest();
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.listIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
}

PHP

/**
 * 指定されたワークスペース内のナレッジベースの詳細を取得します。
 *
 * @param Bailian $client クライアントオブジェクト。
 * @param string $workspaceId ワークスペース ID。
 * @return ListIndicesResponse Alibaba Cloud Model Studio サービスからのレスポンス。
 * @throws Exception
 */
public function listIndices($client, $workspaceId) {
    $headers = [];
    $listIndicesRequest = new ListIndicesRequest([]);
    $runtime = new RuntimeOptions([]);
    return $client->listIndicesWithOptions($workspaceId, $listIndicesRequest, $headers, $runtime);
}

Node.js

/**
 * 指定されたワークスペース内のナレッジベースの詳細を取得します。
 * @param {bailian20231229.Client} client クライアント。
 * @param {string} workspaceId ワークスペース ID。
 * @returns {Promise<bailian20231229.ListIndicesResponse>} Alibaba Cloud Model Studio サービスからのレスポンス。
 */
async function listIndices(client, workspaceId) {
    const headers = {};
    const listIndicesRequest = new bailian20231229.ListIndicesRequest();
    const runtime = new Util.RuntimeOptions({});
    return await client.listIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
}

C#

/// <summary>
/// 指定されたワークスペース内のナレッジベースの詳細を取得します。
/// </summary>
/// <param name="client">クライアント。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <returns>Alibaba Cloud Model Studio サービスからのレスポンス。</returns>
public AlibabaCloud.SDK.Bailian20231229.Models.ListIndicesResponse ListIndices(AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId)
{
    var headers = new Dictionary<string, string>() { };
    var listIndicesRequest = new Bailian20231229.Models.ListIndicesRequest();
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.ListIndicesWithOptions(workspaceId, listIndicesRequest, headers, runtime);
}

Go

// listIndices は、指定されたワークスペース内のナレッジベースの詳細を取得します。
//
// パラメータ:
//   - client      *bailian20231229.Client: クライアント。
//   - workspaceId string: ワークスペース ID。
//
// 戻り値:
//   - *bailian20231229.ListIndicesResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラー情報。
func listIndices(client *bailian20231229.Client, workspaceId string) (_result *bailian20231229.ListIndicesResponse, _err error) {
	headers := make(map[string]*string)
	listIndicesRequest := &bailian20231229.ListIndicesRequest{}
	runtime := &util.RuntimeOptions{}
	return client.ListIndicesWithOptions(tea.String(workspaceId), listIndicesRequest, headers, runtime)
}

リクエスト例

{
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "Status": "200",
  "RequestId": "5ACB2EB3-6C9A-5B0F-8E60-3FBE7EXXXXXX",
  "Message": "success",
  "Data": {
    "TotalCount": "1",
    "PageSize": "10",
    "PageNumber": "1",
    "Indices": [
      {
        "DocumentIds": [
          "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
        ],
        "Description": "",
        "OverlapSize": 100,
        "SinkInstanceId": "gp-2zegk3i6ca4xxxxxx",
        "SourceType": "DATA_CENTER_FILE",
        "RerankModelName": "gte-rerank-hybrid",
        "SinkRegion": "cn-beijing",
        "Name": "Model Studio スマートフォンナレッジベース",
        "ChunkSize": 500,
        "EmbeddingModelName": "text-embedding-v2",
        "RerankMinScore": 0.01,
        "Id": "mymxbdxxxx",
        "SinkType": "BUILT_IN",
        "Separator": " |,|,|。|?|!|\n|\\?|\\!"
      }
    ]
  },
  "Code": "Success",
  "Success": "true"
}

ナレッジベースの削除

ナレッジベースを永久に削除するには、DeleteIndex 操作を呼び出します。ナレッジベースを削除する前に、Model Studio コンソールでリンクされているすべての Alibaba Cloud Model Studio アプリケーションから関連付けを解除する必要があります。そうしないと、削除は失敗します。

注意:この操作では、カテゴリに追加したファイルは削除されません。

重要

Python

def delete_index(client, workspace_id, index_id):
    """
    指定されたナレッジベースを永久に削除します。

    Args:
        client (bailian20231229Client): クライアント。
        workspace_id (str): ワークスペース ID。
        index_id (str): ナレッジベース ID。

    Returns:
        Alibaba Cloud Model Studio サービスからのレスポンス。
    """
    headers = {}
    delete_index_request = bailian_20231229_models.DeleteIndexRequest(
        index_id=index_id
    )
    runtime = util_models.RuntimeOptions()
    return client.delete_index_with_options(workspace_id, delete_index_request, headers, runtime)

Java

/**
 * 指定されたナレッジベースを永久に削除します。
 *
 * @param client      クライアント。
 * @param workspaceId ワークスペース ID。
 * @param indexId     ナレッジベース ID。
 * @return Alibaba Cloud Model Studio サービスからのレスポンス。
 */
public DeleteIndexResponse deleteIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception {
    Map<String, String> headers = new HashMap<>();
    com.aliyun.bailian20231229.models.DeleteIndexRequest deleteIndexRequest = new com.aliyun.bailian20231229.models.DeleteIndexRequest();
    deleteIndexRequest.setIndexId(indexId);
    com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
    return client.deleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
}

PHP

/**
 * 指定されたナレッジベースを永久に削除します。
 *
 * @param Bailian $client クライアントオブジェクト。
 * @param string $workspaceId ワークスペース ID。
 * @param string $indexId ナレッジベース ID。
 * @return mixed Alibaba Cloud Model Studio サービスからのレスポンス。
 * @throws Exception
 */
public function deleteIndex($client, $workspaceId, $indexId) {
    $headers = [];
    $deleteIndexRequest = new DeleteIndexRequest([
        "indexId" => $indexId
    ]);
    $runtime = new RuntimeOptions([]);
    return $client->deleteIndexWithOptions($workspaceId, $deleteIndexRequest, $headers, $runtime);
}

Node.js

/**
 * 指定されたナレッジベースを永久に削除します。
 * @param {bailian20231229.Client} client クライアント。
 * @param {string} workspaceId ワークスペース ID。
 * @param {string} indexId ナレッジベース ID。
 * @returns {Promise<bailian20231229.DeleteIndexResponse>} Alibaba Cloud Model Studio サービスからのレスポンス。
 */
async function deleteIndex(client, workspaceId, indexId) {
    const headers = {};
    const deleteIndexRequest = new bailian20231229.DeleteIndexRequest({
        indexId
    });
    const runtime = new Util.RuntimeOptions({});
    return await client.deleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
}

C#

/// <summary>
/// 指定されたナレッジベースを永久に削除します。
/// </summary>
/// <param name="client">クライアント。</param>
/// <param name="workspaceId">ワークスペース ID。</param>
/// <param name="indexId">ナレッジベース ID。</param>
/// <returns>Alibaba Cloud Model Studio サービスからのレスポンス。</returns>
public AlibabaCloud.SDK.Bailian20231229.Models.DeleteIndexResponse DeleteIndex(AlibabaCloud.SDK.Bailian20231229.Client client, string workspaceId, string indexId)
{
    var headers = new Dictionary<string, string>() { };
    var deleteIndexRequest = new Bailian20231229.Models.DeleteIndexRequest
    {
        IndexId = indexId
    };
    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    return client.DeleteIndexWithOptions(workspaceId, deleteIndexRequest, headers, runtime);
}

Go

// deleteIndex は、指定されたナレッジベースを永久に削除します。
//
// パラメータ:
//   - client      *bailian20231229.Client: クライアント。
//   - workspaceId string: ワークスペース ID。
//   - indexId     string: ナレッジベース ID。
//
// 戻り値:
//   - *bailian20231229.DeleteIndexResponse: Alibaba Cloud Model Studio サービスからのレスポンス。
//   - error: エラー情報。
func deleteIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.DeleteIndexResponse, _err error) {
	headers := make(map[string]*string)
	deleteIndexRequest := &bailian20231229.DeleteIndexRequest{
		IndexId: tea.String(indexId),
	}
	runtime := &util.RuntimeOptions{}
	return client.DeleteIndexWithOptions(tea.String(workspaceId), deleteIndexRequest, headers, runtime)

}

リクエスト例

{
  "IndexId": "mymxbdxxxx",
  "WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}

レスポンス例

{
  "Status": "200",
  "Message": "success",
  "RequestId": "118CB681-75AA-583B-8D84-25440CXXXXXX",
  "Code": "Success",
  "Success": "true"
}

API

ナレッジベース API とそのリクエストおよびレスポンスパラメータの完全なリストについては、「API カタログ (ナレッジベース)」をご参照ください。

よくある質問

  1. ナレッジベースの更新と同期を自動化するにはどうすればよいですか?

    ドキュメント検索

    Object Storage Service (OSS)、Function Compute (FC)、および Model Studio ナレッジベースの API を統合します。以下の手順に従ってください:

    1. バケットの作成: OSS コンソールに移動して、ソースファイルを保存するための OSS バケットを作成します。

    2. ナレッジベースの作成: プライベートな知識コンテンツを保存するために、ドキュメント検索ナレッジベースを作成します。

    3. カスタム関数の作成: FC コンソールに移動し、追加や削除などのファイル変更イベント用の関数を作成します。「関数の作成」をご参照ください。これらの関数は、「ナレッジベースの更新」で説明されている関連 API を呼び出すことにより、OSS からナレッジベースへのファイル変更を同期します。

    4. OSS トリガーの作成: FC で、前のステップで作成したカスタム関数に OSS トリガーを関連付けます。OSS への新しいファイルのアップロードなど、ファイルの変更イベントが検出されると、トリガーがアクティブになり、FC が関数を実行します。「トリガー」をご参照ください。

    データクエリと画像 Q&A

    サポートされていません。

  1. 新しいナレッジベースが空なのはなぜですか?

    これは通常、インデックスジョブの送信ステップが失敗した場合に発生します。CreateIndex API を呼び出しても SubmitIndexJob API の呼び出しが失敗すると、ナレッジベースは空になります。これを解決するには、再度インデックスジョブを送信し、インデックスジョブが完了するのを待ってください。

  1. 「アップロードしたファイルへのアクセスに失敗しました。アップロード操作が成功したか確認してください」というエラーが表示された場合はどうすればよいですか?

    このエラーは通常、ファイルを一時ストレージにアップロードするステップが正常に実行されなかったために発生します。AddFile API 操作を呼び出す前に、このステップが正常に実行されることを確認してください。

  1. 「アクセスが拒否されました:このワークスペースへのアクセス権がないか、ワークスペースが存在しません」というエラーが表示された場合はどうすればよいですか?

    このエラーは通常、以下の理由で発生します:

    • リクエストされたサービスエンドポイント (サービスエンドポイント) が正しくありません: インターネット経由でアクセスする場合、中国サイト (パブリッククラウド) のユーザーは中国 (北京) のサービスエンドポイントを使用し、国際サイトのユーザーはシンガポールのサービスエンドポイントを使用する必要があります。オンラインデバッグ機能を使用している場合は、次の図に示すように、正しいサービスエンドポイントを選択していることを確認してください。

      image

    • WorkspaceId の値が正しくない、またはワークスペースのメンバーではない場合: API を呼び出す前に、WorkspaceId が正しいこと、およびワークスペースのメンバーであることを確認してください。指定されたワークスペースへのメンバーの追加方法

  1. 「指定されたアクセスキーが見つからないか、無効です」というエラーが表示された場合はどうすればよいですか?

    このエラーは通常、指定された access_key_id または access_key_secret が正しくない場合、あるいは access_key_id無効化されている 場合に発生します。 API を呼び出す前に、access_key_id が正しく、無効化されていないことを確認してください。

  1. 「カテゴリが一致しません」というエラーが表示された場合はどうすればよいですか?

    このエラーは、ApplyFileUploadLease API 呼び出しで使用される CategoryId が、後続の AddFile API 呼び出しで渡される CategoryId と異なる場合に一般的に発生します。

    ApplyFileUploadLease から AddFile までのファイルアップロードフロー全体を通して、必ず同じ CategoryId を使用してください。ListCategory API を呼び出して現在のワークスペースにあるカテゴリのリストを取得し、使用している CategoryId が正しいことを確認できます。

課金

  • すべてのナレッジベース機能と API 呼び出しは無料です。「ナレッジベース:課金」をご参照ください。

  • Model Studio にインポートされたファイルなどのデータのストレージスペースは無料です。

エラーコード

このトピックで説明されている API 操作の呼び出しが失敗した場合は、エラーセンターをご参照ください。