NLP案例学习(在线医生)——一、unit对话API应用

一、unit对话API应用

1.1理解智能对话系统:

  • 任务导向型: 完成具有明确指向性的任务, 比如预定酒店咨询, 在线问诊等等.
  • 非任务导向型: 没有明确目的, 比如算算术, 播放音乐, 回答问题,闲聊.

1.2 Unit对话API的使用

学习目标:

  • 了解Unit平台的相关知识.

(Understanding and Interaction Technology)

Unit平台是百度大脑开放的智能对话定制与服务平台, 也是当前最大的中文领域对话开放平台之一.

  • 掌握调用Unit API的实现过程:
  1. 第一步: 注册登录百度账户, 进入Unit控制台创建自己的机器人.https://ai.baidu.com/unit/home

  2. 第二步: 进行相关配置, 获得请求API接口需要的API KeySecret Key.

  3. 第三步: 在服务器上编写API调用脚本并进行测试:

参考UNIT官方文档:https://ai.baidu.com/ai-doc/UNIT/tk38gucnz#%E6%9C%BA%E5%99%A8%E4%BA%BA

#!/usr/bin/env python
# encoding: utf-8
'''
@File    : unit.py
@author: bella
@time: 2020/5/17 9:52
@Software: PyCharm
'''
import json
import random
import requests

"""需要注意的参数,其他代码都是固定步骤"""
# 闲聊(老师案例)
# client_id 为官网获取的API KEY, client_secret 为官网获取的Secret Key
# client_id = "1xhPonkmHqwolDt3GCICLX39"
# client_secret = "SRYsfjMGNuW8G265paMXLEjDTjO6O4RC"
# service_id = "S23245"  #
# 可调参数: unit_chat_response["schema"]["intent_confidence"] >= 0.0,置信度阈值

# 疫情信息,自己创建的机器人
client_id = "z3vkOAbGDohetChOiubKs3rk"
client_secret = "6QLGHGtBx9m3aGx9kYnGoa7WR33YjvUx"
service_id = "S29917"  # 机器人ID,一个百度账号可以创建多个机器人ID


def unit_chat(chat_input, user_id="88888"):
    """
    description:调用百度UNIT接口,回复聊天内容
    Parameters
      ----------
      chat_input : str
          用户发送天内容
      user_id : str
          发起聊天用户ID,可任意定义
    Return
      ----------
      返回unit回复内容
    """
    # 设置默认回复内容,  一旦接口出现异常, 回复该内容
    chat_reply = "不好意思,俺们正在学习中,随后回复你。"
    # 根据 client_id 与 client_secret 获取access_token
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s" % (
    client_id, client_secret)
    res = requests.get(url)
    # print(res)  ## <Response [200]>
    # print(res.text)
    # {"refresh_token": "25.b2ad355fc47455c9d14329d72e857db7.315360000.1905054331.282335-17597003", "expires_in": 2592000,
    #  "session_key": "9mzdDZMy38TkVe2TJdOHI7DYl6UwBzEA+pKp60c8LpzObdPWx1KAMkUvpsftIHPfhii9r36JZrhnQ7GVVqAL+zhTdM2TdQ==",
    #  "access_token": "24.6e3593df825d8c8f4525b266477830c4.2592000.1592286331.282335-17597003",
    #  "scope": "public brain_all_scope unit_\u7406\u89e3\u4e0e\u4ea4\u4e92V2 wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\u6743\u9650 vis-classify_flower lpq_\u5f00\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\u5f00\u653eScope vis-ocr_\u865a\u62df\u4eba\u7269\u52a9\u7406 idl-video_\u865a\u62df\u4eba\u7269\u52a9\u7406",
    #  "session_secret": "84f94d608b4966cf2acd9db36bdee8e8"}
    access_token = eval(res.text)["access_token"]
    # access_token = res.text["access_token"]  # res.text是字符串,索引必须是整数
    # print("access_token",access_token)  #  24.c3f10f0f8e6cdaee3d74f539b62e8503.2592000.1592286860.282335-17597003
    # 根据 access_token 获取聊天机器人接口数据
    unit_chatbot_url = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + access_token
    # 拼装聊天接口对应请求发送数据,主要是填充 query 值
    post_data = {
                "log_id": str(random.random()),
                "request": {
                    "query": chat_input,
                    "user_id": user_id
                },
                "session_id": "",
                # "service_id": "S23245",
                "service_id": service_id,
                "version": "2.0"
            }
    # 将封装好的数据作为请求内容, 发送给Unit聊天机器人接口, 并得到返回结果
    res = requests.post(url=unit_chatbot_url, json=post_data)
    # print("res",res)  # <Response [200]>
    # print(res.content)
    # b'{"result":{"version":"2.0","timestamp":"2020-05-17 13:58:57.909","service_id":"S23245","log_id":"0.013853281268498496","session_id":"service-session-id-1589695137909-24088a352f5c4dbe85cdb9f1ad47b782","interaction_id":"service-interactive-id-1589695137909-9cb3ab560bf8435b99051765fae47f0a","response_list":[{"status":0,"msg":"ok","origin":"85515","schema":{"intent_confidence":1.0,"intent":"BUILT_CHAT"},"action_list":[{"refine_detail":{},"confidence":0.5367454290390015,"custom_reply":"","say":"\xe4\xbb\x8a\xe5\xa4\xa9\xe6\x99\xb4\xe8\xbd\xac\xe5\xa4\x9a\xe4\xba\x91","type":"chat"},{"refine_detail":{},"confidence":0.5367454290390015,"custom_reply":"","say":"\xe4\xbb\x8a\xe5\xa4\xa9\xe8\xbf\x98\xe8\xa1\x8c\xe5\x87\xba\xe5\xa4\xaa\xe9\x98\xb3\xe4\xba\x86","type":"chat"},{"refine_detail":{},"confidence":0.5347083806991577,"custom_reply":"","say":"\xe5\x87\xba\xe5\xa4\xaa\xe9\x98\xb3","type":"chat"}],"qu_res":{}}],"dialog_state":{"skill_states":{}}},"error_code":0}'

    # 获取聊天接口返回数据
    unit_chat_obj = json.loads(res.content)
    # print("unit_chat_obj",unit_chat_obj)
    # {'result': {'version': '2.0', 'timestamp': '2020-05-17 13:56:19.711', 'service_id': 'S23245',
    #             'log_id': '0.5269089474234951',
    #             'session_id': 'service-session-id-1589694979711-74af5854d297452f9f4dd9cb7d177c43',
    #             'interaction_id': 'service-interactive-id-1589694979711-1b2aa5df4bd84c13a486777057612a54',
    #             'response_list': [{'status': 0, 'msg': 'ok', 'origin': '85515',
    #                                'schema': {'intent_confidence': 1.0, 'intent': 'BUILT_CHAT'}, 'action_list': [
    #                     {'refine_detail': {}, 'confidence': 0.5367454290390015, 'custom_reply': '', 'say': '今天晴转多云',
    #                      'type': 'chat'},
    #                     {'refine_detail': {}, 'confidence': 0.5367454290390015, 'custom_reply': '', 'say': '今天还行出太阳了',
    #                      'type': 'chat'},
    #                     {'refine_detail': {}, 'confidence': 0.5347083806991577, 'custom_reply': '', 'say': '出太阳',
    #                      'type': 'chat'}], 'qu_res': {}}], 'dialog_state': {'skill_states': {}}}, 'error_code': 0}
    # 打印返回的结果
    # 判断聊天接口返回数据是否出错 error_code == 0 则表示请求正确
    if unit_chat_obj["error_code"] != 0: return chat_reply
    # 解析聊天接口返回数据,找到返回文本内容 result -> response_list -> schema -> intent_confidence(>0) -> action_list -> say
    unit_chat_obj_result = unit_chat_obj["result"]
    unit_chat_response_list = unit_chat_obj_result["response_list"]
    # 随机选取一个"意图置信度"[+response_list[].schema.intent_confidence]不为0的技能作为回答
    # print("unit_chat_response_list",unit_chat_response_list)  # 输入你好的结果
    # unit_chat_response_list[{'status': 0, 'msg': 'ok', 'origin': '1028409',
    #                          'schema': {'intent_confidence': 0, 'slots': [], 'domain_confidence': 0, 'intent': ''},
    #                          'action_list': [{'action_id': 'fail_action',
    #                                           'refine_detail': {'option_list': [], 'interact': '',
    #                                                             'clarify_reason': ''}, 'confidence': 100,
    #                                           'custom_reply': '', 'say': '这个我还不会,我会再学习更多疫情知识的', 'type': 'failure'}],
    #                          'qu_res': {}}]

    unit_chat_response_obj = random.choice(
       [unit_chat_response for unit_chat_response in unit_chat_response_list if
        unit_chat_response["schema"]["intent_confidence"] >= 0.0])
    # print("unit_chat_response_obj",unit_chat_response_obj)
    unit_chat_response_action_list = unit_chat_response_obj["action_list"]
    unit_chat_response_action_obj = random.choice(unit_chat_response_action_list)
    unit_chat_response_say = unit_chat_response_action_obj["say"]
    return unit_chat_response_say


if __name__ == '__main__':
    while True:
        chat_input = input("请输入:")
        # print(chat_input)
        chat_reply = unit_chat(chat_input)
        print("用户输入 >>>", chat_input)
        print("Unit回复 >>>", chat_reply)
        if chat_input == 'Q' or chat_input == 'q':
            break

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值