日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

搜索Demo

本篇文檔介紹如何使用SDK進行測試問答。

配置環境變量

配置環境變量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET

重要
  • 阿里云賬號AccessKey擁有所有API的訪問權限,建議您使用RAM用戶進行API訪問或日常運維,具體操作,請參見創建RAM用戶

  • 創建AccessKey ID和AccessKey Secret,請參考創建AccessKey

  • 如果您使用的是RAM用戶的AccessKey,請確保主賬號已授權AliyunServiceRoleForOpenSearch服務關聯角色,請參考OpenSearch-行業算法版服務關聯角色,相關文檔參考訪問鑒權規則

  • 請不要將AccessKey ID和AccessKey Secret保存到工程代碼里,否則可能導致AccessKey泄露,威脅您賬號下所有資源的安全。

  • LinuxmacOS系統配置方法:

    執行以下命令,其中, <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系統配置方法

    1. 新建環境變量文件,添加環境變量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET,并寫入已準備好的AccessKey ID和AccessKey Secret。

    2. 重啟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]