Skip to main content

多轮对话

Chat API 完全基于开源版本 LMDeploy 部署,可参考 LMDeploy 文档私有化部署同款接口。

🚀 News

  • InternVL3 (书生·万象) 多模态大模型已开放 API,model 字段使用 internvl3-latest 即可使用此模型进行图文推理
  • InternLM3 (书生·浦语) 系列首个模型 Internm3-8B-Instruct 发布并开源,API 同步支持。model 字段使用 internlm3-latest 即可使用此模型推理

流控策略

  • API 流控限制:默认每用户每分钟限制10次。有更高需求的同学,可在限流策略申请更高的流控配置

请求示例

目前浦语 ChatAPI 兼容了 openai python sdk 内的部分方法,仍在继续适配中...

我们仍推荐大家使用原生的 python 或 curl 请求访问书生 API

对于选择使用 openai sdk 的用户请先安装:

pip install openai

非流式调用

(一) Python 调用示例

  • 原生调用
import requests
import json

url = 'https://chat.intern-ai.org.cn/api/v1/chat/completions'
header = {
'Content-Type':'application/json',
"Authorization":"Bearer eyJ0eXBlIjoiSl...请填写准确的 token!"
}
data = {
"model": "internlm3-latest",
"messages": [{
"role": "user",
"content": "你好~"
}],
"n": 1,
"temperature": 0.8,
"top_p": 0.9
}

res = requests.post(url, headers=header, data=json.dumps(data))
print(res.status_code)
print(res.json())
print(res.json()["choices"][0]['message']["content"])
  • 使用 openai python sdk
from openai import OpenAI

client = OpenAI(
api_key="eyJ0eXBlIjoiSl...请填写准确的 token!", # 此处传token,不带Bearer
base_url="https://chat.intern-ai.org.cn/api/v1/",
)

chat_rsp = client.chat.completions.create(
model="internlm3-latest",
messages=[{"role": "user", "content": "hello"}],
)

for choice in chat_rsp.choices:
print(choice.message.content)

参数说明:

  • 支持 model, messages, n, temperature, top_p, stream, max_tokens, tools
  • 暂不支持其他参数

(二) CLI 调用示例

openai -b "https://chat.intern-ai.org.cn/api/v1/" 
-k "eyJ0eXBlIjoiSl...请填写准确的 token!"
api chat.completions.create
-m "internlm3-latest"
-g user hello

注:

  • 支持 -g ROLE CONTENT -m MODEL [-n N] [-t TEMPERATURE] [-P TOP_P] 参数
  • 暂不支持 [--stop STOP]

(三) curl 调用示例

curl --location 'https://chat.intern-ai.org.cn/api/v1/chat/completions' \
--header 'Authorization: Bearer xxxxxxx' \
--header 'Content-Type: application/json' \
--data '{
"model": "internlm3-latest",
"messages": [{
"role": "user",
"content": "你知道刘慈欣吗?"
}, {
"role": "assistant",
"content": "为一个人工智能助手,我知道刘慈欣。他是一位著名的中国科幻小说家和工程师,曾经获得过多项奖项,包括雨果奖、星云奖等。"
},{
"role": "user",
"content": "他什么作品得过雨果奖?"
}],
"temperature": 0.8,
"top_p": 0.9
}'

流式请求示例

(一) Python 调用示例

  • 原生调用
import requests
import json

url = 'https://chat.intern-ai.org.cn/api/v1/chat/completions'
header = {
'Content-Type':'application/json',
"Authorization":"Bearer eyJ0eXBlIjoiSl...请填写准确的 token!"
}
data = {
"model": "internlm3-latest",
"messages": [{
"role": "user",
"content": "你好~"
}],
"n": 1,
"temperature": 0.8,
"top_p": 0.9,
"stream": True,
}

response = requests.post(url, headers=header,data=json.dumps(data), stream=True)
for chunk in response.iter_lines(chunk_size=8192, decode_unicode=False, delimiter=b'\n'):
if not chunk:
continue
decoded = chunk.decode('utf-8')
if not decoded.startswith("data:"):
raise Exception(f"error message {decoded}")
decoded = decoded.strip("data:").strip()
if "[DONE]" == decoded:
print("finish!")
break
output = json.loads(decoded)
if output["object"] == "error":
raise Exception(f"logic err: {output}")
print(output["choices"][0]["delta"]["content"])

  • 使用 openai python sdk
from openai import OpenAI

client = OpenAI(
api_key="eyJ0eXBlIjoiSl...请填写准确的 token!", # 此处传token,不带Bearer
base_url="https://chat.intern-ai.org.cn/api/v1/",
)

chat_rsp = client.chat.completions.create(
model="internlm3-latest",
messages=[{"role": "user", "content": "hello"}],
stream=True,
)

for chunk in chat_rsp:
print(chunk.choices[0].delta.content)

(二) CLI 调用示例

openai -b "https://chat.intern-ai.org.cn/api/v1/" 
-k "eyJ0eXBlIjoiSl...请填写准确的 token!"
api chat.completions.create
-m "internlm3-latest"
--stream
-g user hello

注:

  • 支持 -g ROLE CONTENT -m MODEL [-n N] [-t TEMPERATURE] [-P TOP_P] --stream 参数
  • 暂不支持 [--stop STOP]

(三) curl 调用示例

curl --location 'https://chat.intern-ai.org.cn/api/v1/chat/completions' \
--header 'Authorization: Bearer xxxxxxx' \
--header 'Content-Type: application/json' \
--data '{
"model": "internlm3-latest",
"messages": [{
"role": "user",
"content": "你知道刘慈欣吗?"
}, {
"role": "assistant",
"content": "为一个人工智能助手,我知道刘慈欣。他是一位著名的中国科幻小说家和工程师,曾经获得过多项奖项,包括雨果奖、星云奖等。"
},{
"role": "user",
"content": "他什么作品得过雨果奖?"
}],
"temperature": 0.8,
"top_p": 0.9,
"stream": true
}'

多模态模型请求示例

以下以 Http 请求体为例,使用具体 SDK 的调用 API 可参考 Python 调用示例CLI 调用示例curl 调用示例

// Request
{
"model": "internvl3-latest",
"messages": [
{
"role": "user",
"content": "你好"
},
{
"role": "assistant",
"content": "你好,我是 internvl"
},
{
"role": "user",
"content": [ // 用户的图文提问内容,数组形式
{
"type": "text", // type 支持 text/image_url
"text": "Describe the image please"
},
{
"type": "image_url",
"image_url": {
"url": "https://static.openxlab.org.cn/internvl/demo/visionpro.png" // 支持互联网公开可访问的图片 url 或图片的 base64 编码
}
},
{
"type": "image_url", // 单轮对话支持上传多张图片
"image_url": {
"url": "https://static.openxlab.org.cn/puyu/demo/000-2x.jpg"
}
}
]
}
],
"temperature": 0.8, // float [0,1],default=0.5
"top_p": 0.9, // float [0,1],default=1
"max_tokens": 100 // default=0
}

含 Tool Call 的请求示例

// Request
{
"model": "internlm3-latest", // 将默认使用最新版本模型
"messages": [
{
"role": "user",
"content": "今天天气怎么样"
},
{
"role": "assistant",
"content": "我需要使用 get_current_weather API 来查询今天上海的天气",
"tool_calls": [
{
"id": "97102",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": "{'location': 'shanghai', 'unit': 'celsius'}"
}
}
]
},
{
"role": "tool",
"content": "{'location': 'shanghai', 'temperature': '40', 'unit': 'celsius'}",
"tool_call_id": "97102"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
},
},
"required": [
"location"
],
},
},
}
],
"temperature": 0.8, // float [0,1],default=0.5
"top_p": 0.9 // float [0,1],default=1
"request_output_len": 100 // default=0
}

返回示例

非流式请求返回示例

// Request
Schema: HTTP
Path: /api/v1/chat/completions
Method: POST
Header:
Authorization: $BearerToken

// Body
{
"model":"internlm3-latest", // 将默认使用最新版本模型
"messages": [{
"role": "user", // role 支持 user/assistant/system/tool
"content": "你知道刘慈欣吗?"
}, {
"role": "assistant",
"content": "为一个人工智能助手,我知道刘慈欣。他是一位著名的中国科幻小说家和工程师,曾经获得过多项奖项,包括雨果奖、星云奖等。"
},{
"role": "user",
"content": "他什么作品得过雨果奖?"
}],
"temperature": 0.8, // float [0,1],default=0.5
"top_p": 0.9 // float [0,1],default=1
"n": 1 // default=1
}
// Response
Status Code: 200
Body:
{
"id": "chatcmpl-123", // 此轮回复的唯一标识
"model": "internlm3-latest" // 模型 ID
"created": 1677652288, // 创建时间戳
"choices": [{ // 模型的回复内容
"index": 0, //0
"message": {
"role": "assistant",
"content": "刘慈欣的《三体》系列获得了2015年的雨果奖最佳长篇小说奖。这也是第一次有亚洲科幻小说家获此殊荣....", // puyu的返回结果
},
"finish_reason": "stop" // length / stop / tool_calls 三选一, length 表示返回结果超出 max_tokens
}],
"moderation": { // 内容审核相关,当前略
"sensitive": false
"category": ""
}
}

流式请求返回示例

// Request
Schema: HTTP
Path: /api/v1/chat/completions
Method: POST
Header:
Authorization: $BearerToken

// Request
{
"model": "internlm3-latest", // 将默认使用最新版本模型
"messages": [{
"role": "user", // role 支持 user/assistant/system/tool
"content": "你知道刘慈欣吗?"
}, {
"role": "assistant",
"content": "为一个人工智能助手,我知道刘慈欣。他是一位著名的中国科幻小说家和工程师,曾经获得过多项奖项,包括雨果奖、星云奖等。"
},{
"role": "user",
"content": "他什么作品得过雨果奖?"
}],
"n": 1,
"temperature": 0.8,
"top_p": 0.9,
"stream": True,
}
// Response
Status Code: 200
Body:
{
"id": "chatcmpl-123", // 此轮回复的唯一标识
"model": "internlm3-latest" // 模型 ID
"created": 1677652288, // 创建时间戳
"choices": [{ // 模型的回复内容
"index": 0, //0
"delta": {
"role": "assistant",
"content": "刘慈欣的《三体》系列获得了2015年的雨果奖最佳长篇小说奖", // puyu的返回结果
},
"finish_reason": "" // length / stop / 空字符串三选一, length 表示返回结果超出 max_tokens。未全部返回时,该字段为空
}],
"moderation": { // 内容审核相关,当前略
"sensitive": false
"category": ""
}
}

Tool Call 返回示例

Status Code: 200 
Body:
{
"id": "chatcmpl-123", // 此轮回复的唯一标识
"model": "internlm3-latest" // 模型 ID
"created": 1677652288, // 创建时间戳
"choices": [{ // 模型的回复内容
"index": 0, //0
"message": {
"role": "assistant",
"content": "get_current_weather",
"tool_calls": [
{
"id": "97102",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": "{'location': 'shanghai', 'unit': 'celsius'}"
}
}
]
},
"finish_reason": "tool_calls"
}],
"moderation": {
"sensitive": false,
"category": ""
}
}

调用参数说明

接口设置模型调用超时,如模型 120s 未输出完成,将打断输出返回当前结果

请求参数说明

参数类型示例说明
modelstringinternlm3-latest调用的模型名称
messagesarray大语言模型:[{"role":"user","content":"你好"}]多模态模型:参考下方多模态 messages对话历史及本次提问目前 role (角色) 支持:user/assistant/system/tool,internthinker-beta 模型暂不支持 "role":"system"
tools可选,array见下方 tools 示例一个数组包含所有模型可以调用的 functions,根据这个数组模型会回复调用相应 function 的 json 对象。
tool_choice可选, string or object{"type": "function", "function": {"name": "my_function"}}支持 none(强制不调用)/auto(自动调用)/required(必须调用一个 function),或者如参考示例传入某个必须让模型调用的 function 对象
temperature可选,float0.8采样温度
top_p可选,float0.9候选 token 的概率下限
max_tokens可选,int100请求输出的最大 token 数,默认 0 将自适应为能支持的最大长度
stream可选,booltrue流式输出增量结果,使用 tools 功能时不支持流式
  • 多模态 messages
{
"model": "internvl-latest",
"messages": [
{
"role": "user",
"content": "你好"
},
{
"role": "assistant",
"content": "你好,我是 internvl"
},
{
"role": "user",
"content": [ // 用户的图文提问内容,数组形式
{
"type": "text", // type 支持 text/image_url
"text": "Describe the image please"
},
{
"type": "image_url",
"image_url": {
"url": "https://static.openxlab.org.cn/internvl/demo/visionpro.png" // 支持互联网公开可访问的图片 url 或图片的 base64 编码
}
},
{
"type": "image_url", // 单轮对话支持上传多张图片
"image_url": {
"url": "https://static.openxlab.org.cn/puyu/demo/000-2x.jpg"
}
}
]
}
],
"temperature": 0.8, // float [0,1],default=0.5
"top_p": 0.9, // float [0,1],default=1
"max_tokens": 100 // default=0
}
  • tools 示例
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
}
]

返回参数说明

参数类型示例说明
idstringchatcmpl-123唯一的会话 id
modelstringinternlm3-latest调用的模型名称
createdint1677652288创建时间戳
choicesarray[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]模型回答
moderationobject{"sensitive":false,"category":""}内容审核相关,暂不支持

相关结构体说明

  • choice 结构说明
参数类型示例说明
indexint0多次生成时,表示结果的序号
messageobject{"role":"assistant", "content":"你好"}表示一个提问或回答
仅非流式请求时存在
deltaobject{"role":"assistant", "content":"你好"}表示一个提问或回答
仅流式请求时存在,使用 tools 功能时不支持流式
finish_reasonstringstoplength / stop / tool_calls 二选一, length 表示返回结果超出 max_tokens
  • message 结构说明
参数类型示例说明
rolestringuseruser 表示用户提问,assistant 表示模型回答
contentstring你好对话内容,当向模型发送 role 为 tool 的请求时,content 内容为调用相应 function 返回的 json string
tool_call_idstring97102仅当向模型发送 role 为 tool 的请求时必填,或模型生成了 tool_calls 内容时必返回,两者需一一对应
tool_callsarray参考下方 tools_calls 示例模型返回 json 格式的 function 调用
  • tool_calls 示例
tool_calls = [
{
"id": "97102",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": "{'location': 'shanghai', 'unit': 'celsius'}"
}
}
]
  • moderation 结构说明
参数类型示例说明
sensitiveboolfalse是否敏感
categorystringad敏感词分类

常见错误

错误码说明解决建议
-10002参数错误检查提问是否为空
-20004非白名单用户请在网页申请调用权限
-20013请求的模型不存在检查 model 参数是否是支持的模型
-20018messages 格式错误messages 格式是否正确
-20035账号未绑定手机号请通过网页绑定手机号
-20053超出频率限制(req/min 或 tokens/min)确认请求频率在允许范围内,或申请更高调用频率
A0202用户鉴权失败请检查提供的 token 是否正确,格式是否一致(是否有 Bearer)
A0211token 过期请确认 token 是否已过期
C1114非本业务 token请检查 token 是否属于本服务