问题描述
Rasa启用API后可以调用,但官方文档 HTTP API只给出了curl的方法
如何通过Python调用API像rasa x
一样进行完整对话?
初始化项目
- 初始化项目:
rasa init
- 启动Rasa API:
rasa run --enable-api
- 访问http://localhost:5005/检验是否启动成功
PS:若有自定义动作,需要定义endpoints和启动自定义动作
endpoints.yml
action_endpoint:
url: "http://localhost:5055/webhook"
启动自定义动作:rasa run actions
仅解析意图
A.py(千万别命名为test.py)
import json
import requests
url = "http://localhost:5005/model/parse"
data = {"text": "hello"}
data = json.dumps(data, ensure_ascii=False)
data = data.encode(encoding="utf-8")
r = requests.post(url=url, data=data)
print(json.loads(r.text))
结果
{'intent': {'name': 'greet', 'confidence': 0.9930983185768127}, 'entities': [], 'intent_ranking': [{'name': 'greet', 'confidence': 0.9930983185768127}, {'name': 'mood_unhappy', 'confidence': 0.0036425672005861998}, {'name': 'bot_challenge', 'confidence': 0.002293727360665798}, {'name': 'mood_great', 'confidence': 0.00035825479426421225}, {'name': 'goodbye', 'confidence': 0.00032570294570177794}, {'name': 'affirm', 'confidence': 0.00022301387798506767}, {'name': 'deny', 'confidence': 5.849302760907449e-05}], 'text': 'hello'}
连续对话
import json
import secrets
import requests
def post(url, data=None):
data = json.dumps(data, ensure_ascii=False)
data = data.encode(encoding="utf-8")
r = requests.post(url=url, data=data)
r = json.loads(r.text)
return r
sender = secrets.token_urlsafe(16)
url = "http://localhost:5005/webhooks/rest/webhook"
while True:
message = input("Your input -> ")
data = {
"sender": sender,
"message": message
}
print(post(url, data))
以下内容是更精细的操作,建议忽略
简单例子
如何进行一轮对话?主要分三步——发送消息、预测下一步动作、执行动作
import json
import requests
def post(url, data=None):
data = json.dumps(data, ensure_ascii=False)
data = data.encode(encoding="utf-8")
r = requests.post(url=url, data=data)
r = json.loads(r.text)
return r
if __name__ == "__main__":
# 会话id,此处简单设为0
conversation_id = 0
# 1. 发送消息
url = "http://localhost:5005/conversations/{}/messages".format(conversation_id)
data = {
"text": "Hi",
"sender": "user"
}
result = post(url, data)
print(result)
# 2. 预测下一步动作
url = "http://localhost:5005/conversations/{}/predict".format(conversation_id)
result = post(url)
print(result)
# 3. 执行动作
url = "http://localhost:5005/conversations/{}/execute".format(conversation_id)
data = {
"name": result["scores"][0]["action"] # 取置信度最高的动作
}
result = post(url, data)
print(result)
print(result["messages"]) # 获取对话信息
# [{'recipient_id': '1', 'text': 'Hey! How are you?'}]
对话流程
简单例子无法连续对话,如何连续对话呢?
import json
import secrets
import requests
def post(url, data=None):
data = json.dumps(data, ensure_ascii=False)
data = data.encode(encoding="utf-8")
r = requests.post(url=url, data=data)
r = json.loads(r.text)
return r
if __name__ == "__main__":
conversation_id = secrets.token_urlsafe(16) # 随机生成会话id
messages_url = "http://localhost:5005/conversations/{}/messages".format(conversation_id) # 发送消息
predict_url = "http://localhost:5005/conversations/{}/predict".format(conversation_id) # 预测下一步动作
execute_url = "http://localhost:5005/conversations/{}/execute".format(conversation_id) # 执行动作
action = "action_listen" # 动作初始化为等待输入
while True:
if action in ["action_listen", "action_default_fallback", "action_restart"]:
# 等待输入
text = input("Your input -> ")
post(messages_url, data={"text": text, "sender": "user"}) # 发送消息
response = post(predict_url) # 预测下一步动作
action = response["scores"][0]["action"] # 取出置信度最高的下一步动作
response = post(execute_url, data={"name": action}) # 执行动作
messages = response["messages"] # 取出对话信息
if messages:
print(messages)
domain.yml中的utter_great可添加buttons
responses:
utter_greet:
- text: Hey! How are you?
buttons:
- payload: '/mood_great'
title: 'great'
- payload: '/mood_unhappy'
title: 'sad'
HTML形式
下载本人的开源界面
- 启动Rasa API(允许跨域)
rasa run --enable-api --cors "*"
- 直接打开页面
index.html
常用命令
- 查看5005端口是否被占用
netstat -aon | findstr 5005
- 启动Rasa API服务(跨域)
rasa run --enable-api --cors "*"
- 启动Rasa API服务(保存日志)
rasa run --enable-api --log-file out.log
- 启动Rasa API服务(指定模型)
rasa run --enable-api -m models
遇到的坑
- 若遇到死循环,一般是遇到默认动作没有退出,查看默认动作