本篇文檔介紹如何使用SDK進行測試問答。
配置環境變數
配置環境變數ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET。
阿里雲帳號AccessKey擁有所有API的存取權限,建議您使用RAM使用者進行API訪問或日常營運,具體操作,請參見建立RAM使用者。
建立AccessKey ID和AccessKey Secret,請參考建立AccessKey。
如果您使用的是RAM使用者的AccessKey,請確保主帳號已授權AliyunServiceRoleForOpenSearch服務關聯角色,請參考OpenSearch-行業演算法版服務關聯角色,相關文檔參考訪問鑒權規則。
請不要將AccessKey ID和AccessKey Secret儲存到工程代碼裡,否則可能導致AccessKey泄露,威脅您帳號下所有資源的安全。
Linux和macOS系統配置方法:
執行以下命令,其中,
<access_key_id>
需替換為您RAM使用者的AccessKey ID,<access_key_secret>
替換為您RAM使用者的AccessKey Secret。export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
Windows系統配置方法
建立環境變數檔案,添加環境變數ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET,並寫入已準備好的AccessKey ID和AccessKey Secret。
重啟Windows系統生效。
相關依賴
使用SDK上傳檔案所需依賴如下。
<dependency>
<groupId>com.aliyun.opensearch</groupId>
<artifactId>aliyun-sdk-opensearch</artifactId>
<version>6.0.0</version>
</dependency>
pip install alibabacloud_tea_util
pip install alibabacloud_opensearch_util
pip install alibabacloud_credentials
V3.4.1 (2021-05-11)
下載地址: https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20230719/mxik/opensearch-sdk-php-release-v3.4.1.zip
Search Demo 範例代碼
BaseRequest參考:Python client 樣本
package com.aliyun.opensearch;
import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchResult;
import java.util.HashMap;
import java.util.Map;
public class LLMSearch {
private static String appName = "替換為應用程式名稱";
private static String host = "替換應用的API訪問地址";
private static String path = "/apps/AppName/actions/knowledge-search";
public static void main(String[] args) {
//使用者識別資訊
//從環境變數讀取配置的AccessKey ID和AccessKey Secret,運行程式碼範例前必須先配置環境變數
String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
//ApiReadTimeOut
OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
openSearch.setTimeout(90000);
OpenSearchClient openSearchClient = new OpenSearchClient(openSearch);
Map<String, String> params = new HashMap<String, String>() {{
put("format", "full_json");
put("_POST_BODY", "{\"question\":{\"text\":\"怎麼充電\",\"type\":\"TEXT\",\"session\":\"\"},\"options\":{\"retrieve\":{\"doc\":{\"filter\":\"\",\"top_n\":5,\"sf\":\"\",\"dense_weight\":\"0.7\",\"formula\":\"\",\"operator\":\"AND\"},\"entry\":{\"sf\":\"\"},\"image\":{\"sf\":\"\",\"dense_weight\":\"0.7\"},\"qp\":{\"query_extend\":false,\"query_extend_num\":5},\"return_hits\":false,\"rerank\":{\"enable\":true,\"model\":\"ops-bge-reranker-larger\"}},\"chat\":{\"stream\":true,\"prompt_config\":{\"attitude\":\"normal\",\"rule\":\"detailed\",\"noanswer\":\"sorry\",\"language\":\"Chinese\",\"role\":false,\"role_name\":\"AI小助手\",\"out_format\":\"text\"},\"agent\":{\"tools\":[]},\"csi_level\":\"strict\",\"history_max\":\"\",\"link\":\"false\",\"model\":\"qwen-plus\",\"model_generation\":\"\"}}}");
}};
try {
OpenSearchResult openSearchResult = openSearchClient
.callAndDecodeResult(path, params, "POST");
System.out.println("RequestID=" + openSearchResult.getTraceInfo().getRequestId());
System.out.println(openSearchResult.getResult());
} catch (
OpenSearchException e) {
System.out.println("RequestID=" + e.getRequestId());
System.out.println("ErrorCode=" + e.getCode());
System.out.println("ErrorMessage=" + e.getMessage());
} catch (
OpenSearchClientException e) {
System.out.println("ErrorMessage=" + e.getMessage());
}
}
}
# -*- coding: utf-8 -*-
import time, os
from typing import Dict, Any
from Tea.exceptions import TeaException
from Tea.request import TeaRequest
from alibabacloud_tea_util import models as util_models
from BaseRequest import Config, Client
class LLMSearch:
def __init__(self, config: Config):
self.Clients = Client(config=config)
self.runtime = util_models.RuntimeOptions(
connect_timeout=10000,
read_timeout=90000,
autoretry=False,
ignore_ssl=False,
max_idle_conns=50,
max_attempts=3
)
self.header = {}
def searchDoc(self, app_name: str,body:Dict, query_params: dict={}) -> Dict[str, Any]:
try:
response = self.Clients._request(method="POST", pathname=f'/v3/openapi/apps/{app_name}/actions/knowledge-search',
query=query_params, headers=self.header, body=body, runtime=self.runtime)
return response
except TeaException as e:
print(e)
if __name__ == "__main__":
# 配置統一的請求入口和 需要去掉http://
endpoint = "<endpoint>"
# 支援 protocol 配置 HTTPS/HTTP
endpoint_protocol = "HTTP"
# 使用者識別資訊
# 從環境變數讀取配置的AccessKey ID和AccessKey Secret,
# 運行程式碼範例前必須先配置環境變數,參考文檔上面“配置環境變數”步驟
access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID")
access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
# 支援 type 配置 sts/access_key 鑒權. 其中 type 預設為 access_key 鑒權. 使用 sts 可配置 RAM-STS 鑒權.
# 備選參數為: sts 或者 access_key
auth_type = "access_key"
# 如果使用 RAM-STS 鑒權, 請配置 security_token, 可使用 阿里雲 AssumeRole 擷取 相關 STS 鑒權結構.
security_token = "<security_token>"
# 配置請求使用的通用資訊.
# type和security_token 參數如果不是子帳號,需要省略
Configs = Config(endpoint=endpoint, access_key_id=access_key_id, access_key_secret=access_key_secret,
security_token=security_token, type=auth_type, protocol=endpoint_protocol)
# 建立 opensearch 執行個體
# 請將<應用程式名稱>替換為您建立的智能問答版執行個體名稱
ops = LLMSearch(Configs)
app_name = "<應用程式名稱>"
# --------------- 文檔搜尋 ---------------
docQuery = {"question": {"text": "搜尋", "type": "TEXT"}}
res1 = ops.searchDoc(app_name=app_name, body=docQuery)
print(res1)
<?php
require_once($path . "/OpenSearch/Autoloader/Autoloader.php");
use OpenSearch\Client\OpenSearchClient;
// 使用者識別資訊
// 從環境變數讀取配置的AccessKey ID和AccessKey Secret,
// 運行程式碼範例前必須先配置環境變數,參考文檔上面“配置環境變數”步驟
// 替換對應的access key id
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
//替換對應的access secret
$secret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$endPoint = '<替換為 endpoint>';
$appName = '<替換為 應用程式名稱>';
$options = array('timeout' => 90);
$requestBody = "{\"question\":{\"text\":\"根據對各種類型典型網站的調研\",\"type\":\"TEXT\"}}";
$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);
$uri = "/apps/{$appName}/actions/knowledge-search";
try{
$ret = $client->post($uri, $requestBody);
print_r(json_decode($ret->result, true));
}catch (\Throwable $e) {
print_r($e);
}
POST_BODY內的其他參數可參考:SearchKnowledge-文本問答
Java SDK 流式輸出範例程式碼
請求樣本
通過AccessKey方式
說明以下樣本需要Java SDK版本不低於6.0.0。
package org.example; import com.aliyun.opensearch.OpenSearchClient; import com.aliyun.opensearch.sdk.dependencies.org.apache.http.HttpResponse; import com.aliyun.opensearch.sdk.generated.OpenSearch; import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class Main { private static String host = "替換為訪問地址"; public static void main(String[] args) { //從環境變數讀取配置的AccessKey ID和AccessKey Secret,運行程式碼範例前必須先配置環境變數 String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); OpenSearch openSearch = new OpenSearch(accesskey, secret, host); openSearch.setTimeout(90000); OpenSearchClient openSearchClient = new OpenSearchClient(openSearch); Map<String, String> params = new HashMap<String, String>() {{ put("_POST_BODY", "{\"question\": {\"text\": \"北京\",\"type\": \"TEXT\"},\"options\": {\"chat\": {\"stream\": true}}}"); }}; String path = "/apps/AppName/actions/knowledge-search"; try { HttpResponse httpResponse = openSearchClient .callForHttpResponse(path, params, "POST"); InputStream responseBodyStream = httpResponse.getEntity().getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); // 請求成功 openSearchClient.getHttpClientManager().getClientTracer().success(httpResponse, ""); } catch (OpenSearchClientException e) { System.out.println("ErrorMessage=" + e.getMessage()); } catch (IOException e) { throw new RuntimeException(e); } } }
通過API Key方式
說明通過API Key方式訪問,Java SDK版本不低於6.0.2。
package org.example; import com.aliyun.opensearch.OpenSearchClient; import com.aliyun.opensearch.sdk.dependencies.org.apache.http.HttpResponse; import com.aliyun.opensearch.sdk.generated.OpenSearch; import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class Main { private static String host = "替換為訪問地址"; public static void main(String[] args) { //通過API Key訪問,sdk版本不低於6.0.2 OpenSearch openSearch = new OpenSearch(); openSearch.setBearerToken("OS-xxxx"); openSearch.setHost(host); openSearch.setTimeout(90000); OpenSearchClient openSearchClient = new OpenSearchClient(openSearch); Map<String, String> params = new HashMap<String, String>() {{ put("_POST_BODY", "{\"question\": {\"text\": \"北京\",\"type\": \"TEXT\"},\"options\": {\"chat\": {\"stream\": true}}}"); }}; String path = "/apps/AppName/actions/knowledge-search"; try { HttpResponse httpResponse = openSearchClient .callForHttpResponse(path, params, "POST"); InputStream responseBodyStream = httpResponse.getEntity().getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); // 請求成功 openSearchClient.getHttpClientManager().getClientTracer().success(httpResponse, ""); } catch (OpenSearchClientException e) { System.out.println("ErrorMessage=" + e.getMessage()); } catch (IOException e) { throw new RuntimeException(e); } } }
輸出樣本
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":391.178295,"result":{"data":[{"answer":"北京","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":409.279769,"result":{"data":[{"answer":"北京是中國","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":429.260018,"result":{"data":[{"answer":"北京是中國的","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":447.107968,"result":{"data":[{"answer":"北京是中國的首都","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":465.897194,"result":{"data":[{"answer":"北京是中國的首都,","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":485.54058,"result":{"data":[{"answer":"北京是中國的首都,具有","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":504.273681,"result":{"data":[{"answer":"北京是中國的首都,具有悠久","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":523.287943,"result":{"data":[{"answer":"北京是中國的首都,具有悠久的歷史","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":542.027658,"result":{"data":[{"answer":"北京是中國的首都,具有悠久的歷史。","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":559.790625,"result":{"data":[{"answer":"北京是中國的首都,具有悠久的歷史。","type":"TEXT"}]}}
data:{"request_id":"AF429C69-2D36-4328-A9BA-5ECDEC716176","status":"OK","latency":689.980221,"result":{"data":[{"answer":"北京是中國的首都,具有悠久的歷史。","type":"TEXT","reference":[{"tokenNum":12,"id":"6004483b75f98deb48198e3543a90c0c","title":"北京.txt"},{"tokenNum":607,"id":"770f7cb52fec7afb1be65d637063a8cb","title":"領航新中國,奮進新時代.docx"}]}]}}
data:[done]