Python调用Rasa API服务进行连续对话

问题描述

Rasa启用API后可以调用,但官方文档 HTTP API只给出了curl的方法

如何通过Python调用API像rasa x一样进行完整对话?

在这里插入图片描述




初始化项目

  1. 初始化项目:rasa init
  2. 启动Rasa API:rasa run --enable-api
  3. 访问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?'}]




对话流程

简单例子无法连续对话,如何连续对话呢?

Created with Raphaël 2.2.0 开始 等待输入? 发送消息 预测下一步动作 执行动作 yes no
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形式

在这里插入图片描述

下载本人的开源界面

  1. 启动Rasa API(允许跨域)
rasa run --enable-api --cors "*"
  1. 直接打开页面index.html




常用命令

  1. 查看5005端口是否被占用 netstat -aon | findstr 5005
  2. 启动Rasa API服务(跨域)rasa run --enable-api --cors "*"
  3. 启动Rasa API服务(保存日志)rasa run --enable-api --log-file out.log
  4. 启动Rasa API服务(指定模型)rasa run --enable-api -m models




遇到的坑

  1. 若遇到死循环,一般是遇到默认动作没有退出,查看默认动作




参考文献

  1. Configuring the HTTP API
  2. Rasa HTTP API
  3. windows系统安装curl
  4. Windows查看某个端口被占用的解决方法
  5. python - How to send POST request?
  6. NLU server - ParsingError · Issue #4024
  7. rasa - http api测试
  8. Bootstrap v3中文文档
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XerCis

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值