一、大模型会话接口集成概述
官方API参考地址
二、API接口调用参数获取
- 2.1 ACCESS_KEY_ID、ACCESS_KEY_SECRET参数获取地址
- 2.2 AgentKey
业务空间 key,不设置则访问默认业务空间,key 值在主账号业务管理页面获取
- 2.3 instance_id
三、Python Code Sample
# -*- coding: utf-8 -*-
import hashlib
import time
import uuid
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient
import json
import requests
class Sample:
def __init__(self):
pass
# 参数设置
ACCESS_KEY_ID = 'LTAI**********'
ACCESS_KEY_SECRET = '8RQfmiwwn***********'
@staticmethod
def create_client() -> OpenApiClient:
"""
使用AK&SK初始化账号Client
@return: Client
@throws Exception
"""
# 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
config = open_api_models.Config(
# 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
access_key_id=Sample.ACCESS_KEY_ID,
# 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
access_key_secret=Sample.ACCESS_KEY_SECRET
)
# Endpoint 请参考 https://api.aliyun.com/product/Chatbot
config.endpoint = f'chatbot.cn-shanghai.aliyuncs.com'
return OpenApiClient(config)
@staticmethod
def get_sign(stream_secret, timestamp) -> str:
"""
计算签名
:param stream_secret:
:param timestamp:
:return:
"""
text_to_hash = f"streamSecret={stream_secret}×tamp={timestamp}"
md5_hash = hashlib.md5(text_to_hash.encode('utf-8')).hexdigest()
return md5_hash
@staticmethod
def create_ApplyForStreamAccessToken_api_info() -> open_api_models.Params:
"""
API 相关
@param path: string Path parameters
@return: OpenApi.Params
"""
params = open_api_models.Params(
# 接口名称,
action='ApplyForStreamAccessToken',
# 接口版本,
version='2022-04-08',
# 接口协议,
protocol='HTTPS',
# 接口 HTTP 方法,
method='POST',
auth_type='AK',
style='RPC',
# 接口 PATH,
pathname=f'/',
# 接口请求体内容格式,
req_body_type='json',
# 接口响应体内容格式,
body_type='json'
)
return params
@staticmethod
def ApplyForStreamAccessToken(
AgentKey:str,
) -> str:
client = Sample.create_client()
params = Sample.create_ApplyForStreamAccessToken_api_info()
# query params
queries = {
}
queries['AgentKey'] = AgentKey
# runtime options
runtime = util_models.RuntimeOptions()
request = open_api_models.OpenApiRequest(
query=OpenApiUtilClient.query(queries)
)
# 复制代码运行请自行打印 API 的返回值
# 返回值实际为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
res = client.call_api(params, request, runtime)
return res['body']
@staticmethod
def create_request_body(message_id, instance_id, utterance):
"""
构造请求body
:param message_id:消息message id
:param instance_id:机器人id
:param utterance:实际内容
:return:
"""
body = {
"messageId": message_id,
"action": "TongyiBeebotChat",
"version": "2022-04-08",
"data": [
{
"type": "JSON_TEXT",
"value": json.dumps({
"InstanceId": instance_id,
"Utterance": utterance
},ensure_ascii=False)
}
]
}
return body
@staticmethod
def sse_request(url, payload):
"""
构建SSE请求
:param url: 请求的URL
:param payload: 要发送的数据
:return: None
"""
# 创建会话
session = requests.Session()
# 请求头
headers = {
'Content-Type': 'application/json'
}
# 使用 POST 请求获取 SSE 线
with session.post(url, headers=headers, data=json.dumps(payload), stream=True) as response:
# 确保请求成功
response.raise_for_status()
# 持续读取服务器发来的事件
for line in response.iter_lines():
if line:
# 处理每一行数据
data = line.decode('utf-8')
print(f'Received: {data}')
if __name__ == '__main__':
AgentKey = "f6b6af483***********_p_beebot_public" # 业务空间key
res = Sample.ApplyForStreamAccessToken(AgentKey) # 1、调用ApplyForStreamAccessToken接口
AccessToken = res['AccessToken']
StreamSecret = res['StreamSecret']
ChannelId = res['ChannelId']
time_millis = int(time.time() * 1000)
sign = Sample.get_sign(StreamSecret, time_millis) # 2、计算会话接口签名
url_template = "https://alime-ws.aliyuncs.com/sse/paas4Json/{AccessToken}/{ChannelId}/{Sign}/{Timestamp}"
url = url_template.format(AccessToken=AccessToken, ChannelId=ChannelId, Sign=sign, Timestamp=time_millis)
# 生成一个随机的UUID
messageId = str(uuid.uuid4())
instance_id = "chatbot-cn-Aei********" # 机器人id
utterance = "你有什么技能?" # 实际问题
payload = Sample.create_request_body(messageId, instance_id, utterance)
Sample.sse_request(url, payload) # 3、发送SSE请求,获取流式响应结果
- 测试结果:
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":false,\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"SequenceId\":\"0e99be8a5ec444359a54405870cc96cf\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"aad1d419-45cb-4f8d-9f24-a0c12ca62749","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"da038f26ab9e4ad7acd8087a5b76c6e3\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"5fb4a490-e0d7-4832-b460-287724d557da","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"67b712bc3a2e477aaef56beca30e441a\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"75e24897-0249-4971-b476-f366c1b16a16","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"245c83ddd9584a5cb771f4f9c07351ca\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"c137f85c-1403-4395-887a-df876d37190a","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"16b98b73c83e404fb10424e14307c089\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"6a3ae208-cb45-46ba-b319-d9f0a09ce415","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"我是个大模型,能够\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"65e6de0c377d4934803b258449fefbd0\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"316abed4-7c0e-42b2-bbf2-9451948a1ad6","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"我是个大模型,能够回答问题、创作文字,比如写\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"3e297b0afb64430d9982bbd3a190563a\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"97e66246-4159-4ce2-990e-db035ab64698","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"我是个大模型,能够回答问题、创作文字,比如写故事、写公文、写邮件\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"d10ee630e84f4995a0755a1448b319e1\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"95af7cc8-5439-4c50-8893-d62877fc33f7","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"我是个大模型,能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本等等,还能表达观点\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"371ac0ab34a94bc2acea1056b4939099\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"3180f1c0-b901-4189-b306-c6ff4f0a25de","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"我是个大模型,能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本等等,还能表达观点,玩游戏等。\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"044f4dadc62f4d938032b49a2bbd719b\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"4e1fcd22-2140-44d1-adde-f3ecb754939e","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"我是个大模型,能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本等等,还能表达观点,玩游戏等。\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"89c05efbd4b342c9a4841e7a2ce87617\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":false}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"7dd5c7f3-b2ed-42a9-a130-b29f9797e7cd","success":true}
Received: data:{
"data":[{
"type":"JSON_TEXT","value":"{\"IsAIGC\":true,\"MessageBody\":{\"DirectMessageBody\":{\"ContentType\":\"RICH_TEXT\",\"Ext\":{},\"SentenceList\":[{\"Content\":\"我是个大模型,能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本等等,还能表达观点,玩游戏等。\"}]},\"Type\":\"Direct\",\"VoiceConfig\":{}},\"MessageId\":\"aad1d419-45cb-4f8d-9f24-a0c12ca62749\",\"QuerySegList\":[\"你\",\"有\",\"什么\",\"技能\",\"?\"],\"SequenceId\":\"6939e0f6569345799e2b19496842ea27\",\"SessionId\":\"dfa8ed43a2584d6c867a1c9b5baee490\",\"Source\":\"NON_STRUCTURAL_KNOWLEDGE\",\"StreamEnd\":true}"}],"messageId":"6bd684db-7259-4060-88fc-de562d2c86e7","requestId":"0b7d7915-1d68-43ce-a634-bbf44ff98cc2","success":true}