文档中心 > AI PAAS

Agent调用文档

更新时间:2026/03/24 访问次数:3428

相关背景介绍

相关概念

openId:淘宝侧基于appkey+用户id生成的唯一标识,用户唯一标识一个用户;

appkey:应用唯一标识

appSecret:应用密钥

                              

调用模式

普通模式(默认):

概念说明

使用应用的appKey进行openId和token的生成与解密,平台默认模式。

核心特点

  ①使用当前有效的appKey

  ②单密钥体系进行签名

使用历史appkey模式:【如需使用请与平台沟通】

概念说明

使用非当前应用的appKey(即曾经历史已存在的appKey)进行openId和token的生成与解密处理。

核心特点

①使用历史已存在的appKey处理openId

②openIdAppKey不同于当前应用的appKey

③双密钥体系进行复合签名验证

使用场景

①系统升级迁移

②保持旧系统兼容性

③历史数据处理

④平滑过渡期

 调用准备

   为了调用安全,所有请求需要进行加签

参数准备:

1、应用appkey、应用appSecret;

2、如果需要使用历史appkey进行调用,还需要准备对应的appkey和appSecret;(这里标记为openIdAppKey和openIdAppSecret)

3、openId,如果传递了参数2,则需要是openIdAppKey生成的openId,否则统一使用应用appkey生成的openId

    该参数定义当前用户是谁

4、sellerOpenId [可选]  如果传递了参数2,则需要是openIdAppKey生成的openId,否则统一使用应用appkey生成的openId

    该参数定义商家id,适用场景,商家专属知识库等,需要传入该参数;

加签逻辑细节

参数准备

参数

类型

必需

说明

appKey

string

应用标识

appSecret

string

应用密钥

timestamp

number

当前时间戳(毫秒)
每次调用需要刷新

nonce

string

随机字符串(建议32位)
每次调用需要刷新

method

string

HTTP方法(GET/POST/PUT/DELETE)

path

string

请求路径(不含域名,如:/api/users)

openIdAppKey

string

历史appkey

openIdAppSecret

string

历史appSecret

签名算法详解

签名字符串构造

普通签名字符串格式

不使用旧appkey


appKey={appKey}&timestamp={timestamp}&nonce={nonce}&method={method}&path={path}
OpenId模式签名字符串格式

 需要使用旧appkey来运行


appKey={appKey}&timestamp={timestamp}&nonce={nonce}&method={method}&path={path}&openIdAppKey={openIdAppKey}

注意:OpenId模式需要同时提供 openIdAppKey 和 openIdAppSecret 参数。

注意:签名字符串中不包含请求体内容,即使有body参数也不会参与签名计算。

注意:顺序不能改变。

HMAC-SHA256签名生成

function generateSignature(appKey, appSecret, timestamp, nonce, method, path, openIdAppKey = null) {
    // 1. 构造签名字符串
    signString = "appKey=" + appKey +
                 "&timestamp=" + timestamp +
                 "&nonce=" + nonce +
                 "&method=" + method.toUpperCase() +
                 "&path=" + path

    if (openIdAppKey != null && openIdAppKey != "") {
        signString = signString + "&openIdAppKey=" + openIdAppKey
    }

    // 注意:签名字符串不包含body内容

    // 2. 确定签名密钥
    signSecret = appSecret
    if (openIdAppKey != null && openIdAppKey != "" && openIdAppKey != appKey) {
        signSecret = appSecret + "|" + openIdAppSecret  // 使用openIdAppSecret
    }

    // 3. 使用HMAC-SHA256生成签名
    signature = hmac_sha256(signString, signSecret)

    // 4. 转换为十六进制字符串
    return hex(signature)
}

注意:签名密钥如果使用了旧appkey,则需要两个密钥拼接;

HTTP请求头构造

必需的认证头

X-App-Key: your_app_key // 应用appkey
X-Timestamp: 1640995200000  // 当前时间戳
X-Nonce: abc123def456ghi789jkl012mno345pqr //随机字符串(建议32位)
X-Signature: a1b2c3d4e5f678901234567890abcdef123456789 // 签名
X-Signature-Algorithm: HMAC-SHA256
X-Signature-Version: v1

可选的认证头

X-Open-Id-App-Key: open_app_key     # OpenId模式使用 - 需要同时提供openIdAppKey和openIdAppSecret

注意:当使用OpenId模式时,需要同时提供 X-Open-Id-App-Key 头和对应的 openIdAppSecret 参数。

验签逻辑细节

                              

错误处理

常见错误码

MISSING_AUTH_HEADERS:缺少必要的认证头

INVALID_APP_KEY:无效的应用标识

TIMESTAMP_EXPIRED:时间戳已过期

DUPLICATE_NONCE:随机数重复

SIGNATURE_VERIFY_FAILED:签名验证失败

关键特性

①签名不包含body:只对请求元数据进行签名,body单独传输

②双重防重放:通过时间戳和随机数防止重放攻击

③灵活的密钥体系:支持普通模式和OpenId模式 

签名刷新

签名中,做了时间戳和随机数验证,每次请求都需要进行刷新;

可以参考SDK实现逻辑

/**
  * 更新认证配置中的时间戳和随机数
  */
private void updateAuthConfig() {
        if (httpOption.getAuthConfig() != null) {
  httpOption.getAuthConfig().setTimestamp(SignatureUtils.generateTimestamp());
          httpOption.getAuthConfig().setNonce(SignatureUtils.generateNonce());
        }
}

HTTP 调用

普通模式

环境

Base URL

生产

https://open-agent-runtime.taobao.com

注意:以下所有请求,都需要前置进行加签;

加签header要求

X-App-Key: your_app_key // 应用appkey
X-Timestamp: 1640995200000  // 当前时间戳
X-Nonce: abc123def456ghi789jkl012mno345pqr //随机字符串(建议32位)
X-Signature: a1b2c3d4e5f678901234567890abcdef123456789 // 签名
X-Signature-Algorithm: HMAC-SHA256
X-Signature-Version: v1

所有请求 需要带上openId

每次请求都需要在header中加上openId,注意 这非常重要,平台会通过该数据定位用户等;

X-Open-Id: openId

判断是否需要sellerOpenId参数

可选参数

对于客服场景,openId标识消费者,但专属知识库维度是基于商家维度,所以需要传递sellerOpenId,用于召回商家专属知识库场景;

X-Seller-Open-Id: sellerOpenId

创建会话

POST /open/api/v1/agents/createConversation

https://open-agent-runtime.taobao.com/open/api/v1/agents/createConversation

requestBody:

{
  /**
    * 运行时账号id,用作后续 API 调用的越权校验
    */
  "runtimeAccountId": "建议传openId";
}

Respons Body:

{
    "success": true,
    "errCode": null,
    "errMsg": null,
    "data": {
        "conversationId": "0198c653f5bb70b1a971c09b935a1e640551"
    }
}

中断会话

POST /open/api/v1/agents/interruptConversation

https://open-agent-runtime.taobao.com/open/api/v1/agents/interruptConversation

Request Body:

{
  "conversationId": "0198c653f5bb70b1a971c09b935a1e640551" //会话id,必填
}

Response Body:

{
    "success": true,
    "errCode": null,
    "errMsg": null,
    "data": {}
}

发起推理

注意:推理接口需要携带openId

POST /open/api/v1/agents/streamCall

https://open-agent-runtime.taobao.com/open/api/v1/agents/streamCall

请求参数:

conversationId  string(必填)

会话 id,用于关联平台存储的对话历史,实现多轮会话(待实现)。


messageId  string(必填)

业务自定义消息 id,需保证会话内唯一,该参数将透传到响应中。


agentCode  string(必填)

Agent Code, Agent 卡片上可以复制 Agent Code。


question  string(必填)

输入期望当前 Agent 执行的指令,用来指导 Agent 生成回复。


mediaList  List(可选)

多媒体文件列表

Media 对象

字段名

类型

必填

说明

枚举值

data

string

多媒体数据内容

-

mediaType

string

多媒体文件类型

image, video, audio

dataType

string

数据格式类型

url


previous  array(可选)

自定义多轮对话。

[
    {
        "role": "user",
        "content": "分别按天按渠道查询商品123和商品456的访客数和转化率排行,并给出两个商品比较的最终结论。"
    },
    {
        "role": "assistant",
        "reasoningContent": "[总结]需要找到店铺中高访客高转化的产品,作为店铺的主推产品。首先需要获取店铺近30天访客前10的产品,然后在这些产品中找到高转化率的产品。[下一步]调用【凡笙测试】商品访客数排行查询工具,获取店铺近30天访客前10的产品数据。",
        "toolCalls": [
            {
                "id": "9a483c6237bb58d8d76c",
                "type": "function",
                "name": "商品访客数排行查询",
                "arguments": "{\"endDate\":\"2025-08-21\",\"startDate\":\"2025-07-22\",\"topN\":\"10\"}"
            }
        ]
    },
    {
        "role": "tool",
        "toolCallResponses": [
            {
                "id": "9a483c62bb58d8d76c",
                "name": "商品访客数排行查询",
                "responseData": "{\"result\":\"xxx"}"
            }
        ]
    },
    {
        "role": "assistant",
        "content": "分析:\n1. 店铺近30天访客前10的产品中,商品xxx数最高,为167014,明显高于其他产品。\n2. 商品ID7然无法获取具体趋势,但其访客数显著高于其他产品,且在前两访客产品中转化率较高。\n\n结论:商品ID794最高,转化率较高,可以作为店铺的主推款。\n\n建议:在有店铺数据的情况下,可根据高访客高转化的数据标准来选择主推款;在没有数据的情况下,需要进行测款,根据测款数据寻找高访客高转化的商品作为主推款。"
    }
]

variables  object(可选)

提示词变量,对应提示词中的 {xxx} 变量。key 为变量名,value 为变量值。


systemParams  object(可选)

系统参数,是指工具入参定义中的系统参数:


agentVersion  string(可选)

①latest(默认):线上发布版本。

②draft:最新草稿版本。

③x.x.x:指定版本号。


timeout  integer(可选)

本次请求的超时时间(默认为 5 分钟),是指从平台收到推理请求到流式输出完全结束的时间。

Request Body

{
    "conversationId": "3AA3A2E16FAD46D5A736940338934964", //会话id, 必填
    "messageId": "529D95AF02594821892CAC2EB13D15B5", //业务自定义消息id,需保证会话内唯一, 前端传 uuid 即可, 必填
    "variables": { // 提示词变量, 选填
        "userName": "oneice"
    },
    "systemParams": { // 系统参数 for atp, 选填
        "tbOauthToken": "9A4830E672554D8CB107355C982C33BC"
    },
    "agentCode": "agent_45db447zc1", // Agent code, 必填
    "question": "帮我查下杭州明天的天气", // 用户提问, 必填
    "enableThinking": false, // 是否开启深度思考, 默认 false, 必填
    "agentVersion": "draft", // agent版本,
    "mediaList": [{ // 多媒体资源
      "data": "https://cdn.example.com/photo.jpg",
      "mediaType": "image",
      "dataType": "url"
    }]
}

返回值说明

返回参数

名称

类型

描述

示例值

conversationId

string

会话 id

0198e1cf212c755fba6c8ebfc007fbd46991

messageId

string

业务自定义消息 id

80cf8809-4231-4861-b0ab-94096e4ddea1

messages

array

消息列表


|─

object



公共字段




|─id

string

message id
流式场景下可以基于该 id 合并消息

e89f4ced571b5a0d10e05d2af6d9aa0b

|─type

string

不同 type 对应不同的字段:?*   llmMessage → role、reasoningContent、content、toolCalls、toolCallResponses


llmMessage

|─usage

object

token usage


|─promptTokens

integer


1000

|─completionTokens

integer


1000

|─totalTokens

integer


2000

|─rt

integer

response time(毫秒)
对于多条同 id 的消息,请以最后一条消息的 rt 为准

5141

|─finishReason

string

结束原因,非空代表一条完整消息的结束。可能的值: stop、longRtBreak、returnDirect、finalAnswer

stop

|─metadata

object

其他元数据


LLM 消息




|─role

string

不同 role 对应不同的字段:?*   assistant → reasoningContent、content、toolCalls

assistant

|─reasoningContent

string

思考过程

``plaintext<br>用户想知道杭州市今天是否会下雨。我需要调用天气查询API来获取杭州市的天气预报信息。使用默认的API key和城市编码330100进行查询。<br>``

|─content

string

思考结果

杭州今天小雨。

|─toolCalls

array

工具调用信息


|─

object



|─id

string

工具调用 id

6149d09cbc92438fb3601e89f0cd932a

|─name

string

透给 LLM 的工具名称,与平台定义的工具名称并不相同

天气查询_tool_32e39vn93x

|─type

string

工具类型:?*   1 : TOOL


1

|─arguments

string

工具调用参数

``json<br>{<br>    "output": "JSON",<br>    "extensions": "all",<br>    "city": "330100",<br>    "key": "661adb9260ea2a5d"<br>}<br>``

|─async

boolean

是否异步工具

false

|─schema

string

工具 schema

``json<br>{<br>    "type": "function",<br>    "function": {<br>        "name": "天气查询_tool_32e39vn93x",<br>        "parameters": {<br>            "type": "object",<br>            "properties": {<br>                "output": {<br>                    "description": "返回格式。可选值:JSON、XML_exampleValue: JSON",<br>                    "type": "string"<br>                },<br>                "extensions": {<br>                    "description": "气象类型。可选值:base、all。base:返回实况天气。all:返回预报天气。_exampleValue: base",<br>                    "type": "string"<br>                },<br>                "city": {<br>                    "description": "城市编码_exampleValue: 110101",<br>                    "type": "string"<br>                },<br>                "key": {<br>                    "description": "API key_exampleValue: 1056920693B04C25A227786FC8D409A7",<br>                    "type": "string"<br>                }<br>            },<br>            "required": [<br>                "city"<br>            ]<br>        },<br>        "description": "天气查询是一个简单的 HTTP 接口,根据用户输入的 adcode(city 参数),查询目标区域当前/未来的天气情况。\n\n#### 返回结果说明\n\n实况天气每小时更新多次,预报天气每天更新3次,分别在8、11、18点左右更新。由于天气数据的特殊性以及数据更新的持续性,无法确定精确的更新时间,请以接口返回数据的 reporttime 字段为准。\n"<br>    }<br>}<br>``

|─name

string

透给 LLM 的工具名称,与平台定义的工具名称并不相同

天气查询_tool_32e39vn93x

|─metadata

object

工具拓展信息


|─actionCode

string

action code

100066

|─actionVersion

string

action version

0.0.6

|─wrapperCode

string

wrapper code


|─wrapperInstanceId

string

wrapper instance id


|─wrapperToolName

string

wrapper tool name


|─toolId

string

普通工具 id

100066

|─toolCode

string

普通工具 code

tool_32e39vn93x

|─toolVersion

string

普通工具版本

0.0.6

|─toolName

string

普通工具名称

天气查询

|─agentCode

string

类 A2A 工具 code

agent_3cb79yhvue

|─agentVersion

string

类 A2A 工具版本

0.3.5

|─agentName

string

类 A2A 工具名称

天气助理

|─toolCallResponses

array

工具调用结果


|─

object



|─id

string

工具调用 id

6149d09cbc92438fb3601e89f0cd932a

|─name

string

模型所识别的工具名称,与平台定义的工具名称并不相同

天气查询_tool_32e39vn93x

|─responseData

string

工具响应数据

``json<br>{<br>    "lives": null,<br>    "count": "1",<br>    "infocode": "10000",<br>    "info": "OK",<br>    "status": "1",<br>    "forecasts": [<br>        {<br>            "province": "浙江",<br>            "casts": [],<br>            "city": "杭州市",<br>            "adcode": "330100",<br>            "reporttime": "2025-09-01 23:05:35"<br>        }<br>    ]<br>}<br>``

整体结构

{
    "conversationId": "0197f4ca994a7d7880e8785cbca33e426991", //会话id
    "messageId": "344c3a88-8b3a-4ed7-be92-9c82624afca7", //业务自定义消息id
    /**
     * 不同 type 映射不同的字段:
     * message → messages
     * longPolling → longPolling
     */
    "type": "messages",

    // 消息列表
    "messages": [
        {
            // ================================ 公共字段 start ================================
            "id": "",
            /**
             * 不同 type 对应不同的字段:
             * llmMessage → role、reasoningContent、content、toolCalls、toolCallResponses
             * intentRecognition → intentRecognition
             * selfPlanTools → selfPlanTools
             * selfPlanPrompt → selfPlanPrompt
             */
            "type": "llmMessage",
            "usage": { //token usage
                "promptTokens": 0,
                "completionTokens": 0,
                "totalTokens": 0
            },
            "rt": 0,
            "finishReason": "",
            // ================================ 公共字段 end ================================

            // ================================ llmMessage start ================================
            "role": "",
            "reasoningContent": "", //思考过程
            "content": "", //思考结果
            "toolCalls": [ //工具调用请求
                {
                    "id": "", //工具调用id
                    "type": "",
                    "name": "",
                    "arguments": ""
                }
            ],
            "toolCallResponses": [ //工具调用结果
                {
                    "id": "", //工具调用id
                    "name": "",
                    "responseData": ""
                }
            ]
            // ================================ llmMessage end ================================

        }
    ],

    //长轮询事件
    "longPolling": { 
        "offset": 0 // 起始 offset
    }
}

一旦推理完成,服务端会在最后返回一条内容为 "[DONE]" 的消息:

event: message
data: [DONE]

一旦推理失败,服务端将返回一条 event=error 的消息,内容为传统 json 格式的 result:

event: error
data: {"success":false,"errCode":"CHAT_CONVERSATION_NOT_EXIST","errMsg":"会话不存在"}
type = longPolling

type = longPolling 时表示这是长轮询事件,需取 longPolling 字段,切换至长轮询逻辑。

注意:长轮询无流式输出;

{
    "conversationId": "0197f4ca994a7d7880e8785cbca33e426991", //会话id
    "messageId": "344c3a88-8b3a-4ed7-be92-9c82624afca7", //业务自定义消息id
    "type": "longPolling",
    "longPolling": { //长轮询事件
        "offset": 0 // 起始 offset
    }
}

前端需断开 SSE 连接并发起长轮询请求,通过长轮询方式获取后续响应。

type = message

type = message 时表示这是大模型回复,需取 messages 字段,把回复渲染成聊天框的消息。

{
    "conversationId": "0197c56d571072fdadff7ca4f178f3150024",
    "messageId": "8e9cd5d3-613a-43ae-8f3a-afcde35913e2",
    "type": "message",
    "messages": []
}

mesages 里每条消息里也有个 type 字段,需再根据里面的 type 进行区分处理。

type = llmMessage(流式)  暂时只考虑这个
{
    "conversationId": "0197c56d571072fdadff7ca4f178f3150024",
    "messageId": "8e9cd5d3-613a-43ae-8f3a-afcde35913e2",
    "type": "message",
    "messages": [
        {
            "id": "222",
            "type": "llmMessage",
            "role": "assistant",
            "reasoningContent": "为了查询杭州明天的天气情况,我需要使用“查询天气”工具。首先,我必须确认杭州市的城市编码。根据已知信息,杭州市的adcode是330100,但具体的citycode没有直接给出。不过,通常情况下,城市编码由adcode和citycode组成,对于大城市而言,citycode往往与电话区号相关联。考虑到杭州的电话区号为0571,我们可以尝试将杭州市的城市编码设置为3301000571来进行查询。如果这个编码不正确,我将向用户询问确切的城市编码。由于用户没有提供API key,我将采用默认值进行查询。",
            "content": "",
            "toolCalls": [
                {
                    "id": "212cacd222494a129ccbce1ce5552b09",
                    "type": "function",
                    "name": "查询天气_tool_32e39vn93x",
                    "arguments": "{\"output\":\"JSON\",\"extensions\":\"all\",\"city\":\"3301000571\",\"key\":\"7e31f40eab77d52c661adb9260ea2a5d\"}"
                }
            ],
            "toolCallResponses": [],
            "usage": {
                "promptTokens": 1751,
                "completionTokens": 241,
                "totalTokens": 1992
            },
            "finishReason": "stop",
            "rt" 1000
        }
    ]
}
{
    "conversationId": "0197c56d571072fdadff7ca4f178f3150024",
    "messageId": "8e9cd5d3-613a-43ae-8f3a-afcde35913e2",
    "type": "message",
    "messages": [
        {
            "id": "333",
            "type": "llmMessage",
            "role": "tool",
            "reasoningContent": "",
            "content": "",
            "toolCalls": [],
            "toolCallResponses": [ // 仅当 role=tool 时有值
                {
                    "id": "212cacd222494a129ccbce1ce5552b09",
                    "name": "查询天气_tool_32e39vn93x",
                    "responseData": "{\"lives\":null,\"count\":\"1\",\"infocode\":\"10000\",\"info\":\"OK\",\"status\":\"1\",\"forecasts\":[{\"casts\":[]}]}"
                }
            ],
            "usage": {
                "promptTokens": 0,
                "completionTokens": 0,
                "totalTokens": 0
            },
            "finishReason": "returnDirect",
            "rt" 1000
        }
    ]
}
{
    "conversationId": "0197c56d571072fdadff7ca4f178f3150024",
    "messageId": "8e9cd5d3-613a-43ae-8f3a-afcde35913e2",
    "type": "message",
    "messages": [
        {
            "id": "444",
            "type": "llmMessage",
            "role": "assistant",
            "reasoningContent": "",
            "content": "您好,我尝试使用了城市编码3301000571来查询杭州市的天气情况,但未能获取到有效的信息。请您提供正确的杭州市城市编码,以便我能为您准确查询明天的天气预报。如果不确定具体编码,也可以告诉我您想了解哪个区的具体天气情况,这样或许能更精确地定位。",
            "toolCalls": [],
            "toolCallResponses": [],
            "usage": {
                "promptTokens": 2095,
                "completionTokens": 73,
                "totalTokens": 2168
            },
            "finishReason": "finalAnswer"
        }
    ]
}

长轮询

POST /open/api/v1/agents/longPolling

https://open-agent-runtime.taobao.com/open/agents/longPolling

requestBody:

{
    "conversationId": "3AA3A2E16FAD46D5A736940338934964", //会话id, 必填
    "messageId": "111", //消息id, 需与推理请求传入的 messageId 保持一致, 必填
    "offset": 0, //偏移量, 取自 asyncBreak 消息的 content 字段, 必填
    "timeout": 10000 //服务端 hold 住请求的超时时间, 默认 10 秒, 选填
}

Respons Body:

{
    "success": true,
    "errCode": "",
    "errMsg": "",
    "data": {
        "outputs": [ 
            {} // 参考推理请求的返回结构
        ],
        "finished": false, // 推理是否已完成
        "offset": 1 // 如未完成需要拿着该 offset 再次发起长轮询
    }
}


执行工作流

*工作流调用最新介绍请移步这里查看?工作流调用说明


工作流执行分为同步和异步调用,均是流式返回结果。默认是同步调用,即调用后等待结果的输出;如果主动选择异步调用,则还需要配套监听开放平台的TMC消息(topic:taobao_agent_WorkflowAsyncResult)获取到工作流执行的结果。

POST /open/api/v1/workflow/execute

https://open-agent-runtime.taobao.com/open/api/v1/workflow/execute

requestBody:

{
    "openId": "AAH4C_-NAOaPuehU232fefe",  // openId定位唯一用户
    "workflowCode": "workflow_19810auczs", // 必选,工作流的标识
    "sync": true,    // true表示同步,false表示异步,默认是true
    "query": "1231234",  //可选,查询文本,工作流可以基于此查询进行语义理解和任务分发。
    "input": {
        "question": "11",
        "text": "{\"chill\":\"1\"}"
    },   //工作流输入参数集合
    "systemParams": {
        "tbOauthToken": "61028165fdb2ba488256ebc41c772474b09016934"
    },   // 系统参数
    "originBizParams":{
        "messageIds":[
            "3434343",
            "4343432"
        ]
    } // 业务参数,当前可选,主要用于业务数据埋点使用,后续会以具体业务场景模式进行规范
}

Respons Body:

{
    "workflowInstanceId": "214003",   // 工作流实例ID
    "workflowCode": "workflow_19810auczs", // 工作流标识
    "status": "RUNNING"   // 工作流执行状态
}

{
    "workflowInstanceId": "214003", // 工作流实例ID
    "workflowCode": "workflow_19810auczs", // 工作流标识
    "status": "SUCCESS",  // 工作流执行状态
    "result": {
        "output": 293334304,
        "qwere": "23",
        "qwdqw": "e"
    }   // 工作流执行完成后的最终结果集
}

使用旧appkey模式

header要求

header需要新增X-Open-Id-App-Key,同时,签名算法需要更新

X-App-Key: your_app_key // 解决方案appkey
X-Timestamp: 1640995200000  // 当前时间戳
X-Nonce: abc123def456ghi789jkl012mno345pqr //随机字符串(建议32位)
X-Signature: a1b2c3d4e5f678901234567890abcdef123456789 // 签名
X-Signature-Algorithm: HMAC-SHA256
X-Signature-Version: v1
X-Open-Id-App-Key: open_app_key     # OpenId模式使用 - 需要同时提供openIdAppKey和openIdAppSecret

其余与普通模式保持一致~

Java SDK

Change log

10.17 更新日志

  ①新增 previous 字段(自定义多轮对话)

10.22 更新日志

  ①修复sdk中随机数共享变量问题,解决了并发请求随机数冲突问题 

11.10 更新日志

  ①新增工作流调用

11.18 更新日志

  ①入参新增了originBizParams字段(String类型),专门用于调用方根据业务场景传入的规范的业务参数,是将对象JSONString化之后作为值进行传入。

1.12 更新日志

  ①WorkflowInput更新了originBizParams为String类型,新增了工作流版本号workflowVersion字段,结合 workflowVersion 可以定位到具体的工作流版本

1.16 更新日志

  ①sdk新增日志


*工作流调用最新介绍请移步这里查看?工作流调用说明

Jar包

支持jdk8 11.18更新 

https://open-agent-sdk.oss-cn-beijing.aliyuncs.com/last/open-tao-agent-light-sdk-1.0.22-log-SNAPSHOT-with-dependencies.jar 

 Tip:1、若启动报错 Caused by: java.lang.NoSuchMethodError: 'void reactor.core.publisher.Hooks.enableAutomaticContextPropagation()',说明 reactor-core 存在依赖冲突,需确保实际使用的 reactor-core 版本为 3.7.6。

API参考 - 普通模式

2.1 初始化Client

public static OpenTaoAgentClient createClient() {
        // 配置环境header
        OkHttpOption httpOption = OkHttpOption.builder()
                .build();

        return OpenTaoAgentClient.builder()
                .appKey("xxx")
                .appSecret("xxxx")
                .apiKey(API_KEY)
                .httpOption(httpOption)
                .build();
}
// API_KEY 暂时固定传递TOP_SDK_INVOKE
OpenTaoAgentClient client = createClient();

2.2 创建会话

请求参数

名称

类型

必填

描述

示例值

runtimeAccountId

string

业务自定义用户 id,用作关联会话和分表键,平台不关心该 id 的实际含义。

可以使用openId

openId

string

openId,平台使用该参数定位用户(商家或消费者),用于工作流等;

xxxxx

sellerOpenId

string

sellerOpenId,平台使用该参数定位商家,用于专属知识库调用等;


返回参数

名称

类型

描述

示例值

conversationId

string

会话 id

0198e1cf212c755fba6c8ebfc007fbd46991

请求示例

public String createConversation(String openId) {
    try {
        CreateConversationResponse resp = client.createConversation(
                    CreateConversationRequest.builder()
                            .runtimeAccountId("xxxxx") // 可以使用openId
                            .openId("xxxxxx") // 必填参数 openId 基于应用生成的openId
                            .sellerOpenId("xxxxx") // 可选参数
                            .build());
        return resp.getConversationId();
    } catch (SdkException e) {
        // TODO: 异常处理
    }
}

2.3 发起推理

Map<String, Object> variables = new HashMap<>();
variables.put("city", "杭州");

Map<String, Object> systemParams = new HashMap<>();

List<Media> mediaList = new ArrayList<>();

// 更多参数请见 SDK 源码
AgentInput input = AgentInput.builder()
        .agentCode("xxx") // Agent code
        // 会话id,必填!调用 createConversation 生成
        .conversationId("01982709eeb37d70a252565b063585b11602") 
        // openId,需与会话创建时传的值保持一致
        .openId("xxxxxx")
        // 选填 sellerOpenId,需与会话创建时传的值保持一致
        .sellerOpenId("xxxxx")
        // 业务自定义消息id,需保证会话内唯一
        .messageId(UUID.randomUUID().toString())
        // 提示词变量,对应 Agent 或 Task 提示词中的 {xxx} 变量
        .variables(variables)
        // 不要改
        .enableThinking(false)
        // 系统参数,指的是工具入参定义中的系统参数,see SystemParamEnum
        .systemParams(systemParams)
        // 选填 自定义多轮对话
        .previous(previous)
        // 用户问题
        .question("查下明天的天气")
        // 选填,仅支持多模态模型传递
        .mediaList(mediaList)
        // 聚合流式消息
        .enableAggregation(true)
        .build();

// 异步处理(没必要包一层 try catch)
// CountDownLatch latch = new CountDownLatch(1);
client.streamCall(input)
        .doOnNext(output -> {
            log.info("Receive a AgentOutput: {}", JsonUtils.toJSONString(output));
        }).doOnError(ex -> { // 不要上抛异常
            log.error("TaoAgentClient streamCall error, input: {}", input, ex);
            // latch.countDown();
        }).doOnComplete(() -> {
            log.info("DONE");
            // latch.countDown();
        }).contextCapture() // 避免 trace 丢失
        .subscribe(EmptySubscriber.INSTANCE); // 避免报错 Exceptions$ErrorCallbackNotImplemented
// latch.await();

// 同步处理
// try {
//     client.streamCall(input).toStream().forEach(output -> System.out.println(JsonUtils.toJSONString(output)));
// } catch (Exception e) {
//     log.error("TaoAgentClient streamCall error, input: {}", input, e);
// }

响应示例:

{
    "conversationId": "01982709eeb37d70a252565b063585b11602", // 会话id
    "messageId": "9e6c7700-9a08-472b-984e-3626caa2c156", // 业务自定义消息id
    "messages": [ // 增量消息列表
        {
            "id": "1037548abb5511d7b8773f2348b133b7", // 可基于该 id 合并同一条消息
            // assistant 代表模型答复,相关字段:reasoningContent、content、toolCalls
            // tool 代表工具调用结果,相关字段:toolCallResponses
            "role": "assistant", 
            // 思考
            "reasoningContent": "用户想了解明天的天气情况,默认城市为杭州。根据补充知识,杭州市的城市编码为330100。我将使用查询天气工具来获取杭州市接下来几天的天气预报信息,并从中提取出明天的具体天气状况。由于用户没有提供API key,我将采用默认值进行查询。",
            // 结果
            "content": "",
            "toolCalls": [ // 工具调用参数
                {
                    "id": "8013332e7d8540e0873ffd55706545ad", // toolCalls.id 对应 toolCallResponses.id
                    "type": "function",
                    "name": "查询天气_tool_32e39vn93x",
                    "arguments": "{\"output\":\"JSON\",\"extensions\":\"all\",\"city\":\"330100\",\"key\":\"7e31f40eab77d52c661adb9260ea2a5d\"}"
                }
            ],
            "toolCallResponses": [], // 工具调用结果
            "usage": { // token 消耗
                "promptTokens": 2414,
                "completionTokens": 153,
                "totalTokens": 2567
            },
            "finishReason": "stop", //  结束原因
            "rt": 4587, // 耗时
            "metadata": {}
        }
}
{
    "conversationId": "01982709eeb37d70a252565b063585b11602",
    "messageId": "9e6c7700-9a08-472b-984e-3626caa2c156",
    "messages": [
        {
            "id": "tool_exec_019826cb0f9b7ed3866cb92d7717856f",
            "role": "tool",
            "reasoningContent": "",
            "content": "",
            "toolCalls": [],
            "toolCallResponses": [
                {
                    "id": "8013332e7d8540e0873ffd55706545ad",
                    "name": "查询天气_tool_32e39vn93x",
                    "responseData": "{\"lives\":null,\"count\":\"1\",\"infocode\":\"10000\",\"info\":\"OK\",\"status\":\"1\",\"forecasts\":[{\"province\":\"浙江\",\"casts\":[{\"date\":\"2025-07-20\",\"dayweather\":\"多云\",\"daywind\":\"东\",\"week\":\"7\",\"daypower\":\"1-3\",\"daytemp\":\"33\",\"nightwind\":\"东\",\"nighttemp\":\"27\",\"daytemp_float\":\"33.0\",\"nighttemp_float\":\"27.0\",\"nightweather\":\"多云\",\"nightpower\":\"1-3\"},{\"date\":\"2025-07-21\",\"dayweather\":\"小雨\",\"daywind\":\"东\",\"week\":\"1\",\"daypower\":\"1-3\",\"daytemp\":\"33\",\"nightwind\":\"东\",\"nighttemp\":\"26\",\"daytemp_float\":\"33.0\",\"nighttemp_float\":\"26.0\",\"nightweather\":\"多云\",\"nightpower\":\"1-3\"},{\"date\":\"2025-07-22\",\"dayweather\":\"小雨\",\"daywind\":\"东\",\"week\":\"2\",\"daypower\":\"1-3\",\"daytemp\":\"33\",\"nightwind\":\"东\",\"nighttemp\":\"26\",\"daytemp_float\":\"33.0\",\"nighttemp_float\":\"26.0\",\"nightweather\":\"晴\",\"nightpower\":\"1-3\"},{\"date\":\"2025-07-23\",\"dayweather\":\"小雨\",\"daywind\":\"东\",\"week\":\"3\",\"daypower\":\"1-3\",\"daytemp\":\"35\",\"nightwind\":\"东\",\"nighttemp\":\"26\",\"daytemp_float\":\"35.0\",\"nighttemp_float\":\"26.0\",\"nightweather\":\"小雨\",\"nightpower\":\"1-3\"}],\"city\":\"杭州市\",\"adcode\":\"330100\",\"reporttime\":\"2025-07-20 15:35:53\"}]}"
                }
            ],
            "usage": {
                "promptTokens": 0,
                "completionTokens": 0,
                "totalTokens": 0
            },
            "finishReason": "returnDirect",
            "rt": 12869,
            "metadata": {}
        }
    ]
}
{
    "conversationId": "01982709eeb37d70a252565b063585b11602",
    "messageId": "9e6c7700-9a08-472b-984e-3626caa2c156",
    "messages": [
        {
            "id": "d821038b6ebc8d59b642a58bf305f192",
            "role": "assistant",
            "reasoningContent": "根据查询到的信息,杭州市明天(2025年8月21日)的天气情况如下:白天有小雨,夜间转为多云,气温介于26°C至33°C之间。风向主要为东风,风力等级在1-3级。",
            "content": "杭州市明天(2025年8月21日)的天气预报为:白天预计会有小雨,晚上则转为多云天气,温度范围是26°C~33°C。风向以东风为主,风力较为温和,请记得携带雨具并注意出行安全。",
            "toolCalls": [],
            "toolCallResponses": [],
            "usage": {
                "promptTokens": 2988,
                "completionTokens": 138,
                "totalTokens": 3126
            },
            "finishReason": "finalAnswer",
            "rt": 1219,
            "metadata": {}
        }
    ]
}

2.4 中断会话

请求参数

名称

类型

必填

描述

示例值

conversationId

string

会话 id,源自创建会话的返回参数

0198e1cf212c755fba6c8ebfc007fbd46991

openId

string

openId,平台使用该参数定位用户(商家或消费者),用于工作流等;

xxxxx

sellerOpenId

string

sellerOpenId,平台使用该参数定位商家,用于专属知识库调用等;


messageId

string

消息 id,源自发起推理的返回参数。
如果要直接中断整个会话,无需传递该参数;如果只想中断特定推理请求的后续回复,则需要传递该参数,并确保其与发起推理时传递的值一致。

050e9565-07c1-4d26-b53b-082750a4ed45

client.interruptSession(
                    InterruptConversationRequest.builder()
                            .conversationId(resp.getConversationId())
                            .messageId(UUID.randomUUID().toString())
                            .openId("xxxx")
                            // 选填 sellerOpenId,需与会话创建时传的值保持一致
                            .sellerOpenId("xxxx")
                            .build());

2.5 执行工作流

*工作流调用最新介绍请移步这里查看?工作流调用说明

请求参数

名称

类型

必填

描述

示例值

workflowCode

string

工作流标识

workflow_19810auczs

openId

string

openId,平台使用该参数定位用户(商家或消费者),用于工作流等;如果工作流中用到了用户维度的工作调用等等,该参数则为必填

xxxxx

sellerOpenId

string

sellerOpenId,平台使用该参数定位商家,用于专属知识库调用等;

sync

boolean

true表示同步,false表示异步;默认是同步,如果是异步,则需要配合开放平台的TMC消息进行结果的获取

true

query

String

查询文本,用于传递用户的自然语言查询。工作流可以基于此查询进行语义理解和任务分发。

input

Map<String,Object>

工作流开始节点使用的参数集合,会直接传递给工作流的第一个节点

systemParams

Map<String,Object>

系统参数集合

originBizParams

Map<String,Object>

业务参数集合,后续指定业务需要传入固定格式的业务数据便于埋点

Map<String, Object> variables = new HashMap<>();
            variables.put("question", "11");
            variables.put("text", "{\"chill\":\"1\"}");

Map<String, Object> systemParams = new HashMap<>();
systemParams.put("tbOauthToken", "61028165fdb2b56ebc41c772474b4a2f2211509016934");

WorkflowInput input = WorkflowInput.builder()
                .workflowCode("workflow_19810auczs")
                // 同步调用
                .sync(true)
                .query("1231234")
                .input(variables)
                .openId("AAH4C_-NAOaPuehU0Z84Kf")
                .systemParams(systemParams)
                .build();

client.executeWorkflow(input)......

API参考 - 指定appkey调用【兼容老应用appkey调用】

初始化Client - 仅这一步与普通模式不同

public static OpenTaoAgentClient createClient() {
        // 配置环境header
        OkHttpOption httpOption = OkHttpOption.builder()
                .build();
        OpenIdConfig openIdConfig = OpenIdConfig.builder()
                .openIdAppKey("xxx")
                .openIdAppSecret("xxxx")
                .build();
        return OpenTaoAgentClient.builder()
                .appKey("xxx")
                .appSecret("xxxx")
                .apiKey(API_KEY)
                .httpOption(httpOption)
                .openIdConfig(openIdConfig)
                .build();
}
// API_KEY 暂时固定传递TOP_INVOKE
OpenTaoAgentClient client = createClient();

其余调用 与普通模式保持一致

完整Demo

import com.taobao.agent.light.sdk.client.OpenTaoAgentClient;
import com.taobao.agent.light.sdk.common.OpenIdConfig;
import com.taobao.agent.light.sdk.model.*;
import com.taobao.agent.light.sdk.okhttp.OkHttpOption;
import com.taobao.agent.light.sdk.util.EmptySubscriber;
import com.taobao.agent.light.sdk.util.JsonUtils;

import java.util.UUID;

/**
 * @author zhangtaiyan.zty
 * @date 2025/9/8 23:58
 */
public class NormalInvokeClientExample {
    private static final String API_KEY = System.getProperty("agent.api.key", "TOP_SDK_INVOKE");

    public static OpenTaoAgentClient createClient() {

        // 配置环境header
        OkHttpOption httpOption = OkHttpOption.builder()
                .build();

        OpenIdConfig openIdConfig = OpenIdConfig.builder()
                .openIdAppKey("xxx")
                .openIdAppSecret("xxx")
                .build();
        return OpenTaoAgentClient.builder()
                .appKey("xxx")
                .appSecret("xxx")
                .apiKey(API_KEY)
                .httpOption(httpOption)
                .openIdConfig(null)
                .build();
    }


    public static void main(String[] args) {
        try {
            OpenTaoAgentClient client = createClient();
            // 这里可以添加您的业务逻辑
            // 例如:调用agent服务等
            CreateConversationResponse resp = client.createConversation(
                    CreateConversationRequest.builder()
                            .runtimeAccountId("xxx")
                            .openId("xxx")
                            .sellerOpenId("xxxx")
                            .build());

            System.out.println(resp.getConversationId());
            AgentInput input = AgentInput.builder()
                    .agentCode("xxx") // Agent code
                    // 会话id,必填!调用 createConversation 生成(请忽略旧版 sdk 注释里的选填,下个版本不再支持自动创建会话)
                    .conversationId(resp.getConversationId())
                    .openId("xxx")
                    .sellerOpenId("xxxx")
                    .messageId(UUID.randomUUID().toString()) // 业务自定义消息id,需保证会话内唯一
                    .question("xxx") // 用户问题
                    .agentVersion(AgentVersion.DRAFT.getValue())
                    .build();

            System.out.println(JsonUtils.toJSONString(input));

            // 异步处理
            // 异步处理(没必要包一层 try catch)
            // CountDownLatch latch = new CountDownLatch(1);
            client.streamCall(input)
                    .doOnNext(output -> {
                        System.out.println("Receive a AgentOutput: " +  JsonUtils.toJSONString(output));
                    }).doOnError(ex -> { // 不要上抛异常
                        System.out.println("TaoAgentClient streamCall error, input: {}" + JsonUtils.toJSONString(input));
                    }).doOnComplete(() -> {
                        System.out.println("DONE");
                    }).contextCapture() // 避免 trace 丢失
                    .subscribe(EmptySubscriber.INSTANCE);

            client.interruptSession(
                    InterruptConversationRequest.builder()
                            .conversationId(resp.getConversationId())
                            .openId("xxxx")
                            .sellerOpenId("xxxx")
                            .build());
            // 4. 等待流式调用完成
            // 等待流式调用完成,主线程阻塞一段时间,确保异步回调执行
        } catch (Exception e) {
            System.out.println("Open Agent SDK 客户端创建失败");
        }
    }
}

附录

系统参数列表

tbOauthToken  // 淘宝token

FAQ

关于此文档暂时还没有FAQ
返回
顶部