ERNIE-3.5-8K-Preview
ERNIE 3.5是百度自研的旗舰级大规模⼤语⾔模型,覆盖海量中英文语料,具有强大的通用能力,可满足绝大部分对话问答、创作生成、插件应用场景要求;支持自动对接百度搜索插件,保障问答信息时效。ERNIE-3.5-8K-Preview为ERNIE-3.5-8K模型的预览版本,指向最新版本模型。本文介绍了相关API。
接口描述
调用本接口,发起一次对话请求。
注意事项
模型版本说明:-Preview,表示预览版接口,指向最新版本的模型。Preview接口滚动升级不会提前通知用户,用户可以在模型版本升级及退役机制文档查看当前最新指向日期。
在线调试
平台提供了 API在线调试平台-示例代码 ,用于帮助开发者调试接口,平台集成快速检索、查看开发文档、查看在线调用的请求内容和返回结果、复制和下载示例代码等功能,简单易用,更多内容请查看API在线调试介绍。
鉴权说明
本文API,支持2种鉴权方式。不同鉴权方式,调用方式不同,请求头域、请求参数的Query参数不同,详见本文请求说明。开发者可以选择以下任一种方式进行鉴权。
· 访问凭证access_token鉴权
· 基于安全认证AK/SK进行签名计算鉴权
请求结构
以访问凭证access_token鉴权方式为例,说明调用API请求结构,示例如下。
1POST /rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=24.4a3a19b******18992 HTTP/1.1
2Host: aip.baidubce.com
3Content-Type: application/json
4
5{
6  "messages": [
7    {"role":"user","content":"你好"}
8   ]
9}
            请求头域
除公共头域外,无其它特殊头域。注意:鉴权方式不同,对应请求头域不同。
请求参数
- 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   (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 | 
| enable_system_memory | bool | 否 | 是否开启系统记忆,说明: (1)false:未开启,默认false (2)true:表示开启,开启后,system_memory_id字段必填  | 
| system_memory_id | string | 否 | 系统记忆ID,说明: (1)用于读取对应ID下的系统记忆,读取到的记忆文本内容会拼接message参与请求推理 (2)通过调用创建系统记忆接口,返回的result字段获取  | 
| 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 | 否 | 是否强制关闭实时搜索功能,可选值: · true:关闭 · false:表示不关闭,默认false,计费问题可查看常见问题  | 
| enable_citation | bool | 否 | 是否开启上角标返回,说明: (1)开启后,有概率触发搜索溯源信息search_info,search_info内容见响应参数介绍 (2)默认false,不开启 (3)注意:本字段不控制是否关闭实时搜索功能,该功能请参见disable_search字段。如果设置了disable_search=true,那么本字段无效  | 
| enable_trace | bool | 否 | 是否返回搜索溯源信息,说明: (1)如果开启,在触发了搜索增强的场景下,会返回搜索溯源信息search_info,search_info内容见响应参数介绍 (2)默认false,表示不返回 (3)注意:本字段不控制是否关闭实时搜索功能,该功能请参见disable_search字段。如果设置了disable_search=true,那么本字段无效  | 
| max_output_tokens | int | 否 | 指定模型最大输出token数,说明: (1)如果设置此参数,范围[2, 2048] (2)如果不设置此参数,最大输出token数为1024  | 
| response_format | string | 否 | 指定响应内容的格式,说明: (1)可选值: · json_object:以json格式返回,可能出现不满足效果情况 · text:以文本格式返回 (2)如果不填写参数response_format值,默认为text  | 
| user_ip | string | 否 | 用户IP,可用于推测用户位置等 | 
| user_id | string | 否 | 表示最终用户的唯一标识符 | 
| tool_choice | tool_choice | 否 | 在函数调用场景下,提示大模型选择指定的函数(非强制),说明:指定的函数名必须在functions中存在 | 
| metadata | map<string,string> | 否 | 说明: (1)元素个数最大支持16个 (2)key和value必须都是string类型  | 
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(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 | 是 | 指定要使用的函数名 | 
响应头域
除公共头域外,部分头域如下。
| 名称 | 描述 | 
|---|---|
| X-Ratelimit-Limit-Requests | 一分钟内允许的最大请求次数 | 
| X-Ratelimit-Limit-Tokens | 一分钟内允许的最大tokens消耗,包含输入tokens和输出tokens | 
| X-Ratelimit-Remaining-Requests | 达到RPM速率限制前,剩余可发送的请求数配额,如果配额用完,将会在0-60s后刷新 | 
| X-Ratelimit-Remaining-Tokens | 达到TPM速率限制前,剩余可消耗的tokens数配额,如果配额用完,将会在0-60s后刷新 | 
响应参数
| 名称 | 类型 | 描述 | 
|---|---|---|
| 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或enable_trace为true,并且触发搜索时,会返回该字段 | 
| result | string | 对话返回结果 | 
| need_clear_history | bool | 表示用户输入是否存在安全风险,是否关闭当前会话,清理历史会话信息 · true:是,表示用户输入存在安全风险,建议关闭当前会话,清理历史会话信息 · false:否,表示用户输入无安全风险  | 
| flag | int | 说明:返回flag表示触发安全 | 
| 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数,说明: (1)如果未触发独立搜索,指用户输入原始问题tokens数 (2)如果触发独立搜索,问题tokens数包括用户输入问题token数和触发搜索相关的tokens数  | 
| completion_tokens | int | 回答tokens数 | 
| total_tokens | int | tokens总数 | 
| prompt_tokens_details | Object | 问题tokens数详情 | 
| search_count | int | 触发独立搜索计费次数 | 
prompt_tokens_details说明
| 名称 | 类型 | 描述 | 
|---|---|---|
| search_tokens | int | 搜索独立计费tokens数 | 
function_call说明
| 名称 | 类型 | 描述 | 
|---|---|---|
| name | string | 触发的function名 | 
| thoughts | string | 模型思考过程 | 
| arguments | string | 请求参数 | 
注意 :同步模式和流式模式,响应参数返回不同,详细内容参考示例描述。
- 同步模式下,响应参数为以上字段的完整json包。
 - 流式模式下,各字段的响应参数为 data: {响应参数}。
 
请求示例(单轮)
以访问凭证access_token鉴权方式为例,说明如何调用API,示例如下。
1# 步骤一,获取access_token,替换下列示例中的应用API Key与应用Secret Key
2curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]'
3
4# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
5curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=[步骤一调用接口获取的access_token]' -d '{
6   "messages": [
7    {"role":"user","content":"你好"}
8   ]
9}'
        1import requests
2import json
3
4def get_access_token():
5    """
6    使用应用API Key,应用Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
7    """
8        
9    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
10    
11    payload = json.dumps("")
12    headers = {
13        'Content-Type': 'application/json',
14        'Accept': 'application/json'
15    }
16    
17    response = requests.request("POST", url, headers=headers, data=payload)
18    return response.json().get("access_token")
19
20def main():
21    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=" + get_access_token()
22    
23    payload = json.dumps({
24        "messages": [
25            {
26                "role": "user",
27                "content": "你好"
28            }
29        ]
30    })
31    headers = {
32        'Content-Type': 'application/json'
33    }
34    
35    response = requests.request("POST", url, headers=headers, data=payload)
36    
37    print(response.text)
38    
39
40if __name__ == '__main__':
41    main()
        响应示例(单轮)
1HTTP/1.1 200 OK
2Date: Fri, 19 Jan 2024 08:49:13 GMT
3Content-Type: application/json;charset=utf-8
4Statement: AI-generated
5X-Ratelimit-Limit-Requests: 300 
6X-Ratelimit-Limit-Tokens: 300000
7X-Ratelimit-Remaining-Requests: 298
8X-Ratelimit-Remaining-Tokens: 299971
9     
10{
11  "id": "as-61qu1k9xvf",
12  "object": "chat.completion",
13  "created": 1709711333,
14  "result": "你好,请问有什么我可以帮助你的吗?无论你有什么问题或需要帮助,我都会尽力回答和协助你。请随时告诉我你的需求。",
15  "is_truncated": false,
16  "need_clear_history": false,
17  "finish_reason": "normal",
18  "usage": {
19    "prompt_tokens": 1,
20    "completion_tokens": 29,
21    "total_tokens": 30
22  }
23}
            请求示例(多轮)
1# 步骤一,获取access_token,替换下列示例中的应用API Key与应用Secret Key
2curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]'
3
4# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
5curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=[步骤一调用接口获取的access_token]' -d '{
6  "messages": [
7    {"role":"user","content":"你好"},
8    {"role":"assistant","content":"你好,请问有什么我可以帮助你的吗?无论你有什么问题或需要帮助,我都会尽力回答和协助你。请随时告诉我你的需求。"},
9    {"role":"user","content": "我在上海,周末可以去哪里玩?"},
10    {"role":"assistant","content": "上海是一个充满活力和文化氛围的城市,有很多适合周末游玩的地方。以下是几个值得推荐的地方:\n\n1. 上海科技馆:上海科技馆是中国大陆最大的科技馆之一,有许多互动展览和科学实验室,可以让您了解科技的发展历史和最新成果。\n2. 上海博物馆:上海博物馆是一座集艺术、历史和文化于一体的博物馆,有许多精美的艺术品和文物,可以让您深入了解中国和世界的文化历史。\n3. 外滩:外滩是上海的标志性景点之一,有许多高楼大厦和繁华的商业街区,是欣赏黄浦江美景和城市风貌的好去处。\n4. 上海迪士尼乐园:上海迪士尼乐园是世界上最大的迪士尼主题公园之一,有许多精彩的游乐项目和演出,可以让您尽情享受娱乐和欢乐。\n5. 上海野生动物园:上海野生动物园是一个以自然保护为主题的野生动物园,有许多珍稀动物和植物,可以让您近距离接触大自然。\n\n这些地方都是上海周末游玩的好去处,可以根据自己的兴趣和需求选择合适的行程。"},
11    {"role":"user","content": "上海有哪些美食"}
12  ]
13}'
        1import requests
2import json
3
4def get_access_token():
5    """
6    使用应用API Key,应用Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
7    """
8        
9    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
10    
11    payload = json.dumps("")
12    headers = {
13        'Content-Type': 'application/json',
14        'Accept': 'application/json'
15    }
16    
17    response = requests.request("POST", url, headers=headers, data=payload)
18    return response.json().get("access_token")
19
20
21def main():
22        
23    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=" + get_access_token()
24    
25    payload = json.dumps({
26        "messages": [
27            {
28                "role": "user",
29                "content": "你好"
30            },
31            {
32                "role": "assistant",
33                "content": "你好,请问有什么我可以帮助你的吗?无论你有什么问题或需要帮助,我都会尽力回答和协助你。请随时告诉我你的需求。"
34            },
35            {
36                "role": "user",
37                "content": "我在上海,周末可以去哪里玩?"
38            },
39            {
40                "role": "assistant",
41                "content": "上海是一个充满活力和文化氛围的城市,有很多适合周末游玩的地方。以下是几个值得推荐的地方:\n\n1. 上海科技馆:上海科技馆是中国大陆最大的科技馆之一,有许多互动展览和科学实验室,可以让您了解科技的发展历史和最新成果。\n2. 上海博物馆:上海博物馆是一座集艺术、历史和文化于一体的博物馆,有许多精美的艺术品和文物,可以让您深入了解中国和世界的文化历史。\n3. 外滩:外滩是上海的标志性景点之一,有许多高楼大厦和繁华的商业街区,是欣赏黄浦江美景和城市风貌的好去处。\n4. 上海迪士尼乐园:上海迪士尼乐园是世界上最大的迪士尼主题公园之一,有许多精彩的游乐项目和演出,可以让您尽情享受娱乐和欢乐。\n5. 上海野生动物园:上海野生动物园是一个以自然保护为主题的野生动物园,有许多珍稀动物和植物,可以让您近距离接触大自然。\n\n这些地方都是上海周末游玩的好去处,可以根据自己的兴趣和需求选择合适的行程。"
42            },
43            {
44                "role": "user",
45                "content": "上海有哪些美食"
46            }
47        ]
48    })
49    headers = {
50        'Content-Type': 'application/json'
51    }
52    
53    response = requests.request("POST", url, headers=headers, data=payload)
54    
55    print(response.text)
56    
57
58if __name__ == '__main__':
59    main()
        响应示例(多轮)
1HTTP/1.1 200 OK
2Date: Wed, 28 Feb 2024 02:04:30 GMT
3Content-Type: application/json;charset=utf-8
4Statement: AI-generated
5X-Ratelimit-Limit-Requests: 300
6X-Ratelimit-Limit-Tokens: 300000
7X-Ratelimit-Remaining-Requests: 299
8X-Ratelimit-Remaining-Tokens: 299741
9
10{
11  "id": "as-g1mtr4p03c",
12  "object": "chat.completion",
13  "created": 1709711455,
14  "result": "上海是一个美食之都,拥有许多独特的地方特色菜肴和小吃。以下是一些上海的美食推荐:\n\n1. 生煎包:生煎包是上海的特色小吃之一,底部酥脆,上部松软,馅料鲜美,深受当地人喜爱。\n\n2. 南翔小笼包:南翔小笼包是上海的著名特色小吃,皮薄馅嫩,汤汁丰富,味道鲜美,是品尝上海传统美食的必选之一。\n\n3. 白斩鸡:白斩鸡是上海菜中的一道经典菜肴,鸡肉鲜嫩多汁,口感滑爽,搭配上调料食用更佳。\n\n4. 油条:油条是上海的传统早餐食品之一,外酥里嫩,香气四溢,搭配豆浆或豆腐脑食用更佳。\n\n5. 蟹壳黄:蟹壳黄是一种上海传统小吃,因其形似蟹壳而得名,口感香脆,馅料丰富,有甜、咸两种口味可选。\n\n6. 咸豆花:咸豆花是上海的传统小吃之一,豆花口感细腻,搭配咸味的调料和配料,味道独特而美味。\n\n除了以上几种美食,上海还有许多其他特色小吃和菜肴,如糖醋排骨、红烧肉、松鼠桂鱼、罗宋汤等。无论您是美食家还是普通游客,都可以在上海找到满足自己味蕾的美食佳肴。",
15  "is_truncated": false,
16  "need_clear_history": false,
17  "finish_reason": "normal",
18  "usage": {
19    "prompt_tokens": 259,
20    "completion_tokens": 306,
21    "total_tokens": 565
22  }
23}
            请求示例(流式)
1# 步骤一,获取access_token,替换下列示例中的应用API Key与应用Secret Key
2curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]'
3
4# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
5curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=[步骤一调用接口获取的access_token]' -d '{
6  "messages": [
7    {"role":"user", "content": "给我推荐一些自驾游路线"}
8  ],
9  "stream": true
10}'
        1import requests
2import json
3
4def get_access_token():
5    """
6    使用应用API Key,应用Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
7    """
8        
9    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
10    
11    payload = json.dumps("")
12    headers = {
13        'Content-Type': 'application/json',
14        'Accept': 'application/json'
15    }
16    
17    response = requests.request("POST", url, headers=headers, data=payload)
18    return response.json().get("access_token")
19
20
21def main():
22        
23    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=" + get_access_token()
24    
25    payload = json.dumps({
26        "messages": [
27            {
28                "role": "user",
29                "content": "给我推荐一些自驾游路线"
30            }
31        ],
32         "stream": True
33    })
34    headers = {
35        'Content-Type': 'application/json'
36    }
37    
38    response = requests.request("POST", url, headers=headers, data=payload, stream=True)
39    
40    for line in response.iter_lines():
41        print(line.decode("UTF-8"))
42    
43
44if __name__ == '__main__':
45    main()
        响应示例(流式)
1HTTP/1.1 200 OK
2Date: Wed, 28 Feb 2024 02:02:31 GMT
3Content-Type: text/event-stream;charset=utf-8
4Cache-Control: no-cache
5Statement: AI-generated
6X-Ratelimit-Limit-Requests: 300
7X-Ratelimit-Limit-Tokens: 300000
8X-Ratelimit-Remaining-Requests: 299
9X-Ratelimit-Remaining-Tokens: 299994
10
11data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085751,"sentence_id":0,"is_end":false,"is_truncated":false,"result":"当然可以","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":0,"total_tokens":6}}
12data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085752,"sentence_id":1,"is_end":false,"is_truncated":false,"result":",以下是一些建议的自驾游路线:\n\n1. **丝绸之路自驾游**:西安出发,经过天水、兰州、嘉峪关","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":0,"total_tokens":6}}
13data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085752,"sentence_id":2,"is_end":false,"is_truncated":false,"result":"、敦煌,最后到达哈密和乌鲁木齐。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":0,"total_tokens":6}}
14data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085752,"sentence_id":3,"is_end":false,"is_truncated":false,"result":"这条路线将带你领略古代丝绸之路的辉煌和壮丽。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":0,"total_tokens":6}}
15data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085753,"sentence_id":4,"is_end":false,"is_truncated":false,"result":"\n2. **海南环岛自驾**:这是一条热带天堂的自驾路线,你可以尽情享受海南的美丽海滩和热带风情。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":0,"total_tokens":6}}
16data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085754,"sentence_id":5,"is_end":false,"is_truncated":false,"result":"\n3. **穿越阿里大北线**:成都出发,经过广元、汉中、西安、延安、银川、阿拉善左","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":0,"total_tokens":6}}
17data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085754,"sentence_id":6,"is_end":false,"is_truncated":false,"result":"旗等地,最后回到成都。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":0,"total_tokens":6}}
18data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085755,"sentence_id":7,"is_end":false,"is_truncated":false,"result":"这条路线将带你穿越中国的大西北,感受高原的壮丽和神秘。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":0,"total_tokens":6}}
19data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085756,"sentence_id":8,"is_end":false,"is_truncated":false,"result":"\n4. **寻找那北方的净土——自驾阿尔山**:北京出发,经过张家口、张北、太仆寺旗等地","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":176,"total_tokens":182}}
20data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085756,"sentence_id":9,"is_end":false,"is_truncated":false,"result":",最后到达阿尔山。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":176,"total_tokens":182}}
21data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085757,"sentence_id":10,"is_end":false,"is_truncated":false,"result":"这条路线将带你领略北方的自然风光和纯净之美。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":176,"total_tokens":182}}
22data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085757,"sentence_id":11,"is_end":false,"is_truncated":false,"result":"\n\n这些路线各具特色,可以满足不同人群的需求。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":176,"total_tokens":182}}
23data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085758,"sentence_id":12,"is_end":false,"is_truncated":false,"result":"无论你喜欢历史人文、自然风光还是热带风情,都可以在这些路线中找到满意的旅程。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":176,"total_tokens":182}}
24data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085759,"sentence_id":13,"is_end":false,"is_truncated":false,"result":"在计划行程时,记得留出时间来享受路途中的风景,这样你的自驾游体验将更加丰富和难忘。","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":176,"total_tokens":182}}
25data: {"id":"as-0gcrii0a9k","object":"chat.completion","created":1709085759,"sentence_id":14,"is_end":true,"is_truncated":false,"result":"","need_clear_history":false,"finish_reason":"normal","usage":{"prompt_tokens":6,"completion_tokens":255,"total_tokens":261}}
            function call示例(单轮)
- 第一次请求
 
1# 步骤一,获取access_token,替换下列示例中的应用API Key与应用Secret Key
2curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]'
3
4# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
5
6curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=[步骤一调用接口获取的access_token]' -d '{
7        "messages": [
8      {"role":"user","content":"上海市今天的天气"}
9    ],
10   "functions": [
11        {
12            "name": "get_current_weather",
13            "description": "获得指定地点的天气",
14            "parameters": {
15                "type": "object",
16                "properties": {
17                "location": {
18                    "type": "string",
19                    "description": "省,市名,例如:河北省,石家庄"
20                },
21                "unit": {
22                    "type": "string",
23                    "enum": ["摄氏度", "华氏度"]
24                }
25                },
26                "required": ["location"]
27            }
28	},
29        {
30            "name": "get_current_price",
31            "description": "获得指定公司的股价",
32            "parameters": {
33                "type": "object",
34                "properties": {
35                "company": {
36                    "type": "string",
37                    "description": "公司名,例如:腾讯,阿里巴巴"
38                },
39                "exchange": {
40                    "type": "string",
41                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
42                }
43                },
44                "required": ["company", "exchange"]
45            },
46            "responses": {
47                "type": "object",
48                "properties": {
49                "price": {
50                    "type": "int",
51                    "description": "当日股票价格"
52                },
53                "unit": {
54                    "type": "string",
55                    "enum": ["人民币", "美元","港币"],
56                    "description": "股票价格货币类型"
57                },
58                "change": {
59                    "type": "string",
60                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
61                }
62                }
63            },
64            "examples": [
65        			[
66        			     {"role":"user","content":"What is the weather like in Boston?"},
67        			     {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}}
68        			],
69        			[
70        			     {"role":"user","content":"你的名字是什么?"},
71        			     {"role": "assistant", "content": null, "function_call": {"name": "", "arguments": "{}", "thoughts":"我无需调用任何工具"}}
72        			]
73            ]
74        }
75    ],
76    "stream":true,
77    "tool_choice": {
78        "type": "function",
79        "function": {
80            "name": "get_current_weather"
81        }
82    }
83}'
        1import requests
2import json
3
4
5def get_access_token():
6    """
7    使用应用API Key,应用Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
8    """
9
10    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
11
12    payload = json.dumps("")
13    headers = {
14        'Content-Type': 'application/json',
15        'Accept': 'application/json'
16    }
17
18    response = requests.request("POST", url, headers=headers, data=payload)
19    return response.json().get("access_token")
20
21
22def main():
23    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=" + get_access_token()
24
25    payload = json.dumps({
26        "messages": [
27            {"role": "user", "content": "上海市今天的天气"}
28        ],
29        "functions": [
30            {
31                "name": "get_current_weather",
32                "description": "获得指定地点的天气",
33                "parameters": {
34                    "type": "object",
35                    "properties": {
36                        "location": {
37                            "type": "string",
38                            "description": "省,市名,例如:河北省,石家庄"
39                        },
40                        "unit": {
41                            "type": "string",
42                            "enum": ["摄氏度", "华氏度"]
43                        }
44                    },
45                    "required": ["location"]
46                }
47            },
48            {
49                "name": "get_current_price",
50                "description": "获得指定公司的股价",
51                "parameters": {
52                    "type": "object",
53                    "properties": {
54                        "company": {
55                            "type": "string",
56                            "description": "公司名,例如:腾讯,阿里巴巴"
57                        },
58                        "exchange": {
59                            "type": "string",
60                            "enum": ["纳斯达克", "上海证券交易所", "香港证券交易所"]
61                        }
62                    },
63                    "required": ["company", "exchange"]
64                },
65                "responses": {
66                    "type": "object",
67                    "properties": {
68                        "price": {
69                            "type": "int",
70                            "description": "当日股票价格"
71                        },
72                        "unit": {
73                            "type": "string",
74                            "enum": ["人民币", "美元", "港币"],
75                            "description": "股票价格货币类型"
76                        },
77                        "change": {
78                            "type": "string",
79                            "description": "当日股票价格变化,如下跌3%,上涨0.5%"
80                        }
81                    }
82                },
83                "examples": [
84                    [
85                        {"role": "user", "content": "What is the weather like in Boston?"},
86                        {"role": "assistant", "content": None,
87                         "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}}
88                    ],
89                    [
90                        {"role": "user", "content": "你的名字是什么?"},
91                        {"role": "assistant", "content": None,
92                         "function_call": {"name": "", "arguments": "{}", "thoughts": "我无需调用任何工具"}}
93                    ]
94                ]
95            }
96        ],
97        "stream": True,
98        "tool_choice": {
99            "type": "function",
100            "function": {
101                "name": "get_current_weather"
102            }
103        }
104
105    },ensure_ascii=False)
106    headers = {
107        'Content-Type': 'application/json'
108    }
109
110    response = requests.request("POST", url, headers=headers, data=payload.encode('utf8'))
111
112    print(response.text)
113
114
115
116if __name__ == '__main__':
117    main()
        - 第一次响应
 
1data: {"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}}
            - 函数调用
 
1curl -X POST 'http://0.0.0.0:80/get_current_weather' -d '{
2   "unit": "摄氏度",
3   "location": "上海市"
4}'
        1import requests
2import json
3
4
5def main():
6    """
7    替换下列示例函数内容
8    """
9    url = "http://0.0.0.0:80/get_current_weather"
10
11    payload = json.dumps({
12        "unit": "摄氏度",
13        "location": "上海市"
14    },ensure_ascii=False)
15    headers = {
16        'Content-Type': 'application/json'
17    }
18
19    response = requests.request("POST", url, headers=headers, data=payload.encode('utf8'))
20
21    print(response.text)
22
23
24if __name__ == '__main__':
25    main()
        - 函数响应
 
1{
2    "temperature": "25", 
3    "unit": "摄氏度", 
4    "description": "晴朗"
5}
            - 第二次请求
 
1# 步骤一,获取access_token,替换下列示例中的应用API Key与应用Secret Key
2curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]'
3
4# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
5
6curl -X POST 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=[步骤一调用接口获取的access_token]' -d '{
7    "messages": [
8      {"role":"user","content":"上海市今天天气如何?"},
9      {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"上海市\"}"}},
10      {"role": "function", "name": "get_current_weather", "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"}],
11   "functions": [
12        {
13            "name": "get_current_weather",
14            "description": "获得指定地点的天气",
15            "parameters": {
16                "type": "object",
17                "properties": {
18                "location": {
19                    "type": "string",
20                    "description": "省,市名,例如:河北省,石家庄"
21                },
22                "unit": {
23                    "type": "string",
24                    "enum": ["摄氏度", "华氏度"]
25                }
26                },
27                "required": ["location"]
28            }
29	},
30        {
31            "name": "get_current_price",
32            "description": "获得指定公司的股价",
33            "parameters": {
34                "type": "object",
35                "properties": {
36                "company": {
37                    "type": "string",
38                    "description": "公司名,例如:腾讯,阿里巴巴"
39                },
40                "exchange": {
41                    "type": "string",
42                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
43                }
44                },
45                "required": ["company", "exchange"]
46            },
47            "responses": {
48                "type": "object",
49                "properties": {
50                "price": {
51                    "type": "int",
52                    "description": "当日股票价格"
53                },
54                "unit": {
55                    "type": "string",
56                    "enum": ["人民币", "美元","港币"],
57                    "description": "股票价格货币类型"
58                },
59                "change": {
60                    "type": "string",
61                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
62                }
63                }
64            }
65        }
66    ],
67"stream":true
68}'
        1import requests
2import json
3
4
5def get_access_token():
6    """
7    使用应用API Key,应用Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
8    """
9
10    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
11
12    payload = json.dumps("")
13    headers = {
14        'Content-Type': 'application/json',
15        'Accept': 'application/json'
16    }
17
18    response = requests.request("POST", url, headers=headers, data=payload)
19    return response.json().get("access_token")
20
21
22def main():
23    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=" + get_access_token()
24
25    payload = json.dumps({
26        "messages": [
27            {"role": "user", "content": "上海市今天天气如何?"},
28            {"role": "assistant", "content": None,
29             "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"上海市\"}"}},
30            {"role": "function", "name": "get_current_weather",
31             "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"}],
32        "functions": [
33            {
34                "name": "get_current_weather",
35                "description": "获得指定地点的天气",
36                "parameters": {
37                    "type": "object",
38                    "properties": {
39                        "location": {
40                            "type": "string",
41                            "description": "省,市名,例如:河北省,石家庄"
42                        },
43                        "unit": {
44                            "type": "string",
45                            "enum": ["摄氏度", "华氏度"]
46                        }
47                    },
48                    "required": ["location"]
49                }
50            },
51            {
52                "name": "get_current_price",
53                "description": "获得指定公司的股价",
54                "parameters": {
55                    "type": "object",
56                    "properties": {
57                        "company": {
58                            "type": "string",
59                            "description": "公司名,例如:腾讯,阿里巴巴"
60                        },
61                        "exchange": {
62                            "type": "string",
63                            "enum": ["纳斯达克", "上海证券交易所", "香港证券交易所"]
64                        }
65                    },
66                    "required": ["company", "exchange"]
67                },
68                "responses": {
69                    "type": "object",
70                    "properties": {
71                        "price": {
72                            "type": "int",
73                            "description": "当日股票价格"
74                        },
75                        "unit": {
76                            "type": "string",
77                            "enum": ["人民币", "美元", "港币"],
78                            "description": "股票价格货币类型"
79                        },
80                        "change": {
81                            "type": "string",
82                            "description": "当日股票价格变化,如下跌3%,上涨0.5%"
83                        }
84                    }
85                }
86            }
87        ],
88        "stream": True
89    },ensure_ascii=False)
90    headers = {
91        'Content-Type': 'application/json'
92    }
93
94    response = requests.request("POST", url, headers=headers, data=payload.encode('utf8'))
95
96    print(response.text)
97
98
99if __name__ == '__main__':
100    main()
        - 第二次响应
 
1data: {"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}}
2data: {"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}}
3data: {"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示例(多轮)
- 第一次请求
 
1# 步骤一,获取access_token,替换下列示例中的应用API Key与应用Secret Key
2curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]'
3
4# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
5
6curl -X POST https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=[步骤一调用接口获取的access_token] -d '{
7        "messages": [
8        {
9            "role": "user",
10            "content": "上海市今天天气如何?"
11        },
12        {
13            "role": "assistant",
14            "content": null,
15            "function_call": {
16                "name": "get_current_weather",
17                "arguments": "{ \"location\": \"上海市\"}"
18            }
19        },
20        {
21            "role": "function",
22            "name": "get_current_weather",
23            "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"
24        },
25        {
26            "role": "assistant",
27            "content": "上海市今天天气是:气温25摄氏度,晴朗。"
28        },
29        {
30            "role": "user",
31            "content": "北京市今天天气如何?"
32        }
33    ],
34   "functions": [
35        {
36            "name": "get_current_weather",
37            "description": "获得指定地点的天气",
38            "parameters": {
39                "type": "object",
40                "properties": {
41                "location": {
42                    "type": "string",
43                    "description": "省,市名,例如:河北省,石家庄"
44                },
45                "unit": {
46                    "type": "string",
47                    "enum": ["摄氏度", "华氏度"]
48                }
49                },
50                "required": ["location"]
51            }
52    },
53        {
54            "name": "get_current_price",
55            "description": "获得指定公司的股价",
56            "parameters": {
57                "type": "object",
58                "properties": {
59                "company": {
60                    "type": "string",
61                    "description": "公司名,例如:腾讯,阿里巴巴"
62                },
63                "exchange": {
64                    "type": "string",
65                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
66                }
67                },
68                "required": ["company", "exchange"]
69            },
70            "responses": {
71                "type": "object",
72                "properties": {
73                "price": {
74                    "type": "int",
75                    "description": "当日股票价格"
76                },
77                "unit": {
78                    "type": "string",
79                    "enum": ["人民币", "美元","港币"],
80                    "description": "股票价格货币类型"
81                },
82                "change": {
83                    "type": "string",
84                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
85                }
86                }
87            },
88    "examples": [
89      {"role":"user","content":"What is the weather like in Boston?"},
90      {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}},
91      {"role": "function", "name": "get_current_weather", "content": "{\"temperature\": \"25\", \"unit\": \"centigrade\", \"description\": \"cloud\"}"}
92    ]
93        }
94    ],
95    "stream":true,
96    "tool_choice": {
97        "type": "function",
98        "function": {
99            "name": "get_current_weather"
100        }
101    }
102}'
        1import requests
2import json
3
4
5def get_access_token():
6    """
7    使用应用API Key,应用Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
8    """
9
10    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
11
12    payload = json.dumps("")
13    headers = {
14        'Content-Type': 'application/json',
15        'Accept': 'application/json'
16    }
17
18    response = requests.request("POST", url, headers=headers, data=payload)
19    return response.json().get("access_token")
20
21
22def main():
23    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=" + get_access_token()
24
25    payload = json.dumps({
26         "messages": [
27        {
28            "role": "user",
29            "content": "上海市今天天气如何?"
30        },
31        {
32            "role": "assistant",
33            "content": None,
34            "function_call": {
35                "name": "get_current_weather",
36                "arguments": "{ \"location\": \"上海市\"}"
37            }
38        },
39        {
40            "role": "function",
41            "name": "get_current_weather",
42            "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"
43        },
44        {
45            "role": "assistant",
46            "content": "上海市今天天气是:气温25摄氏度,晴朗。"
47        },
48        {
49            "role": "user",
50            "content": "北京市今天天气如何?"
51        }
52    ],
53   "functions": [
54        {
55            "name": "get_current_weather",
56            "description": "获得指定地点的天气",
57            "parameters": {
58                "type": "object",
59                "properties": {
60                "location": {
61                    "type": "string",
62                    "description": "省,市名,例如:河北省,石家庄"
63                },
64                "unit": {
65                    "type": "string",
66                    "enum": ["摄氏度", "华氏度"]
67                }
68                },
69                "required": ["location"]
70            }
71    },
72        {
73            "name": "get_current_price",
74            "description": "获得指定公司的股价",
75            "parameters": {
76                "type": "object",
77                "properties": {
78                "company": {
79                    "type": "string",
80                    "description": "公司名,例如:腾讯,阿里巴巴"
81                },
82                "exchange": {
83                    "type": "string",
84                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
85                }
86                },
87                "required": ["company", "exchange"]
88            },
89            "responses": {
90                "type": "object",
91                "properties": {
92                "price": {
93                    "type": "int",
94                    "description": "当日股票价格"
95                },
96                "unit": {
97                    "type": "string",
98                    "enum": ["人民币", "美元","港币"],
99                    "description": "股票价格货币类型"
100                },
101                "change": {
102                    "type": "string",
103                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
104                }
105                }
106            },
107    "examples": [
108      {"role":"user","content":"What is the weather like in Boston?"},
109      {"role": "assistant", "content": None, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}},
110      {"role": "function", "name": "get_current_weather", "content": "{\"temperature\": \"25\", \"unit\": \"centigrade\", \"description\": \"cloud\"}"}
111    ]
112        }
113    ],
114    "stream":True,
115    "tool_choice": {
116        "type": "function",
117        "function": {
118            "name": "get_current_weather"
119        }
120    }
121    },ensure_ascii=False)
122    headers = {
123        'Content-Type': 'application/json'
124    }
125
126    response = requests.request("POST", url, headers=headers, data=payload.encode('utf8'))
127
128    print(response.text)
129
130
131if __name__ == '__main__':
132    main()
        - 第一次响应
 
1data: {"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}}
            - 函数调用
 
1curl -X POST http://0.0.0.0:80/get_current_weather -d '{
2   "unit": "摄氏度",
3   "location": "北京市"
4}'
        1import requests
2import json
3
4
5def main():
6    """
7    替换下列示例函数内容
8    """
9    url = "http://0.0.0.0:80/get_current_weather"
10
11    payload = json.dumps({
12        "unit": "摄氏度",
13        "location": "北京市"
14    },ensure_ascii=False)
15    headers = {
16        'Content-Type': 'application/json'
17    }
18
19    response = requests.request("POST", url, headers=headers, data=payload.encode('utf8'))
20
21    print(response.text)
22
23
24if __name__ == '__main__':
25    main()
        - 函数响应
 
1{
2    "temperature": "-1", 
3    "unit": "摄氏度", 
4    "description": "大雪"
5}
            - 第二次请求
 
1# 步骤一,获取access_token,替换下列示例中的应用API Key与应用Secret Key
2curl 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]'
3
4# 步骤二,调用本文API,使用步骤一获取的access_token,替换下列示例中的”调用接口获取的access_token“
5
6curl -X POST https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=[步骤一调用接口获取的access_token] -d '{
7        "messages": [
8        {
9            "role": "user",
10            "content": "上海市今天天气如何?"
11        },
12        {
13            "role": "assistant",
14            "content": null,
15            "function_call": {
16                "name": "get_current_weather",
17                "arguments": "{ \"location\": \"上海市\"}"
18            }
19        },
20        {
21            "role": "function",
22            "name": "get_current_weather",
23            "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"
24        },
25        {
26            "role": "assistant",
27            "content": "上海市今天天气是:气温25摄氏度,晴朗。"
28        },
29        {
30            "role": "user",
31            "content": "北京市今天天气如何?"
32        },
33        {
34            "role": "assistant",
35            "content": null,
36            "function_call": {
37                "name": "get_current_weather",
38                "arguments": "{ \"location\": \"北京市\"}"
39            }
40        },
41        {
42            "role": "function",
43            "name": "get_current_weather",
44            "content": "{\"temperature\": \"-1\", \"unit\": \"摄氏度\", \"description\": \"大雪\"}"
45        }
46    ],
47   "functions": [
48        {
49            "name": "get_current_weather",
50            "description": "获得指定地点的天气",
51            "parameters": {
52                "type": "object",
53                "properties": {
54                "location": {
55                    "type": "string",
56                    "description": "省,市名,例如:河北省,石家庄"
57                },
58                "unit": {
59                    "type": "string",
60                    "enum": ["摄氏度", "华氏度"]
61                }
62                },
63                "required": ["location"]
64            }
65    },
66        {
67            "name": "get_current_price",
68            "description": "获得指定公司的股价",
69            "parameters": {
70                "type": "object",
71                "properties": {
72                "company": {
73                    "type": "string",
74                    "description": "公司名,例如:腾讯,阿里巴巴"
75                },
76                "exchange": {
77                    "type": "string",
78                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
79                }
80                },
81                "required": ["company", "exchange"]
82            },
83            "responses": {
84                "type": "object",
85                "properties": {
86                "price": {
87                    "type": "int",
88                    "description": "当日股票价格"
89                },
90                "unit": {
91                    "type": "string",
92                    "enum": ["人民币", "美元","港币"],
93                    "description": "股票价格货币类型"
94                },
95                "change": {
96                    "type": "string",
97                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
98                }
99                }
100            },
101    "examples": [
102                [
103                 {"role":"user","content":"What is the weather like in Boston?"},
104                 {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}}
105                ],
106                [
107                     {"role":"user","content":"你的名字是什么?"},
108                 {"role": "assistant", "content": null, "function_call": {"name": "", "arguments": "{}", "thoughts":"我无需调用任何工具"}}
109                ]
110            ]
111        }
112    ],
113    "stream":true,
114    "tool_choice": {
115        "type": "function",
116        "function": {
117            "name": "get_current_weather"
118        }
119    }
120}'
        1import requests
2import json
3
4
5def get_access_token():
6    """
7    使用应用API Key,应用Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
8    """
9
10    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[应用API Key]&client_secret=[应用Secret Key]"
11
12    payload = json.dumps("")
13    headers = {
14        'Content-Type': 'application/json',
15        'Accept': 'application/json'
16    }
17
18    response = requests.request("POST", url, headers=headers, data=payload)
19    return response.json().get("access_token")
20
21
22def main():
23    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-preview?access_token=" + get_access_token()
24
25    payload = json.dumps({
26         "messages": [
27        {
28            "role": "user",
29            "content": "上海市今天天气如何?"
30        },
31        {
32            "role": "assistant",
33            "content": None,
34            "function_call": {
35                "name": "get_current_weather",
36                "arguments": "{ \"location\": \"上海市\"}"
37            }
38        },
39        {
40            "role": "function",
41            "name": "get_current_weather",
42            "content": "{\"temperature\": \"25\", \"unit\": \"摄氏度\", \"description\": \"晴朗\"}"
43        },
44        {
45            "role": "assistant",
46            "content": "上海市今天天气是:气温25摄氏度,晴朗。"
47        },
48        {
49            "role": "user",
50            "content": "北京市今天天气如何?"
51        },
52        {
53            "role": "assistant",
54            "content": None,
55            "function_call": {
56                "name": "get_current_weather",
57                "arguments": "{ \"location\": \"北京市\"}"
58            }
59        },
60        {
61            "role": "function",
62            "name": "get_current_weather",
63            "content": "{\"temperature\": \"-1\", \"unit\": \"摄氏度\", \"description\": \"大雪\"}"
64        }
65    ],
66   "functions": [
67        {
68            "name": "get_current_weather",
69            "description": "获得指定地点的天气",
70            "parameters": {
71                "type": "object",
72                "properties": {
73                "location": {
74                    "type": "string",
75                    "description": "省,市名,例如:河北省,石家庄"
76                },
77                "unit": {
78                    "type": "string",
79                    "enum": ["摄氏度", "华氏度"]
80                }
81                },
82                "required": ["location"]
83            }
84    },
85        {
86            "name": "get_current_price",
87            "description": "获得指定公司的股价",
88            "parameters": {
89                "type": "object",
90                "properties": {
91                "company": {
92                    "type": "string",
93                    "description": "公司名,例如:腾讯,阿里巴巴"
94                },
95                "exchange": {
96                    "type": "string",
97                    "enum": ["纳斯达克", "上海证券交易所","香港证券交易所"]
98                }
99                },
100                "required": ["company", "exchange"]
101            },
102            "responses": {
103                "type": "object",
104                "properties": {
105                "price": {
106                    "type": "int",
107                    "description": "当日股票价格"
108                },
109                "unit": {
110                    "type": "string",
111                    "enum": ["人民币", "美元","港币"],
112                    "description": "股票价格货币类型"
113                },
114                "change": {
115                    "type": "string",
116                    "description": "当日股票价格变化,如下跌3%,上涨0.5%"
117                }
118                }
119            },
120    "examples": [
121                [
122                 {"role":"user","content":"What is the weather like in Boston?"},
123                 {"role": "assistant", "content": None, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston\"}"}}
124                ],
125                [
126                     {"role":"user","content":"你的名字是什么?"},
127                 {"role": "assistant", "content": None, "function_call": {"name": "", "arguments": "{}", "thoughts":"我无需调用任何工具"}}
128                ]
129            ]
130        }
131    ],
132    "stream":True,
133    "tool_choice": {
134        "type": "function",
135        "function": {
136            "name": "get_current_weather"
137        }
138    }
139    },ensure_ascii=False)
140    headers = {
141        'Content-Type': 'application/json'
142    }
143
144    response = requests.request("POST", url, headers=headers, data=payload.encode('utf8'))
145
146    print(response.text)
147
148
149if __name__ == '__main__':
150    main()
        - 第二次响应
 
1data: {"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}}
2data: {"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}}
3data: {"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}}
4data: {"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再次请求。
1{
2  "error_code": 110,
3  "error_msg": "Access token invalid or no longer valid"
4}
            更多相关错误码,请查看错误码说明。
