You need to enable JavaScript to run this app.
文档中心
向量数据库VikingDB

向量数据库VikingDB

复制全文
下载 pdf
知识库(Collection)
service_chat
复制全文
下载 pdf
service_chat
概述

service_chat 支持基于一个已创建的知识服务进行检索/问答。

请求参数
参数类型是否必选默认值参数说明

serviceResourceId

String

是

--

知识服务唯一 ID
可通过知识服务创建结果或知识服务列表接口获取

messages

List

是

--

检索/问答多轮对话消息
格式为一问一答形式,发出消息的对话参与者角色可选值包括:

  • user:User Message 用户消息
  • assistant:Assistant Message 对话助手消息
    其中 最后一个元素 role == user,content 为当前最新的提问 query
    纯文本对话:
    例如:
[
{
"role": "system",
"content": "你是一位在线客服,你的首要任务是通过巧妙的话术回复用户的问题,你需要根据「参考资料」来回答接下来的「用户问题」,这些信息在 <context></context> XML tags 之内,你需要根据参考资料给出准确,简洁的回答。参考资料中可能会包含图片信息,图片的引用说明在<img></img>XML tags 之内,参考资料内的图片顺序与用户上传的图片顺序一致。"
},
{"role": "user", "content": "你好"},
{"role": "assistant", "content": "你好!有什么我可以帮助你的?"},
{"role": "user", "content": "当前轮次用户问题"}
]

图文对话:
例如:

[
{
"role": "system",
"content": "你是一位在线客服,你的首要任务是通过巧妙的话术回复用户的问题,你需要根据「参考资料」来回答接下来的「用户问题」,这些信息在 <context></context> XML tags 之内,你需要根据参考资料给出准确,简洁的回答。参考资料中可能会包含图片信息,图片的引用说明在<img></img>XML tags 之内,参考资料内的图片顺序与用户上传的图片顺序一致。"
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "推荐一个类似的适合 3 岁小孩的玩具"
},
{
"type": "image_url",
"image_url": {
"url": "https://ark-project.tos-cn-beijing.volces.XXX.jpeg"
}
}
]
}
]

queryParam

Map<String, Object>

否

null

检索过滤条件
在创建知识服务时如果您已配置了过滤条件,那么和该附加过滤条件一起生效,逻辑为 and

  • 支持对 doc 的 meta 信息过滤
  • 详细使用方式和支持字段见filter表达式,可支持对 doc_id 做筛选
  • 此处用于过滤的字段,需要在 collection/create 时添加到 index_config 的 fields 上
    例如:
    单层 filter:
doc_filter = {
"op": "must", // 查询算子 must/must_not/range/range_out
"field": "doc_id",
"conds": ["tos_doc_id_123", "tos_doc_id_456"]
}
query_param = {
"doc_filter": doc_filter
}

多层 filter:

doc_filter = {
"op": "and",   // 逻辑算子 and/or
"conds": [     // 条件列表,支持嵌套逻辑算子和查询算子
{
"op": "must",
"field": "type",
"conds": [1]
},
{
...         // 支持>=1的任意数量的条件进行组合
}
]
}
query_param = {
"doc_filter": doc_filter
}

stream

Boolean

否

true

是否采用流式返回

  • true:按 SSE 协议流式返回;false:生成完成后一次性返回完整结果
    当创建的知识服务为问答类型服务时生效
响应消息

目前知识服务主要分为两类,检索类型和问答类型。针对不同类型的知识服务,返回的消息格式也有所不同
检索/问答/流式的差异体现在 Data 内字段是否出现及返回时机:
Count、RewriteQuery、ResultList 通常在首流返回;TokenUsage 通常在尾流返回;GeneratedAnswer、ReasoningContent 在中间流分段返回(SSE)。

字段类型参数说明
codeInteger状态码
messageString返回信息
requestIdString标识每个请求的唯一标识符
dataServiceChatDataServiceChatData

ServiceChatData

字段类型参数说明
countInteger检索结果返回的条数
rewriteQueryStringquery 改写的结果
tokenUsageObjectToken 使用信息
resultListList检索返回的信息
generatedAnswerStringLLM 模型生成的回答
reasoningContentString推理模型生成的内容
promptStringprompt 内容
endBoolean是否结束(流式场景用于标识最后一段)

ServiceChatRetrieveItem

字段类型参数说明
idString索引的主键

content

String

切片内容
1、非结构化文件:Content 返回切片内容
2、faq 文件:Content 返回答案
3、结构化文件:Content 返回参与索引的字段和取值,以 K:V 对拼接,使用 \n 区隔

mdContentStringmarkdown 格式的解析结果(表格切片可通过 ChunkType == table 判断)
scoreDouble向量化语义检索得分
pointIdString切片 id
originTextString原始文本
originalQuestionStringfaq 数据检索召回的答案对应的原始问题
chunkTitleString切片标题
chunkIdLong切片位次 id(代表在原始文档中的位次顺序)
processTimeLong检索耗时(秒)
rerankScoreDouble重排得分
docInfoServiceChatRetrieveItemDocInfoServiceChatRetrieveItemDocInfo
recallPositionInteger向量化语义检索召回位次
rerankPositionInteger重排位次
chunkTypeString切片所属类型(如 doc-image、image、video、table、mixed-table、text、structured、faq 等)
chunkSourceString切片来源
updateTimeLong更新时间
chunkAttachmentList检索召回附件的临时下载链接,有效期 10 分钟
tableChunkFieldsList结构化数据检索返回单行全量数据
originalCoordinateMap<String, Object>切片在所属文档的原始位置坐标

ServiceChatRetrieveItemDocInfo

字段类型参数说明
docIdString文档 id
docNameString文档名字
createTimeLong文档的创建时间
docTypeString知识所属原始文档的类型
docMetaString文档相关元信息
sourceString知识来源类型
titleString知识所属文档的标题

ChunkAttachment

字段类型参数说明
uuidString附件的唯一标识
captionString图片所属标题,若未识别到标题则值为 "\n"
typeStringimage 等
linkString临时下载链接,有效期 10 分钟
infoLinkString附件 info_link
columnNameString附件列名

PointTableChunkField

字段类型参数说明
fieldNameString字段名
fieldValueObject字段值
请求示例

首次使用知识库 SDK,可参考 使用说明
本示例演示了知识库 Java SDK 中 ServiceChat 的基础使用方法,包含普通调用和流式调用两种方式;该功能使用 API Key 鉴权(VIKING_API_KEY),且需配置知识服务 ID。

package com.volcengine.vikingdb.runtime.knowledge.examples.service_chat;

import com.fasterxml.jackson.databind.ObjectWriter;
import com.volcengine.vikingdb.runtime.core.ApiClient;
import com.volcengine.vikingdb.runtime.core.RequestAddition;
import com.volcengine.vikingdb.runtime.core.auth.Auth;
import com.volcengine.vikingdb.runtime.core.auth.AuthWithApiKey;
import com.volcengine.vikingdb.runtime.enums.Scheme;
import com.volcengine.vikingdb.runtime.knowledge.model.request.ChatMessage;
import com.volcengine.vikingdb.runtime.knowledge.model.request.ServiceChatRequest;
import com.volcengine.vikingdb.runtime.knowledge.model.response.ServiceChatResponse;
import com.volcengine.vikingdb.runtime.knowledge.service.KnowledgeService;

import java.util.Collections;

public class Main {
    private static final ObjectWriter PRETTY_JSON = ApiClient.objectMapper.writerWithDefaultPrettyPrinter();
    private static final Scheme SCHEME = Scheme.HTTPS;
    private static final String HOST = "api-knowledgebase.mlp.cn-beijing.volces.com";
    private static final String REGION = "cn-beijing";
    private static final String SERVICE_RESOURCE_ID = "<YOUR_SERVICE_RESOURCE_ID>";

    public static void main(String[] args) throws Exception {
        String apiKey = getEnv("VIKING_API_KEY");
        if (apiKey.isEmpty()) {
            System.out.println("missing_auth: set VIKING_API_KEY");
            return;
        }
        Auth auth = new AuthWithApiKey(apiKey);

        KnowledgeService service = newKnowledgeService(auth);
        ServiceChatRequest req = ServiceChatRequest.builder()
                .serviceResourceId(SERVICE_RESOURCE_ID)
                .messages(Collections.singletonList(ChatMessage.builder()
                        .role("user")
                        .content("<YOUR_QUERY>")
                        .build()))
                .stream(false)
                .build();

        ServiceChatResponse resp = service.serviceChat(req, new RequestAddition());
        printJson("service_chat", resp);
    }

    private static KnowledgeService newKnowledgeService(Auth auth) {
        return new KnowledgeService(SCHEME, HOST, REGION, auth);
    }

    private static String getEnv(String name) {
        String v = System.getenv(name);
        if (v == null) {
            return "";
        }
        v = v.trim();
        return v.isEmpty() ? "" : v;
    }

    private static void printJson(String name, Object obj) throws Exception {
        if (obj == null) {
            System.out.println(name + ": null");
            return;
        }
        System.out.println(name + ": " + PRETTY_JSON.writeValueAsString(obj));
    }
}
package com.volcengine.vikingdb.runtime.knowledge.examples.service_chat_stream;

import com.volcengine.vikingdb.runtime.core.RequestAddition;
import com.volcengine.vikingdb.runtime.core.auth.Auth;
import com.volcengine.vikingdb.runtime.core.auth.AuthWithApiKey;
import com.volcengine.vikingdb.runtime.enums.Scheme;
import com.volcengine.vikingdb.runtime.knowledge.model.request.ChatMessage;
import com.volcengine.vikingdb.runtime.knowledge.model.request.ServiceChatRequest;
import com.volcengine.vikingdb.runtime.knowledge.model.response.ServiceChatResponse;
import com.volcengine.vikingdb.runtime.knowledge.service.KnowledgeService;
import com.volcengine.vikingdb.runtime.knowledge.service.KnowledgeStream;

import java.util.Collections;

public class Main {
    private static final Scheme SCHEME = Scheme.HTTPS;
    private static final String HOST = "api-knowledgebase.mlp.cn-beijing.volces.com";
    private static final String REGION = "cn-beijing";
    private static final String SERVICE_RESOURCE_ID = "<YOUR_SERVICE_RESOURCE_ID>";

    public static void main(String[] args) throws Exception {
        String apiKey = getEnv("VIKING_API_KEY");
        if (apiKey.isEmpty()) {
            System.out.println("missing_auth: set VIKING_API_KEY");
            return;
        }
        Auth auth = new AuthWithApiKey(apiKey);

        KnowledgeService service = newKnowledgeService(auth);
        ServiceChatRequest req = ServiceChatRequest.builder()
                .serviceResourceId(SERVICE_RESOURCE_ID)
                .messages(Collections.singletonList(ChatMessage.builder()
                        .role("user")
                        .content("<YOUR_QUERY>")
                        .build()))
                .stream(true)
                .build();

        try (KnowledgeStream<ServiceChatResponse> stream = service.serviceChatStream(req,
                new RequestAddition())) {
            System.out.println("service_chat_stream:");
            for (ServiceChatResponse item : stream) {
                if (item != null && item.getData() != null && item.getData().getGeneratedAnswer() != null) {
                    System.out.print(item.getData().getGeneratedAnswer());
                }
                if (item != null && item.getData() != null && Boolean.TRUE.equals(item.getData().getEnd())) {
                    break;
                }
            }
            System.out.print("\n");
        }
    }

    private static KnowledgeService newKnowledgeService(Auth auth) {
        return new KnowledgeService(SCHEME, HOST, REGION, auth);
    }

    private static String getEnv(String name) {
        String v = System.getenv(name);
        if (v == null) {
            return "";
        }
        v = v.trim();
        return v.isEmpty() ? "" : v;
    }
}
最近更新时间:2026.09.08 20:33:20
这个页面对您有帮助吗?
有用
有用
无用
无用