You need to enable JavaScript to run this app.
导航
对接指南
最近更新时间:2024.08.12 11:08:14首次发布时间:2024.04.17 14:21:06

火山引擎向量数据库 Viking DB 支持通过 API 接口进行向量数据库操作,在使用 API 接口之前,需要先完成以下操作。

前提条件

已通过 注册账号及开通服务 页面操作完成注册账号及开通服务。

AK/SK 密钥获取

在调用火山引擎向量数据库 VikingDB 的各个能力之前,确保您已生成访问密钥 Access Key。Access Key 包括 Access Key ID(简称为 AK) 和 Access Key Secret(简称为 SK),其中,Access Key ID 用于标识用户,Access Key Secret 用于验证用户的密钥,请您妥善保管。
AK/SK 密钥获取方式如下,更多详情请参考 Access Key(密钥)管理

  1. 单击右上角账号名下拉框中的【密钥管理】进入对应页面。
  2. 单击【新建密钥】按钮,可获取 AK/SK,可以此为凭证调用上述已接入应用的接口。

图片

注意

安全起见,建议新建子账户,并使用子账户的 AK/SK。

获取签名

获取到 AK/SK 后,生成签名。签名过程说明详情请参考 签名过程Demo,通过源码生成签名详情请参考 签名源码示例,通过 SDK 生成签名详情请参考 SDK概览

Python 语言 SDK 生成签名

  1. 安装火山引擎程序包。

    pip install volcengine

  2. 生成签名。

    # volc_auth.py
    
    import json
    import sys
    
    from volcengine.auth.SignerV4 import SignerV4
    from volcengine.base.Request import Request
    from volcengine.Credentials import Credentials
    
    
    def prepare_request(method, path, ak, sk, params=None, data=None, doseq=0):
        if params:
            for key in params:
                if (
                    type(params[key]) == int
                    or type(params[key]) == float
                    or type(params[key]) == bool
                ):
                    params[key] = str(params[key])
                elif sys.version_info[0] != 3:
                    if type(params[key]) == unicode:
                        params[key] = params[key].encode("utf-8")
                elif type(params[key]) == list:
                    if not doseq:
                        params[key] = ",".join(params[key])
        r = Request()
        r.set_shema("https")
        r.set_method(method)
        r.set_connection_timeout(10)
        r.set_socket_timeout(10)
        mheaders = {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Host": "api-vikingdb.volces.com",
        }
        r.set_headers(mheaders)
        if params:
            r.set_query(params)
        r.set_host("api-vikingdb.volces.com")
        r.set_path(path)
        if data is not None:
            r.set_body(json.dumps(data))
        # 生成签名
        credentials = Credentials(ak, sk, "air", "cn-north-1")
        SignerV4.sign(r, credentials)
        return r
    

GO 语言 SDK 生成签名

  1. 安装火山引擎程序包。

    go get -u github.com/volcengine/volc-sdk-golang

  2. 生成签名。

    package main
    
    import (
            "bytes"
            "fmt"
            "net/http"
            "net/url"
            "strings"
            "io/ioutil"
            "github.com/volcengine/volc-sdk-golang/base"
    )
    
    const (
            testAk = "***"
            testSk = "***"
    )
    
    func PrepareRequest(method string, path string, ak string, sk string, query url.Values, body []byte) *http.Request {
            u := url.URL{
                    Scheme:   "https",
                    Host:     "api-vikingdb.volces.com",
                    Path:     path,
            }
            if query != nil {
                    u.RawQuery = query.Encode()
            }
            req, _ := http.NewRequest(strings.ToUpper(method), u.String(), bytes.NewReader(body))
            req.Header.Add("Accept", "application/json")
            req.Header.Add("Content-Type", "application/json")
            req.Header.Add("Host", "api-vikingdb.volces.com")
            credential := base.Credentials{
                    AccessKeyID:     ak,
                    SecretAccessKey: sk,
                    Service:         "air",
                    Region:          "cn-north-1",
            }
            req = credential.Sign(req)
            return req
    }
    
    func main() {
            body := []byte(`{"collection_name":"test_no_vector_collection"}`)
            req := PrepareRequest("GET", "/api/collection/info", testAk, testSk, nil, body)
            fmt.Printf("%+v\n", req)
            // 发送请求
            client := &http.Client{}
            resp, err := client.Do(req)
            if err != nil {
                    fmt.Println("Error sending request:", err)
                    return
            }
            defer resp.Body.Close()
    
            rb, _ := ioutil.ReadAll(resp.Body)
            fmt.Println(string(rb))
    }
    

Java语言 SDK 生成签名

  1. 安装火山引擎程序包。

    <dependency>
        <groupId>com.volcengine</groupId>
        <artifactId>volc-sdk-java</artifactId>
        <version>最新版本</version>
    </dependency> 
    
  2. 生成签名

    package javaTest;
    
    import java.util.List;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    import com.volcengine.auth.ISignerV4;
    import com.volcengine.auth.impl.SignerV4Impl;
    import com.volcengine.model.Credentials;
    import com.volcengine.service.SignableRequest;
    
    public class sign {
      public static SignableRequest prepareRequest(String host, String path, String method, List<NameValuePair> params, String body, String ak, String sk) throws Exception {
        SignableRequest request = new SignableRequest();
        request.setMethod(method);
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Host", host);
        request.setEntity(new StringEntity(body, "utf-8"));
    
        URIBuilder builder = request.getUriBuilder();
        builder.setScheme("https");
        builder.setHost(host);
        builder.setPath(path);
        if (params != null) {
          builder.setParameters(params);
        }
    
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(2000).build();
        request.setConfig(requestConfig);
    
        Credentials credentials = new Credentials("cn-north-1", "air");
        credentials.setAccessKeyID(ak);
        credentials.setSecretAccessKey(sk);
    
        // 签名
        ISignerV4 ISigner = new SignerV4Impl();
        ISigner.sign(request, credentials);
    
        return request;
      }
    
      public static void main(String[] args) throws Exception {
        String host = "viking-knowledge-demo.byte-test.com";
        String path = "api/doc_chunking";
        String method = "POST";
        String body = "{\"doc_infos\":[{\"doc_type\":\"pdf\",\"url\":\"https://viking-db-tos.tos-cn-beijing.volces.com/tce_test/%E6%B5%8B%E8%AF%95%E9%A3%9E%E4%B9%A6%E6%96%87%E6%A1%A3%E8%A7%A3%E6%9E%90%E6%95%88%E6%9E%9C/%E6%8E%A8%E8%8D%90%E5%B9%B3%E5%8F%B0%E5%AF%B9%E5%A4%96%E4%BB%8B%E7%BB%8Dppt%20V13.pdf?X-Tos-Algorithm=TOS4-HMAC-SHA256&X-Tos-Content-Sha256=UNSIGNED-PAYLOAD&X-Tos-Credential=AKTP0W2SmSuRexHHSwaMbazu80C2FjsFuuVEdFKlJMuuDV%2F20231207%2Fcn-beijing%2Ftos%2Frequest&X-Tos-Date=20231207T114453Z&X-Tos-Expires=3600&X-Tos-SignedHeaders=host&X-Tos-Security-Token=nCgdqdEROend3.ChsKBzNzX056d3cSECLUlSIF60Axnogurjf9sCUQmeDGqwYYqfzGqwYg_4zM6QcoAjC1wZsJQgN0b3NSGGRvbmdqaW5rdWlAYnl0ZWRhbmNlLmNvbVgEYAE.A9iq1xqYbpibvLJoOYjpMz6Tz7GUuaL1A_BY1MWhAAJTMVy7qk-rIA5SvJqbCWsFTz5hkDjaaegVIg0botVPaQ&X-Tos-Signature=ca0dbe8bcbc73e1cc120125a19b384da20ae6e0b2c67ac878757e94f8a7969a2\"}]}";
        String ak = "your_ak_on_volcengine";
        String sk = "your_sk_on_volcengine";
        SignableRequest request = prepareRequest(host, path, method, null, body, ak, sk);
        System.out.println(request.getURI());
    
        HttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(request);
    
        int statusCode = response.getStatusLine().getStatusCode();
        String content = EntityUtils.toString(response.getEntity());
    
        System.out.println(statusCode);
        System.out.println(content);
      }
    }
    

Node.js语言 SDK 生成签名

  1. 安装火山引擎程序包。
pnpm add @volcengine/openapi
  1. 生成签名
import { Signer } from '@volcengine/openapi';
import type { RequestObj } from '@volcengine/openapi/lib/base/types';

interface Options {
  pathname: string
  method: 'GET' | 'POST'
  body?: string // json 字符串,当且仅当 post 请求
  region: 'cn-beijing' | 'cn-shanghai'
  params?: Record<string, any> // 当且仅当 get 请求
}

function signer({ pathname, method, body, region, params }: Options) {
  const requestObj: RequestObj = {
   region, 
   headers: {
     Accept: 'application/json',
     'Content-Type': 'application/json'
   },
   method,
   body,
   pathname,
   params,
 }

  const signer = new Signer(requestObj, 'air')
    signer.addAuthorization({
      accessKeyId: 'ak', // 替换为用户 ak
      secretKey: 'sk', // 替换为用户 sk
 })
 return requestObj.headers
}

调用函数 signer 生成请求体 header 后,将生成好的 header 注入到用户请求函数中。