ERNIE-Bot-8K
所有文档
menu

千帆大模型服务与开发平台ModelBuilder

ERNIE-Bot-8K

注意:ERNIE-Bot-8K于2024年4月12日已下线,如需要继续使用请切换至ERNIE-3.5-8K,接口文档请参考ERNIE-3.5-8K使用说明

ERNIE-Bot-8K是百度自研的旗舰级大规模⼤语⾔模型,覆盖海量中英文语料,具有强大的通用能力,可满足绝大部分对话问答、创作生成、插件应用场景要求;支持自动对接百度搜索插件,保障问答信息时效,支持5K 输入+2K 输出。本文介绍了相关API。

创建chat

调用本接口,发起一次对话请求。

注意事项

在线调试

平台提供了 API在线调试平台-示例代码 ,用于帮助开发者调试接口,平台集成快速检索、查看开发文档、查看在线调用的请求内容和返回结果、复制和下载示例代码等功能,简单易用,更多内容请查看API在线调试介绍

请求说明

基本信息

请求地址: https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k

请求方式: POST

Header参数

根据不同鉴权方式,查看对应Header参数。

  • 访问凭证access_token鉴权
名称 类型 必填 描述
Content-Type string 固定值application/json
  • 基于安全认证AK/SK进行签名计算鉴权
名称 类型 必填 描述
Content-Type string 固定值application/json
x-bce-date string 当前时间,遵循ISO8601规范,格式如2016-04-06T08:23:49Z
Authorization string 用于验证请求合法性的认证信息,更多内容请参考鉴权认证机制,签名工具可参考IAM签名工具

Query参数

只有访问凭证access_token鉴权方式,需使用Query参数。

  • 访问凭证access_token鉴权
名称 类型 必填 描述
access_token string 通过API Key和Secret Key获取的access_token,参考Access Token获取

Body参数

名称 类型 必填 描述
messages List(message) 聊天上下文信息。说明:
(1)messages成员不能为空,1个成员表示单轮对话,多个成员表示多轮对话;例如:
· 1个成员示例,"messages": [ {"role": "user","content": "你好"}]
· 3个成员示例,"messages": [ {"role": "user","content": "你好"},{"role":"assistant","content":"需要什么帮助"},{"role":"user","content":"自我介绍下"}]
(2)最后一个message为当前请求的信息,前面的message为历史对话信息
(3)成员数目必须为奇数,成员中message的role值说明如下:奇数位message的role值必须为user或function,偶数位message的role值为assistant,第一个message的role不能是function。例如:
示例中message中的role值分别为user、assistant、user、assistant、user;奇数位(红框)message中的role值为user,即第1、3、5个message中的role值为user;偶数位(蓝框)值为assistant,即第2、4个message中的role值为assistant
image.png
(4)message中的content总长度、functions和system字段总内容不能超过20000个字符,且不能超过5120 tokens
functions List(function) 一个可触发函数的描述列表,说明:
(1)支持的function数量无限制
(2)长度限制,最后一个message的content长度(即此轮对话的问题)、functions和system字段总内容不能超过20000个字符,且不能超过5120 tokens
temperature float 说明:
(1)较高的数值会使输出更加随机,而较低的数值会使其更加集中和确定
(2)默认0.8,范围 (0, 1.0],不能为0
top_p float 说明:
(1)影响输出文本的多样性,取值越大,生成文本的多样性越强
(2)默认0.8,取值范围 [0, 1.0]
penalty_score float 通过对已生成的token增加惩罚,减少重复生成的现象。说明:
(1)值越大表示惩罚越大
(2)默认1.0,取值范围:[1.0, 2.0]
stream bool 是否以流式接口的形式返回数据,默认false
system string 模型人设,主要用于人设设定,例如,你是xxx公司制作的AI助手,说明:
(1)长度限制,最后一个message的content长度(即此轮对话的问题)、functions和system字段总内容不能超过20000个字符,且不能超过5120 tokens
(2)如果同时使用system和functions,可能暂无法保证使用效果,持续进行优化
stop List(string) 生成停止标识,当模型生成结果以stop中某个元素结尾时,停止文本生成。说明:
(1)每个元素长度不超过20字符
(2)最多4个元素
disable_search bool 是否强制关闭实时搜索功能,默认false,表示不关闭
enable_citation bool 是否开启上角标返回,说明:
(1)开启后,有概率触发搜索溯源信息search_info,search_info内容见响应参数介绍
(2)默认false,不开启
max_output_tokens int 指定模型最大输出token数,说明:
(1)如果设置此参数,范围[2, 2048]
(2)如果不设置此参数,最大输出token数为1024
response_format string 指定响应内容的格式,说明:
(1)可选值:
· json_object:以json格式返回,可能出现不满足效果情况
· text:以文本格式返回
(2)如果不填写参数response_format值,默认为text
user_id string 表示最终用户的唯一标识符
tool_choice tool_choice 在函数调用场景下,提示大模型选择指定的函数(非强制),说明:指定的函数名必须在functions中存在

message说明

名称 类型 必填 描述
role string 当前支持以下:
user: 表示用户
assistant: 表示对话助手
function: 表示函数
content string 对话内容,说明:
(1)当前message存在function_call,且role="assistant"时可以为空,其他场景不能为空
(2)最后一个message对应的content不能为blank字符,包含空格、"\n"、“\r”、“\f”等
(3)当role为function,content为JSON格式,效果可能更好
name string message作者;当role=function时,必填,且是响应内容中function_call中的name
function_call function_call 函数调用,function call场景下第一轮对话的返回,第二轮对话作为历史信息在message中传入

function说明

functions中function说明如下

名称 类型 必填 描述
name string 函数名
description string 函数描述
parameters object 函数请求参数,说明:
(1)JSON Schema 格式,参考JSON Schema描述
(2)如果函数没有请求参数,parameters值格式如下:
{"type": "object","properties": {}}
responses object 函数响应参数,JSON Schema 格式,参考JSON Schema描述
examples List(example) function调用的一些历史示例,说明:
(1)可以提供正例(正常触发)和反例(无需触发)的example
·正例:从历史请求数据中获取
·反例:
       当role = user,不会触发请求的query
       当role = assistant,有固定的格式。function_call的name为空,arguments是空对象:"{}",thought可以填固定的:"我不需要调用任何工具"
(2)兼容之前的 List(example) 格式

example说明

名称 类型 必填 描述
role string 当前支持以下:
user: 表示用户
assistant: 表示对话助手
function: 表示函数
content string 对话内容,说明:
(1)当前message存在function_call,且role="assistant"时可以为空,其他场景不能为空
(2)最后一个message对应的content不能为blank字符,包含空格、"\n"、“\r”、“\f”等
name string message作者;当role=function时,必填,且是响应内容中function_call中的name
function_call function_call 函数调用,function call场景下第一轮对话的返回,第二轮对话作为历史信息在message中传入

function_call说明

名称 类型 必填 描述
name string 触发的function名
arguments string 请求参数
thoughts string 模型思考过程

tool_choice说明

名称 类型 必填 描述
type string 指定工具类型,function
function function 指定要使用的函数

function说明

tool_choice中function说明如下

名称 类型 必填 描述
name string 指定要使用的函数名

响应说明

名称 类型 描述
id string 本轮对话的id
object string 回包类型
chat.completion:多轮对话返回
created int 时间戳
sentence_id int 表示当前子句的序号。只有在流式接口模式下会返回该字段
is_end bool 表示当前子句是否是最后一句。只有在流式接口模式下会返回该字段
is_truncated bool 当前生成的结果是否被截断
finish_reason string 输出内容标识,说明:
· normal:输出内容完全由大模型生成,未触发截断、替换
· stop:输出结果命中入参stop中指定的字段后被截断
· length:达到了最大的token数,根据EB返回结果is_truncated来截断
· content_filter:输出内容被截断、兜底、替换为**等
· function_call:调用了funtion call功能
search_info search_info 搜索数据,当请求参数enable_citation为true并且触发搜索时,会返回该字段
result string 对话返回结果
need_clear_history bool 表示用户输入是否存在安全风险,是否关闭当前会话,清理历史会话信息
true:是,表示用户输入存在安全风险,建议关闭当前会话,清理历史会话信息
false:否,表示用户输入无安全风险
ban_round int 当need_clear_history为true时,此字段会告知第几轮对话有敏感信息,如果是当前问题,ban_round=-1
usage usage token统计信息
function_call function_call 由模型生成的函数调用,包含函数名称,和调用参数

search_info说明

名称 类型 描述
search_results List(search_result) 搜索结果列表

search_result说明

名称 类型 描述
index int 序号
url string 搜索结果URL
title string 搜索结果标题

usage说明

名称 类型 描述
prompt_tokens int 问题tokens数
completion_tokens int 回答tokens数
total_tokens int tokens总数
plugins List(plugin_usage) plugin消耗的tokens

plugin_usage说明

名称 类型 描述
name string plugin名称,chatFile:chatfile插件消耗的tokens
parse_tokens int 解析文档tokens
abstract_tokens int 摘要文档tokens
search_tokens int 检索文档tokens
total_tokens int 总tokens

function_call说明

名称 类型 描述
name string 触发的function名
thoughts string 模型思考过程
arguments string 请求参数

注意 :同步模式和流式模式,响应参数返回不同,详细内容参考示例描述。

  • 同步模式下,响应参数为以上字段的完整json包。
  • 流式模式下,各字段的响应参数为 data: {响应参数}。

示例

以访问凭证access_token鉴权方式为例,说明如何调用API,示例如下。

请求示例(单轮)

# 步骤一,获取access_token,替换下列示例中的API Key与Secret Key
curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]'

# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=[步骤一调用接口获取的access_token]' -d '{
   "messages": [
    {"role":"user","content":"你好"}
   ]
}' | iconv -f utf-8 -t utf-8
import requests
import json

def get_access_token():
    """
    使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
    """
        
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
    
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main():
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=" + get_access_token()
    
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "你好"
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    print(response.text)
    

if __name__ == '__main__':
    main()

响应示例(单轮)

HTTP/1.1 200 OK
Date: Thu, 23 Mar 2023 03:12:03 GMT
Content-Type: application/json;charset=utf-8
Statement: AI-generated

{
  "id": "as-96grhebivg",
  "object": "chat.completion",
  "created": 1709710806,
  "result": "你好,请问有什么我可以帮助你的吗?无论你有什么问题或需要,我都会尽力回答和提供帮助。",
  "is_truncated": false,
  "need_clear_history": false,
  "finish_reason": "normal",
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 22,
    "total_tokens": 23
  }
}

请求示例(多轮)

# 步骤一,获取access_token,替换下列示例中的API Key与Secret Key
curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]'

# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=[步骤一调用接口获取的access_token]' -d '{
  "messages": [
    {"role":"user","content":"你好"},
    {"role":"assistant","content":"你好,请问有什么我可以帮助你的吗?无论你有什么问题或需要,我都会尽力回答和提供帮助。"},
    {"role":"user","content": "我在上海,周末可以去哪里玩?"},
    {"role":"assistant","content": "上海是一个充满活力和文化氛围的城市,有很多适合周末游玩的地方。以下是几个值得推荐的地方:\n\n1. 上海科技馆:上海科技馆是中国大陆最大的科技馆之一,有许多互动展览和科学实验室,可以让您了解科技的发展历史和最新成果。\n2. 上海博物馆:上海博物馆是一座集艺术、历史和文化于一体的博物馆,有许多精美的艺术品和文物,可以让您深入了解中国和世界的文化历史。\n3. 外滩:外滩是上海的标志性景点之一,有许多高楼大厦和繁华的商业街区,是欣赏黄浦江美景和城市风貌的好去处。\n4. 上海迪士尼乐园:上海迪士尼乐园是世界上最大的迪士尼主题公园之一,有许多精彩的游乐项目和演出,可以让您尽情享受娱乐和欢乐。\n5. 上海野生动物园:上海野生动物园是一个以自然保护为主题的野生动物园,有许多珍稀动物和植物,可以让您近距离接触大自然。\n\n这些地方都是上海周末游玩的好去处,可以根据自己的兴趣和需求选择合适的行程。"},
    {"role":"user","content": "上海有哪些美食?"}
  ]
}'  | iconv -f utf-8 -t utf-8
import requests
import json

def get_access_token():
    """
    使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
    """
        
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
    
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")


def main():
        
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=" + get_access_token()
    
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "你好"
            },
            {
                "role": "assistant",
                "content": "你好,请问有什么我可以帮助你的吗?无论你有什么问题或需要,我都会尽力回答和提供帮助。"
            },
            {
                "role": "user",
                "content": "我在上海,周末可以去哪里玩?"
            },
            {
                "role": "assistant",
                "content": "上海是一个充满活力和文化氛围的城市,有很多适合周末游玩的地方。以下是几个值得推荐的地方:\n\n1. 上海科技馆:上海科技馆是中国大陆最大的科技馆之一,有许多互动展览和科学实验室,可以让您了解科技的发展历史和最新成果。\n2. 上海博物馆:上海博物馆是一座集艺术、历史和文化于一体的博物馆,有许多精美的艺术品和文物,可以让您深入了解中国和世界的文化历史。\n3. 外滩:外滩是上海的标志性景点之一,有许多高楼大厦和繁华的商业街区,是欣赏黄浦江美景和城市风貌的好去处。\n4. 上海迪士尼乐园:上海迪士尼乐园是世界上最大的迪士尼主题公园之一,有许多精彩的游乐项目和演出,可以让您尽情享受娱乐和欢乐。\n5. 上海野生动物园:上海野生动物园是一个以自然保护为主题的野生动物园,有许多珍稀动物和植物,可以让您近距离接触大自然。\n\n这些地方都是上海周末游玩的好去处,可以根据自己的兴趣和需求选择合适的行程。"
            },
            {
                "role": "user",
                "content": "上海有哪些美食?"
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    print(response.text)
    

if __name__ == '__main__':
    main()

响应示例(多轮)

HTTP/1.1 200 OK
Date: Mon, 12 Apr 2021 06:27:55 GMT
Content-Type: application/json;charset=utf-8
Statement: AI-generated

{
  "id": "as-338b6dsazp",
  "object": "chat.completion",
  "created": 1709711025,
  "result": "上海是一个美食之都,拥有许多独特而美味的传统菜肴和小吃。以下是一些上海的美食推荐:\n\n1. 生煎包:生煎包是上海的特色小吃之一,是一种底部酥脆、上部松软的面食,内馅通常为猪肉、皮冻等。\n\n2. 小笼包:小笼包是上海非常有名的小吃,外皮白嫩,内馅鲜美,汤汁丰富,口感极佳。\n\n3. 蟹壳黄:蟹壳黄是一种传统的上海点心,外形酷似蟹壳,口感香脆,内馅有甜、咸两种口味可选。\n\n4. 阳春面:阳春面是上海的传统面食,汤清味鲜,清淡爽口,是春季时节的代表性食品。\n\n5. 油条:油条是上海的传统早餐食品之一,外酥里嫩,香气四溢,常与豆浆、粢饭糕等搭配食用。\n\n6. 白切鸡:白切鸡是上海的传统名菜之一,鸡肉鲜嫩多汁,搭配特制的酱汁,味道鲜美。\n\n除了以上几种美食,上海还有许多其他值得尝试的特色小吃和菜肴,如糖醋排骨、红烧肉、松鼠桂鱼、罗宋汤等。无论是品尝当地特色还是探索新口味,上海的美食文化都能让您留下难忘的回忆。",
  "is_truncated": false,
  "need_clear_history": false,
  "finish_reason": "normal",
  "usage": {
    "prompt_tokens": 253,
    "completion_tokens": 300,
    "total_tokens": 553
  }
}

请求示例(流式)

# 步骤一,获取access_token,替换下列示例中的API Key与Secret Key
curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]'

# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=[步骤一调用接口获取的access_token]' -d '{
  "messages": [
    {"role":"user", "content": "给我推荐一些自驾游路线"}
  ],
  "stream": true
}'
import requests
import json

def get_access_token():
    """
    使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
    """
        
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
    
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")


def main():
        
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=" + get_access_token()
    
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "给我推荐一些自驾游路线"
            }
        ],
         "stream": True
    })
    headers = {
        'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload, stream=True)
    
    for line in response.iter_lines():
        print(line.decode("UTF-8"))
    

if __name__ == '__main__':
    main()

响应示例(流式)

HTTP/1.1 200 OK
Date: Mon, 12 Apr 2021 06:27:55 GMT
Content-Type: text/event-stream;charset=utf-8
Cache-Control: no-cache
Statement: AI-generated

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166793,"sentence_id":0,"is_end":false,is_truncated":false,"result":"以下是一些适合自驾游的路线推荐:\n\n1.","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":16,"total_tokens":27}}

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166794,"sentence_id":1,"is_end":false,is_truncated":false,"result":" 中国大陆最美的景观大道:川藏线,从成都出发,沿着川藏公路一路向西,经过稻城亚丁、理塘、巴塘、芒康等美景,最终到达拉萨。","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":50,"total_tokens":77}}

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166795,"sentence_id":2,"is_end":false,"is_truncated":false,"result":"\n2. 丝绸之路:这是一条贯穿中国东西部的公路,从上海出发,经过西安、兰州、乌鲁木齐等城市,最终到达喀什。","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":43,"total_tokens":120}}

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166796,"sentence_id":3,"is_end":false,"is_truncated":false,"result":"沿途可以欣赏到中国北方和南方的不同景色。\n3. 西北大环线:从成都出发,经过都江堰、青城山、丹巴、塔公草原、新都桥等景点,最终到达西宁。","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":56,"total_tokens":176}}

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166799,"sentence_id":4,"is_end":false,"is_truncated":false,"result":"这条路线可以领略到中国西北地区的壮美风光。\n4. 东北环线:从沈阳出发,经过长春、吉林、延吉等城市,最终到达哈尔滨。","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":48,"total_tokens":224}}

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166800,"sentence_id":5,"is_end":false,"is_truncated":false,"result":"沿途可以欣赏到中国东北地区的广阔草原和森林。\n5. 西南环线:从成都出发,经过雅安、康定、理塘、稻城亚丁等景点,最终到达香格里拉。","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":54,"total_tokens":278}}

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166802,"sentence_id":6,"is_end":false,"is_truncated":false,"result":"这条路线可以领略到中国西南地区的高山峡谷和民族文化。\n6. 海南环线:从三亚出发,经过海口、文昌、万宁等城市,最终到达三亚。","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":52,"total_tokens":330}}

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166803,"sentence_id":7,"is_end":false,"is_truncated":false,"result":"这条路线可以欣赏到中国南方的海岸线和热带雨林。\n7. 滇藏线:从昆明出发,经过大理、丽江、香格里拉等景点,最终到达西藏拉萨。","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":52,"total_tokens":382}}

data: {"id":"as-ywwpgx4dt7","object":"chat.completion","created":1680166804,"sentence_id":8,"is_end":true,"is_truncated":false,"result":"这条路线可以领略到中国西南地区和西藏地区的自然风光和人文景观。","need_clear_history":false,"usage":{"prompt_tokens":11,"completion_tokens":30,"total_tokens":412}}

function call示例(单轮)

第一次请求

# 步骤一,获取access_token,替换下列示例中的API Key与Secret Key
curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]'

# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“

curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=[步骤一调用接口获取的access_token]' -d '{
        "messages": [
      {"role":"user","content":"上海市今天的天气"}
    ],
   "functions": [
        {
            "name": "get_current_weather",
            "description": "获得指定地点的天气",
            "parameters": {
                "type": "object",
                "properties": {
                "location": {
                    "type": "string",
                    "description": "省,市名,例如:河北省,石家庄"
                },
                "unit": {
                    "type": "string",
                    "enum": ["摄氏度", "华氏度"]
                }
                },
                "required": ["location"]
            }
	},
        {
            "name": "get_current_price",
            "description": "获得指定公司的股价",
            "parameters": {
                "type": "object",
                "properties": {
                "company": {
                    "type": "string",
                    "description": "公司名,例如:腾讯,阿里巴巴"
                },
                "exchange": {
                    "type": "string",
                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
                }
                },
                "required": ["company", "exchange"]
            },
            "responses": {
                "type": "object",
                "properties": {
                "price": {
                    "type": "int",
                    "description": "当日股票价格"
                },
                "unit": {
                    "type": "string",
                    "enum": ["人民币", "美元","港币"],
                    "description": "股票价格货币类型"
                },
                "change": {
                    "type": "string",
                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
                }
                }
            },
            "examples": [
        			[
        			     {"role":"user","content":"What is the weather like in Boston?"},
        			     {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}}
        			],
        			[
        			     {"role":"user","content":"你的名字是什么?"},
        			     {"role": "assistant", "content": null, "function_call": {"name": "", "arguments": "{}", "thoughts":"我无需调用任何工具"}}
        			]
            ]
        }
    ],
    "stream":true,
    "tool_choice": {
        "type": "function",
        "function": {
            "name": "get_current_weather"
        }
    }
}' | iconv -f utf-8 -t utf-8

第一次响应

data: {"id":"as-rtpw9dcmef","object":"chat.completion","created":1693449832,"sentence_id":0,"is_end":true,"is_truncated":false,"result":"","need_clear_history":false,"function_call":{"name":"get_current_weather","thoughts":"用户提到了天气,需要调用API来获取天气信息。","arguments":"{\"unit\":\"摄氏度\",\"location\":\"上海市\"}"},"usage":{"prompt_tokens":8,"completion_tokens":46,"total_tokens":54}}

函数调用

curl -X POST 'http://0.0.0.0:80/get_current_weather' -d '{
   "unit": "摄氏度",
   "location": "上海市"
}' | iconv -f utf-8 -t utf-8

函数响应

{
    "temperature": "25", 
    "unit": "摄氏度", 
    "description": "晴朗"
}

第二次请求

# 步骤一,获取access_token,替换下列示例中的API Key与Secret Key
curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]'

# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“

curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=[步骤一调用接口获取的access_token]' -d '{
    "messages": [
      {"role":"user","content":"上海市今天天气如何?"},
      {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"上海市\"}"}},
      {"role": "function", "name": "get_current_weather", "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"}],
   "functions": [
        {
            "name": "get_current_weather",
            "description": "获得指定地点的天气",
            "parameters": {
                "type": "object",
                "properties": {
                "location": {
                    "type": "string",
                    "description": "省,市名,例如:河北省,石家庄"
                },
                "unit": {
                    "type": "string",
                    "enum": ["摄氏度", "华氏度"]
                }
                },
                "required": ["location"]
            }
	},
        {
            "name": "get_current_price",
            "description": "获得指定公司的股价",
            "parameters": {
                "type": "object",
                "properties": {
                "company": {
                    "type": "string",
                    "description": "公司名,例如:腾讯,阿里巴巴"
                },
                "exchange": {
                    "type": "string",
                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
                }
                },
                "required": ["company", "exchange"]
            },
            "responses": {
                "type": "object",
                "properties": {
                "price": {
                    "type": "int",
                    "description": "当日股票价格"
                },
                "unit": {
                    "type": "string",
                    "enum": ["人民币", "美元","港币"],
                    "description": "股票价格货币类型"
                },
                "change": {
                    "type": "string",
                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
                }
                }
            }
        }
    ],
"stream":true
}' | iconv -f utf-8 -t utf-8

第二次响应

data: {"id":"as-kf6e9thk0f","object":"chat.completion","created":1693450180,"sentence_id":0,"is_end":false,"is_truncated":false,"result":"上海市今天天气是:","need_clear_history":false,"usage":{"prompt_tokens":26,"completion_tokens":8,"total_tokens":34}}

data: {"id":"as-kf6e9thk0f","object":"chat.completion","created":1693450180,"sentence_id":1,"is_end":false,"is_truncated":false,"result":"气温25摄氏度,晴朗。","need_clear_history":false,"usage":{"prompt_tokens":26,"completion_tokens":8,"total_tokens":42}}

data: {"id":"as-kf6e9thk0f","object":"chat.completion","created":1693450180,"sentence_id":2,"is_end":true,"is_truncated":false,"result":"","need_clear_history":false,"usage":{"prompt_tokens":26,"completion_tokens":0,"total_tokens":42}}

function call示例(多轮)

第一次请求

# 步骤一,获取access_token,替换下列示例中的API Key与Secret Key
curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]'

# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“

curl -XPOST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=[步骤一调用接口获取的access_token]' -d '{
       "messages": [
        {
            "role": "user",
            "content": "上海市今天天气如何?"
        },
        {
            "role": "assistant",
            "content": null,
            "function_call": {
                "name": "get_current_weather",
                "arguments": "{ \"location\": \"上海市\"}"
            }
        },
        {
            "role": "function",
            "name": "get_current_weather",
            "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"
        },
        {
            "role": "assistant",
            "content": "上海市今天天气是:气温25摄氏度,晴朗。"
        },
        {
            "role": "user",
            "content": "北京市今天天气如何?"
        }
    ],
   "functions": [
        {
            "name": "get_current_weather",
            "description": "获得指定地点的天气",
            "parameters": {
                "type": "object",
                "properties": {
                "location": {
                    "type": "string",
                    "description": "省,市名,例如:河北省,石家庄"
                },
                "unit": {
                    "type": "string",
                    "enum": ["摄氏度", "华氏度"]
                }
                },
                "required": ["location"]
            }
    },
        {
            "name": "get_current_price",
            "description": "获得指定公司的股价",
            "parameters": {
                "type": "object",
                "properties": {
                "company": {
                    "type": "string",
                    "description": "公司名,例如:腾讯,阿里巴巴"
                },
                "exchange": {
                    "type": "string",
                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
                }
                },
                "required": ["company", "exchange"]
            },
            "responses": {
                "type": "object",
                "properties": {
                "price": {
                    "type": "int",
                    "description": "当日股票价格"
                },
                "unit": {
                    "type": "string",
                    "enum": ["人民币", "美元","港币"],
                    "description": "股票价格货币类型"
                },
                "change": {
                    "type": "string",
                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
                }
                }
            },
           "examples": [
                [
                 {"role":"user","content":"What is the weather like in Boston?"},
                 {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}}
                ],
                [
                     {"role":"user","content":"你的名字是什么?"},
                 {"role": "assistant", "content": null, "function_call": {"name": "", "arguments": "{}", "thoughts":"我无需调用任何工具"}}
                ]
            ]
        }
    ],
    "stream":true,
    "tool_choice": {
        "type": "function",
        "function": {
            "name": "get_current_weather"
        }
    }
}' | iconv -f utf-8 -t utf-8

第一次响应

data: {"id":"as-cp6rrapzdp","object":"chat.completion","created":1701421831,"sentence_id":0,"is_end":true,"is_truncated":false,"result":"","need_clear_history":false,"function_call":{"name":"get_current_weather","thoughts":"用户询问了北京市今天的天气,我需要使用get_current_weather工具来获取相关信息。","arguments":"{\"location\":\"北京市\"}"},"finish_reason":"function_call","usage":{"prompt_tokens":43,"completion_tokens":0,"total_tokens":43}}

函数调用

curl -XPOST http://0.0.0.0:80/get_current_weather -d '{
   "unit": "摄氏度",
   "location": "北京市"
}' | iconv -f utf-8 -t utf-8

函数响应

{
    "temperature": "-1", 
    "unit": "摄氏度", 
    "description": "大雪"
}

第二次请求

# 步骤一,获取access_token,替换下列示例中的API Key与Secret Key
curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[API Key]&client_secret=[Secret Key]'

# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“

curl -XPOST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=[步骤一调用接口获取的access_token]' -d '{
        "messages": [
        {
            "role": "user",
            "content": "上海市今天天气如何?"
        },
        {
            "role": "assistant",
            "content": null,
            "function_call": {
                "name": "get_current_weather",
                "arguments": "{ \"location\": \"上海市\"}"
            }
        },
        {
            "role": "function",
            "name": "get_current_weather",
            "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"
        },
        {
            "role": "assistant",
            "content": "上海市今天天气是:气温25摄氏度,晴朗。"
        },
        {
            "role": "user",
            "content": "北京市今天天气如何?"
        },
        {
            "role": "assistant",
            "content": null,
            "function_call": {
                "name": "get_current_weather",
                "arguments": "{ \"location\": \"北京市\"}"
            }
        },
        {
            "role": "function",
            "name": "get_current_weather",
            "content": "{\"temperature\": \"-1\", \"unit\": \"摄氏度\", \"description\": \"大雪\"}"
        }
    ],
   "functions": [
        {
            "name": "get_current_weather",
            "description": "获得指定地点的天气",
            "parameters": {
                "type": "object",
                "properties": {
                "location": {
                    "type": "string",
                    "description": "省,市名,例如:河北省,石家庄"
                },
                "unit": {
                    "type": "string",
                    "enum": ["摄氏度", "华氏度"]
                }
                },
                "required": ["location"]
            }
    },
        {
            "name": "get_current_price",
            "description": "获得指定公司的股价",
            "parameters": {
                "type": "object",
                "properties": {
                "company": {
                    "type": "string",
                    "description": "公司名,例如:腾讯,阿里巴巴"
                },
                "exchange": {
                    "type": "string",
                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
                }
                },
                "required": ["company", "exchange"]
            },
            "responses": {
                "type": "object",
                "properties": {
                "price": {
                    "type": "int",
                    "description": "当日股票价格"
                },
                "unit": {
                    "type": "string",
                    "enum": ["人民币", "美元","港币"],
                    "description": "股票价格货币类型"
                },
                "change": {
                    "type": "string",
                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
                }
                }
            },
            "examples": [
                    [
                     {"role":"user","content":"What is the weather like in Boston?"},
                     {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}}
                    ],
                    [
                     {"role":"user","content":"你的名字是什么?"},
                     {"role": "assistant", "content": null, "function_call": {"name": "", "arguments": "{}", "thoughts":"我无需调用任何工具"}}
                    ]
            ]
        }
    ],
    "stream":true,
    "tool_choice": {
        "type": "function",
        "function": {
            "name": "get_current_weather"
        }
    }
}' | iconv -f utf-8 -t utf-8

第二次响应

data: {"id":"as-jp2fqncxhk","object":"chat.completion","created":1701422332,"sentence_id":0,"is_end":false,"is_truncated":false,"result":"根据天气预报,北京市","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":62,"completion_tokens":0,"total_tokens":62}}

data: {"id":"as-jp2fqncxhk","object":"chat.completion","created":1701422333,"sentence_id":1,"is_end":false,"is_truncated":false,"result":"今天天气是:气温-1摄氏度,大雪。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":62,"completion_tokens":0,"total_tokens":62}}

data: {"id":"as-jp2fqncxhk","object":"chat.completion","created":1701422333,"sentence_id":2,"is_end":false,"is_truncated":false,"result":"如果您需要了解更多天气信息或有其他问题,请随时告诉我。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":62,"completion_tokens":0,"total_tokens":62}}

data: {"id":"as-jp2fqncxhk","object":"chat.completion","created":1701422333,"sentence_id":3,"is_end":true,"is_truncated":false,"result":"","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":62,"completion_tokens":31,"total_tokens":93}}

错误码

如果请求错误,服务器返回的JSON文本包含以下参数。

名称 描述
error_code 错误码
error_msg 错误描述信息,帮助理解和解决发生的错误

例如Access Token失效返回以下内容,需要重新获取新的Access Token再次请求。

{
  "error_code": 110,
  "error_msg": "Access token invalid or no longer valid"
}

更多相关错误码,请查看错误码说明