【阿里云】| 智能对话机器人(云小蜜) | 快速开发入门
文章目录
- 一、环境要求
- 二、实现代码
- 三、参考文档
一、环境要求
Python 3
安装 SDK 核心库 OpenAPI ,使用pip安装包依赖:
pip install alibabacloud_tea_openapi
SDK 安装方式
- PyPI PIP:
pip install alibabacloud_chatbot20171011==2.0.1
- PyPI Anaconda:
conda install alibabacloud_chatbot20171011=2.0.1
- PyPI PIP:
二、实现代码
- sample demo 如下(涉及具体个人核心配置数据处,请对应自行修改填充)
# -*- coding: utf-8 -*-
# @ Date : 2022/1/27 16:27
# @ Author : RichardLau_Cx
# @ Project: Chatbot
# @ File : API_sample_new.py
# @ IDE : PyCharmimport ssl
import time
import uuid
import hmac
import base64
import requests
import urllib.parse
from hashlib import sha1
from Chatbot import configs # 自定义的配置数据信息文件# 解决访问ssl网站证书的问题
try:_create_unverified_https_context = ssl._create_unverified_contextexcept AttributeError:# Legacy Python that doesn't verify HTTPS certificates by defaultpasselse:# Handle target environment that doesn't support HTTPS verificationssl._create_default_https_context = _create_unverified_https_contextprotocol = 'https://'
domain_name = 'chatbot.cn-shanghai.aliyuncs.com/'
Parameters = {'Format': 'JSON','Version': '2017-10-11','AccessKeyId': configs.AccessKeyId,'SignatureMethod': 'HMAC-SHA1','SignatureVersion': 1.0
}def percent_encode(code):"""名称和值要使用 UTF-8 字符集进行 URL 编码,URL 编码的编码规则是:1.字符 A-Z、a-z、0-9 以及字符“-”、“_”、“.”、“~”,不进行编码;2.对于其他字符编码成“%XY”的格式,其中 XY 是字符对应 ASCII 码的 16 进制表示。比如英文的双引号对应的编码就是 “%22”;3.对于扩展的 UTF-8 字符,编码成“%XY%ZA…”的格式;4.注意英文空格要被编码成 “%20”,而不是加号“+”。:param code: 待编码串:return: 编码字符串"""# result = urllib.parse.quote(str(code))encode = str(code)result = urllib.parse.quote(encode)result = result.replace('+', '%20')result = result.replace('/', '%2F')result = result.replace('*', '%2A')result = result.replace('%7E', '~')return result# print("/: " + percent_encode('/'))def signature(params):"""签名机制:param params: 公共请求参数:return: 签名结果串"""# 1. 使用请求参数来构造规范化的请求字符串(Canonicalized Query String)# 1.1 按照参数名称的字母顺序对请求中所有的请求参数进行排序sorted_params = sorted(params.items(), key=lambda params: params[0])print("sorted_params: " + str(sorted_params))# 1.2 对每个请求参数的名称和值进行编码canonicalize_query_string = ''for (k, v) in sorted_params:# 1.3 对编码后的参数名称和值使用英文等号“=”进行连接# 1.4 再把英文等号连接得到的字符串按参数名称的字母顺序依次使用“&”符号连接,即得到规范化请求字符串canonicalize_query_string += '&' + percent_encode(k) + '=' + percent_encode(v)# print("canonicalize_query_string: " + str(canonicalize_query_string))# 2. 使用上一步构造的规范化字符串,按照下面的规则构造用于计算签名的字符串http_method = 'GET'string_to_sign = http_method + '&' + percent_encode('/') + '&' + percent_encode(canonicalize_query_string[1:])# print("string_to_sign: " + str(string_to_sign))string_to_sign = bytes(string_to_sign, encoding='utf8')# print("string_to_sign: " + str(string_to_sign))# 3. 按照 RFC2104 的定义,使用上面的用于签名的字符串计算签名 HMAC 值sign_key = bytes((configs.AccessKeySecret + '&'), encoding='utf8')hmacs = hmac.new(key=sign_key, msg=string_to_sign, digestmod=sha1)# 4. 按照 Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature)sign = base64.b64encode(hmacs.digest()).strip()return signformats = "%Y-%m-%dT%H:%M:%SZ"
timestamp = time.strftime(formats, time.gmtime()) # 函数用于格式化时间,返回以可读字符串表示的当地时间,格式由参数 format 决定
Parameters['Timestamp'] = timestampParameters['SignatureNonce'] = str(uuid.uuid1())
Parameters['Action'] = "Chat"
Parameters['InstanceId'] = configs.InstanceId
Parameters['Utterance'] = "你能够解决什么问题?" # 想AI机器人进行提问
Parameters['Signature'] = signature(Parameters) # 其函数操作包含了之前的一些属性值,因此理应放置到最后计算赋值sorted_params = sorted(Parameters.items(), key=lambda Parameters: Parameters[0])
url = protocol + domain_name + '?' + urllib.parse.urlencode(sorted_params)
print("url: " + str(url))r = requests.get(url) # 进行接口访问
print('r.text: ' + str(r.text))
- 优化封装版(基于class)
# -*- coding: utf-8 -*-
# @ Date : 2022/1/27 16:27
# @ Author : RichardLau_Cx
# @ Project: Python
# @ File : API_sample_new.py
# @ IDE : PyCharmimport ssl
import time
import uuid
import hmac
import base64
import requests
import urllib.parse
from hashlib import sha1
from Chatbot.configs import Configs # 自定义的配置数据信息文件def percent_encode(code):"""名称和值要使用 UTF-8 字符集进行 URL 编码,URL 编码的编码规则是:1.字符 A-Z、a-z、0-9 以及字符“-”、“_”、“.”、“~”,不进行编码;2.对于其他字符编码成“%XY”的格式,其中 XY 是字符对应 ASCII 码的 16 进制表示。比如英文的双引号对应的编码就是 “%22”;3.对于扩展的 UTF-8 字符,编码成“%XY%ZA…”的格式;4.注意英文空格要被编码成 “%20”,而不是加号“+”。:param code: 待编码串:return: 编码字符串"""encode = str(code)result = urllib.parse.quote(encode)result = result.replace('+', '%20')result = result.replace('/', '%2F')result = result.replace('*', '%2A')result = result.replace('%7E', '~')return resultclass ChatBot:def __init__(self):self.configs = Configs()def signature(self, params):"""签名机制:param params: 公共请求参数:return: 签名结果串"""# 1. 使用请求参数来构造规范化的请求字符串(Canonicalized Query String)# 1.1 按照参数名称的字母顺序对请求中所有的请求参数进行排序sorted_params = sorted(params.items(), key=lambda params: params[0])# print("sorted_params: " + str(sorted_params))# 1.2 对每个请求参数的名称和值进行编码canonicalize_query_string = ''for (k, v) in sorted_params:# 1.3 对编码后的参数名称和值使用英文等号“=”进行连接# 1.4 再把英文等号连接得到的字符串按参数名称的字母顺序依次使用“&”符号连接,即得到规范化请求字符串canonicalize_query_string += '&' + percent_encode(k) + '=' + percent_encode(v)# print("canonicalize_query_string: " + str(canonicalize_query_string))# 2. 使用上一步构造的规范化字符串,按照下面的规则构造用于计算签名的字符串http_method = 'GET'string_to_sign = http_method + '&' + percent_encode('/') + '&' + percent_encode(canonicalize_query_string[1:])# print("string_to_sign: " + str(string_to_sign))string_to_sign = bytes(string_to_sign, encoding='utf8')# print("string_to_sign: " + str(string_to_sign))# 3. 按照 RFC2104 的定义,使用上面的用于签名的字符串计算签名 HMAC 值sign_key = bytes((self.configs.AccessKeySecret + '&'), encoding='utf8')hmacs = hmac.new(key=sign_key, msg=string_to_sign, digestmod=sha1)# 4. 按照 Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature)sign = base64.b64encode(hmacs.digest()).strip()return signdef send(self, utterance):"""向服务器发出请求:param utterance: 向AI机器人进行发话:return: 响应结果(json数据)"""# 解决访问ssl网站证书的问题try:_create_unverified_https_context = ssl._create_unverified_contextexcept AttributeError:# Legacy Python that doesn't verify HTTPS certificates by defaultpasselse:# Handle target environment that doesn't support HTTPS verificationssl._create_default_https_context = _create_unverified_https_contextself.configs = Configs()protocol = 'https://'domain_name = 'chatbot.cn-shanghai.aliyuncs.com/'Parameters = {'Format': 'JSON','Version': '2017-10-11','AccessKeyId': self.configs.AccessKeyId,'SignatureMethod': 'HMAC-SHA1','SignatureVersion': 1.0}formats = "%Y-%m-%dT%H:%M:%SZ"timestamp = time.strftime(formats, time.gmtime()) # 函数用于格式化时间,返回以可读字符串表示的当地时间,格式由参数 formats 决定Parameters['Timestamp'] = timestampParameters['SignatureNonce'] = str(uuid.uuid1())Parameters['Action'] = "Chat"Parameters['InstanceId'] = self.configs.InstanceIdParameters['Utterance'] = utteranceParameters['Signature'] = self.signature(Parameters) # 其函数操作包含了之前的一些属性值,因此理应放置到最后计算赋值sorted_params = sorted(Parameters.items(), key=lambda Parameters: Parameters[0])url = protocol + domain_name + '?' + urllib.parse.urlencode(sorted_params)# print("url: " + str(url))response = requests.get(url).json() # 进行接口访问处# print('response: ' + str(type(response)))# print('response.content: ' + str(response["Messages"][0]["Text"]["Content"])) # 获取应答内容))return responseif '__main__' == __name__:data = "你是谁?" # 言论内容chatbot = ChatBot()response = chatbot.send(utterance=data)print('response.content: ' + str(response["Messages"][0]["Text"]["Content"]))
三、参考文档
- 阿里云 Python SDK
- 智能对话机器人 SDK参考
- 智能对话机器人 API参考
【阿里云】| 智能对话机器人(云小蜜) | 快速开发入门相关推荐
- 四十六、微信小程序快速开发入门
@Author:Runsen 很久没有写博客,前端学习到这里真的不容易,那接下来Runsen继续学习微信小程序开发. 首先微信小程序官方开发文档(免费的).微信开发者工具(免费的).微信云开发(还是免 ...
- 最佳实践 | 用腾讯云智能语音打造智能对话机器人
在AI技术的推动下,智能对话机器人逐渐成为我们工作.生活中的重要效率工具,乃至是伙伴,特别是为企业带来最原始最直观的"降本增效"落地实现. 作为开发者,你是否有想过基于语音技术打造 ...
- 阿里云智能对话分析服务
2019独角兽企业重金招聘Python工程师标准>>> 关于智能对话分析服务 智能对话分析服务 (Smart Conversation Analysis) 依托于阿里云语音识别和自然 ...
- 微信智能对话机器人调用第三方云函数
这是一个通过给公众号绑定微信智能对话机器人调用第三方云函数实现用户信息查询 的简单示例. 一:微信智能对话机器人配置: 1:在"高级技能"中创建"查询用户"的技 ...
- 首家优秀型厂商,百度智能云智能对话通过信通院权威评测!
百度智能云人工智能技术再加码,借助产品测评彰显人工智能领导者地位. 近日,在中国信息通信研究院2022年组织的"可信 AI"评测中,百度智能云以总得分91.08分的最高分数,获得了 ...
- 《智能对话机器人开发实战20讲》--学习笔记--AIML基础功能拓展-与互联网的集成
一.学习笔记 环境要求: aiml bs4 语料库: tuling.aiml search_web.aiml <that>WHICH SEARCH ENGINE WOULD YOU LIK ...
- mxm智能教育机器人无法智能对话_零代码使用腾讯TBP打造智能对话机器人
点击观看大咖分享 心疼你独自一人承担生活的苦难,寂寞夜里陪伴你的只剩无人倾诉的压抑和无处安放的焦虑.养个宠物,它却不能get到你的"宠言宠语".找个伴侣,还要浪费吵架的时间和精力. ...
- 智能对话机器人设计全流程
智能对话机器人设计全流程(阿里小蜜) 8.1什么是对话机器人 对话机器人模拟人类对话聊天形式并提供服务的程序,对话机器人之所以被广泛应用,是因为名称中的对话和机器人分别和用户和服务提供方都提供了价值 ...
- 腾讯技术直播间 | 零代码打造智能对话机器人
随着智能客服.AI营销日益普及,你是否发现在生活的各个角落,有越来越多对话机器人忙碌的身影? 你是否想打造属于自己的对话机器人,却被繁琐的代码.复杂的模型困扰? 现在,有了腾讯智能对话平台,你就能轻松 ...
最新文章
- 二叉搜索树c/c++代码实现
- Hive之 Hql语法解析
- 在WebStorm里配置watcher实现编辑less文件时自动生成.map和压缩后的.css文件
- 空间谱专题16:间距选取分析
- HDU 5741 Helter Skelter(构造法)
- php 检测变量中的回车键_PHP 的变量类型,变量检测
- ipad分屏大小怎么调整_flash怎么调整元素大小-Adobe flash统一图形大小的方法
- java mongo分组统计_mongodb 分组 topN
- Oracle 基本函数-数值、字符、 Instr()、日期、转换、SQL 操作符、trunc 截断
- WinForm(一):开始一个WinForm程序
- sql 不允许保存更改 解决办法
- 【重磅消息】欧洲最大云服务公司OVH机房着火:部分客户数据完全丢失且无法恢复
- 68pin SCSI接头针脚排序
- js正则表达式把数字格式化成XXXX-XXX-XXX
- 提取小米手机系统完整包BOOT,及ROOT!
- SOT23(Small Outline Transistor)
- 使用再生龙镜像备份还原linux,以及遇到的问题和解决方法
- java倒序查询数据库_数据库 倒序查询
- (1.4.5)字符串类
- UUID和UUID_SHORT