1. クライアントの初期化ファイルをアップロードしてナレッジベースを作成する前に、クライアントを初期化する必要があります。設定済みの AccessKey と AccessKey シークレットを使用して ID 検証を完了し、endpoint を設定します。 パブリックエンドポイント: クライアントがインターネットにアクセスできることを確認してください。 VPC エンドポイント: クライアントがシンガポール ap-southeast-1VPC
クライアントが作成されると、後続の API 呼び出し用の Client オブジェクトが取得されます。 | Pythondef 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 はクライアントを作成して設定します。
//
// Returns:
// - *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 と入力します。Alibaba Cloud Model Studio は、カテゴリを使用してアップロードされたファイルを管理します。システムは自動的にデフォルトのカテゴリを作成します。また、AddCategory 操作を呼び出して新しいカテゴリを作成し、対応する category_id を取得することもできます。 file_name: アップロードするファイルの名前を拡張子を含めて入力します。値は実際のファイル名と同じでなければなりません。 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 = "これをアップロードするファイルの実際のローカルパス (例: /xxx/xxx/xxx/Bailian_Phones_Specifications.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 = "これをアップロードするファイルの実際のローカルパス (例: /xxx/xxx/xxx/Bailian_Phones_Specifications.docx) に置き換えます"
file_size = get_file_size(file_path)
print(f"ファイルのサイズ (バイト単位) は: {file_size}")
コード内の file_path 変数をファイルの実際のローカルパスに置き換えてコードを実行します。これにより、オブジェクトファイルのサイズをバイト単位で取得できます。次の値は一例です。 ファイルのサイズ (バイト単位) は: 14015
一時的なアップロードリースを正常にリクエストすると、以下を取得します: これらは次のステップで使用します。 | Pythondef 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 にファイルアップロードリースをリクエストします。
//
// Args:
// - client (bailian20231229.Client): クライアント。
// - categoryId (string): カテゴリ ID。
// - fileName (string): ファイル名。
// - fileMD5 (string): ファイルの MD5 ハッシュ。
// - fileSize (string): ファイルサイズ (バイト単位)。
// - workspaceId (string): ワークスペース ID。
//
// Returns:
// - *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": "Bailian_Phones_Specifications.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 サーバーにアップロードします。ファイルはローカルストレージまたはパブリック URL からアップロードできます。各ワークスペースは最大 10,000 個のファイルをサポートします。サポートされているファイル形式は、PDF、DOCX、DOC、TXT、Markdown、PPTX、PPT、XLSX、XLS、HTML、PNG、JPG、JPEG、BMP、および GIF です。 |
重要 この操作は、オンラインデバッグやサンプルコードの生成をサポートしていません。 ローカルストレージからのアップロードPythonimport 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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。"
}
# ファイルを読み取ってアップロードします。
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 の場合 /xxx/xxx/Bailian_Phones_Specifications.docx) に置き換えます。"
upload_file(pre_signed_url_or_http_url, file_path)
Javaimport 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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。");
// ファイルを読み取り、接続を介してアップロードします。
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 の場合 /xxx/xxx/Bailian_Phones_Specifications.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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。"
];
// ローカルファイルを一時ストレージにアップロードします。
$filePath = "これを、アップロードするファイルの実際のローカルパス (例: Linux の場合 /xxx/xxx/Bailian_Phones_Specifications.docx) に置き換えます。";
try {
uploadFile($preSignedUrl, $headers, $filePath);
} catch (Exception $e) {
echo "エラー: " . $e->getMessage() . "\n";
}
}
// メイン関数を呼び出します。
main();
?>
Node.jsconst 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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。"
};
// ローカルファイルを一時ストレージにアップロードします。
const filePath = "これを、アップロードするファイルの実際のローカルパス (例: Linux の場合 /xxx/xxx/Bailian_Phones_Specifications.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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。";
// ファイルを読み取り、接続を介してアップロードします。
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 の場合 /xxx/xxx/Bailian_Phones_Specifications.docx) に置き換えます。";
UploadFile(preSignedUrlOrHttpUrl, filePath);
}
}
Gopackage main
import (
"fmt"
"io"
"os"
"github.com/go-resty/resty/v2"
)
// UploadFile はローカルファイルを一時ストレージにアップロードします。
//
// Args:
// - preSignedUrl (string): アップロードリースからの URL。
// - headers (map[string]string): アップロードリクエストのヘッダー。
// - filePath (string): ファイルのローカルパス。
//
// Returns:
// - 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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。",
}
// ローカルファイルを一時ストレージにアップロードします。
filePath := "これを、アップロードするファイルの実際のローカルパス (例: Linux の場合 /xxx/xxx/Bailian_Phones_Specifications.docx) に置き換えます。"
// アップロード関数を呼び出します。
err := UploadFile(preSignedUrl, headers, filePath)
if err != nil {
fmt.Printf("アップロードに失敗しました: %v\n", err)
}
}
URL からのアップロードURL が公開アクセス可能で、有効なファイルを指していることを確認してください。 Pythonimport 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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。"
}
# ファイル 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)
Javaimport 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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。");
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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。"
];
$sourceUrl = "これを、アップロードするファイルの URL に置き換えます。";
try {
uploadFile($preSignedUrl, $headers, $sourceUrl);
} catch (Exception $e) {
echo "エラー: " . $e->getMessage() . "\n";
}
}
// メイン関数を呼び出します。
main();
?>
Node.jsconst 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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。"
};
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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。";
// リクエストストリームを取得し、それにファイルストリームを書き込みます。
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);
}
}
Gopackage main
import (
"fmt"
"net/http"
"github.com/go-resty/resty/v2"
)
// UploadFileFromUrl はパブリック URL から一時ストレージにファイルをアップロードします。
//
// Args:
// - preSignedUrl (string): アップロードリースからの URL。
// - headers (map[string]string): アップロードリクエストのヘッダー。
// - sourceUrl (string): ファイルの URL。
//
// Returns:
// - 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 フィールドの値に置き換えます。空の値が返された場合は、空の値を渡します。",
}
sourceUrl := "これを、アップロードするファイルの URL に置き換えます。"
// アップロード関数を呼び出します。
err := UploadFileFromUrl(preSignedUrl, headers, sourceUrl)
if err != nil {
fmt.Printf("アップロードに失敗しました: %v\n", err)
}
}
|
2.3. ファイルをカテゴリに追加するAlibaba Cloud Model Studio は、カテゴリを使用してアップロードされたファイルを管理します。したがって、AddFile 操作を呼び出して、アップロードされたファイルを同じワークスペースのカテゴリに追加する必要があります。 parser: DASHSCOPE_DOCMIND と入力します。 lease_id: ファイルアップロードリースのリクエストによって返された Data.FileUploadLeaseId を入力します。 category_id: この例では、default と入力します。ファイルをカスタムカテゴリにアップロードした場合は、対応する category_id を入力します。
ファイルが追加されると、Model Studio はファイルの FileId を返し、自動的に解析を開始します。lease_id は無効になります。同じリース ID を使用してリクエストを再度送信しないでください。 | Pythondef 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 の指定されたカテゴリにファイルを追加します。
//
// Args:
// - client (bailian20231229.Client): クライアント。
// - leaseId (string): リース ID。
// - parser (string): ファイルのパーサ。
// - categoryId (string): カテゴリ ID。
// - workspaceId (string): ワークスペース ID。
//
// Returns:
// - *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 の場合、ファイルは解析されています。その後、ナレッジベースにインポートできます。 | Pythondef 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 はファイルに関する基本情報を取得します。
//
// Args:
// - client (bailian20231229.Client): クライアント。
// - workspaceId (string): ワークスペース ID。
// - fileId (string): ファイル ID。
//
// Returns:
// - any: 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": "Bailian_Phones_Specifications.docx",
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"SizeInBytes": "14015",
"Parser": "DASHSCOPE_DOCMIND"
},
"Code": "Success",
"Success": "true"
}
|
3. ナレッジベースの作成 |
3.1. ナレッジベースの初期化ファイルが解析された後、同じワークスペースのナレッジベースにインポートできます。ドキュメント検索ナレッジベースを初期化するには、CreateIndex 操作を呼び出します。これにより送信が確定するわけではありません。 workspace_id: 詳細については、「ワークスペース ID の取得方法」をご参照ください。 file_id: ファイルをカテゴリに追加したときに返された FileId を入力します。 `source_type` が DATA_CENTER_FILE に設定されている場合、このパラメーターは必須です。そうでない場合、エラーが報告されます。 structure_type: この例では、unstructured と入力します。 API を使用してデータクエリまたは画像 Q&A ペアナレッジベースを作成することはできません。Model Studio コンソールを使用して作成する必要があります。 source_type: この例では、DATA_CENTER_FILE と入力します。 sink_type: この例では、BUILT_IN と入力します。
応答の Data.Id フィールドの値はナレッジベース ID です。この ID は、後続のインデックス構築に使用されます。 ナレッジベース ID は安全に保管してください。このナレッジベースに関連する後続のすべての API 操作で必要になります。 | Pythondef 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 でナレッジベースを作成 (初期化) します。
//
// Args:
// - client (bailian20231229.Client): クライアント。
// - workspaceId (string): ワークスペース ID。
// - fileId (string): ファイル ID。
// - name (string): ナレッジベースの名前。
// - structureType (string): ナレッジベースのデータの型。
// - sourceType (string): アプリケーションデータのデータの型。カテゴリとファイルタイプがサポートされています。
// - sinkType (string): ナレッジベースのベクターストレージタイプ。
//
// Returns:
// - *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": "Model Studio Phone Knowledge Base",
"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 操作を呼び出してインデックスジョブを送信する必要があります。これにより、ナレッジベースのインデックス構築が開始されます。 ジョブを送信すると、Alibaba Cloud Model Studio は非同期タスクとしてインデックスの構築を開始します。この操作によって返される Data.Id は、対応するジョブ ID です。次のステップでは、この ID を使用してジョブの最新のステータスをクエリします。 | Pythondef 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 はインデックスジョブを送信します。
//
// Args:
// - client (bailian20231229.Client): クライアント。
// - workspaceId (string): ワークスペース ID。
// - indexId (string): ナレッジベース ID。
//
// Returns:
// - *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 の場合、ナレッジベースが作成されます。 | Pythondef 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 はインデックスジョブのステータスをクエリします。
//
// Args:
// - client (bailian20231229.Client): クライアント。
// - workspaceId (string): ワークスペース ID。
// - jobId (string): ジョブ ID。
// - indexId (string): ナレッジベース ID。
//
// Returns:
// - *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": "Bailian Phones Specifications",
"Code": "FINISH"
}
],
"JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
},
"Code": "Success",
"Success": "true"
}
|