文档

文本向量化及切片向量化

更新时间:

配置环境变量

配置环境变量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>4.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

EmbeddingDoc 样例代码

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 = "AppName";
    private static String host = "替换应用的API访问地址";
    private static String path = "/apps/AppName/actions/knowledge-embedding";

    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(62000);

        OpenSearchClient openSearchClient = new OpenSearchClient(openSearch);

        Map<String, String> params = new HashMap<String, String>() {{
            put("format", "full_json");
            put("_POST_BODY", "{\"content\":\"测试文本\",\"query\":false}");
        }};
      	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=10000,
            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-embedding',
                                             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 = "替换为应用id"

    # --------------- 文档搜索 ---------------

    docQuery = {"content":"测试文本","query":false}

    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('debug' => true);
$requestBody = "{"content":"测试文本","query":false}";

$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);

$uri = "/apps/{$appName}/actions/knowledge-embedding";

try{
    $ret = $client->post($uri, $requestBody);
    print_r(json_decode($ret->result, true));
}catch (\Throwable $e) {
    print_r($e);
}

SplitDoc样例代码

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 = "AppName";
    private static String host = "替换应用的API访问地址";
    private static String path = "/apps/AppName/actions/knowledge-split";

    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(62000);

        OpenSearchClient openSearchClient = new OpenSearchClient(openSearch);

        Map<String, String> params = new HashMap<String, String>() {{
            put("format", "full_json");
            put("_POST_BODY", "{"title":"测试标题","content":"测试文本","use_embedding":true}");
        }};
      	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=10000,
            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-split',
                                             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 = "替换为应用id"

    # --------------- 文档搜索 ---------------

    docQuery = {"title":"测试标题","content":"测试文本","use_embedding":true}

    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('debug' => true);
$requestBody = "{"title":"测试标题","content":"测试文本","use_embedding":true}";

$client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);

$uri = "/apps/{$appName}/actions/knowledge-split";

try{
    $ret = $client->post($uri, $requestBody);
    print_r(json_decode($ret->result, true));
}catch (\Throwable $e) {
    print_r($e);
}
  • 本页导读 (0)