当前位置:   article > 正文

第一次构建一个对话机器人流程解析(二)

第一次构建一个对话机器人流程解析(二)

1. 问答机器人的组成-基于知识图谱的搜索

  • 在教育场景下,若学生有关于学习内容的提问,或业务层面的提问,则要求问答机器人的回答必须精准,来满足业务的要求
  • 因此需要通过知识图谱来快速检索,所提内容的相关信息,并针对这些相关信息进行处理,得到精准的回答
  • 本次内容中直接应用了知识图谱基本功能,关系寻找及关系提取
  • 后续学习中会提供更多的应用

2. 伪代码实现

  1. from py2neo import Graph #导入neo4j
  2. from pyhanlp import * #导入nlp的工具包
  3. from random import choice
  4. #知识图谱的初步应用
  5. class GraphSearch():
  6. def __init__(self):
  7. self.graph = Graph("http://localhost:7474", username="graph.db", password="lesson1")
  8. self.iswho_sql = "profile match p=(n)<-[r]-(b) where n.name='%s' return n.name,r.name,b.name"
  9. self.isrelation_sql = "profile match p=(n)<-[r]-(b) where n.name=~'%s' and b.name=~'%s' return n.name,r.name,b.name"
  10. def search_answer(self,question):
  11. #使用HanLP进行词性判断
  12. sentence = HanLP.parseDependency(question)
  13. #后续可以替换成自己训练的模块首先针对句意进行分析,其次针对目标实体进行提取;但主要也是针对业务场景进行分析和处理
  14. seg = {}
  15. res_combine = ''
  16. for word in sentence.iterator():
  17. ##只处理nr名词:人,v动词,n名词,针对进行提问进行词性分析
  18. if word.POSTAG[0] == 'n' or word.POSTAG in ['v','r']:
  19. if word.POSTAG not in seg:
  20. seg[word.POSTAG] = [word.LEMMA]
  21. else:
  22. seg[word.POSTAG].append(word.LEMMA)
  23. #简单基于词性和内容判断是否为目标句式'A是谁'以此使用知识图谱进行回答
  24. if 'v' in seg and '是' in seg['v']:
  25. if 'r' in seg and 'nr' in seg and '谁' in seg['r']:
  26. for person in seg['nr']:
  27. res = self.graph.run(self.iswho_sql%(person)).data()
  28. res_combine = []
  29. for i in res[:10]:
  30. res_combine.append('%s是:%s%s'%(i['n.name'],i['b.name'],i['r.name']))
  31. return choice(res_combine)
  32. #基于词性和内容判断是否为目标句式'A和B的关系'以此使用知识图谱进行回答
  33. if 'n' in seg and '关系' in seg['n']:
  34. if len(seg['nr']) == 2:
  35. res1 = self.graph.run(self.isrelation_sql%(seg['nr'][1],seg['nr'][0])).data()
  36. if res1 != []:
  37. res_combine = seg['nr'][0]+'的'+res2[0]['r.name']+'是'+seg['nr'][1]
  38. return res_combine
  39. res2 = self.graph.run(self.isrelation_sql%(seg['nr'][0],seg['nr'][1])).data()
  40. if res2 != []:
  41. res_combine = seg['nr'][1]+'的'+res2[0]['r.name']+'是'+seg['nr'][0]
  42. return res_combine
  43. if res_combine == '':
  44. return None

后续在完成业务场景下的实体提取和意图识别,学习及模型训练后,丰富该功能的问答

3. 问答机器人的组成-基于网络的回答

  • 在对话机器人构建的初期,常常面临数据不足,导致机器人无法进行准确回答,因此在前期会适当调用第三方对话的接口,来进行回答
  • 以此防止突然冷场或机器人对话失灵
  • 后续使用生成式的对话机器人,来解决此类问题
  1. import requests
  2. class InterNet():
  3. def __init__(self):
  4. pass
  5. def search_answer(self,question):
  6. url = 'https://api.ownthink.com/bot?appid=xiaosi&userid=user&spoken='
  7. try:
  8. text = requests.post(url+question).json()
  9. if 'message' in text and text['message'] == 'success':
  10. return text['data']['info']['text']
  11. else:
  12. return None
  13. except:
  14. return None

4. 服务的构建-什么是flask

5. 服务的构建-我的第一个flask

  1. '''
  2. 我的第一个flask_service.py
  3. '''
  4. from flask_cors import cross_origin
  5. from flask import Flask,request,redirect,url_for
  6. import requests,json
  7. #初始化一个flask
  8. app = Flask(__name__)
  9. @app.route('/test', methods=['GET', 'POST'])
  10. @cross_origin()
  11. def myfirst_service():
  12. if request.method == "POST":
  13. data = request.get_data().decode()
  14. data = json.loads(data)
  15. return json.dumps(data['question'],ensure_ascii=False)
  16. if __name__ == "__main__":
  17. app.run(host='0.0.0.0',port=8080,threaded=True)
  18. '''
  19. 我的第一个send.py
  20. '''
  21. import requests
  22. import json
  23. url = 'http://127.0.0.1:8080/test'
  24. question = '你好啊,我的第一个flask'
  25. data = {
  26. 'question':question
  27. }
  28. print(requests.post(url,data=json.dumps(data)).json())
  29. #service
  30. from flask_cors import cross_origin
  31. from flask import Flask,request,redirect,url_for
  32. import requests,json
  33. from mychatbot import template,CorpusSearch,GraphSearch,InterNet
  34. #global
  35. app = Flask(__name__)
  36. #init the chatbot
  37. template_model = template()
  38. CorpusSearch_model = CorpusSearch()
  39. GraphSearch_model = GraphSearch()
  40. InterNet_model = InterNet()
  41. @app.route('/test', methods=['GET', 'POST'])
  42. @cross_origin()
  43. def myfirst_service():
  44. if request.method == "POST":
  45. #sta_post = time.time()
  46. data = request.get_data().decode()
  47. data = json.loads(data)
  48. return json.dumps('1',ensure_ascii=False)
  49. @app.route('/template', methods=['GET', 'POST'])
  50. @cross_origin()
  51. def test_template():
  52. if request.method == "POST":
  53. #sta_post = time.time()
  54. data = request.get_data().decode()
  55. data = json.loads(data)
  56. question = data['question']
  57. answer = template_model.search_answer(question)
  58. return json.dumps(answer,ensure_ascii=False)
  59. @app.route('/CorpusSearch', methods=['GET', 'POST'])
  60. @cross_origin()
  61. def test_CorpusSearch():
  62. if request.method == "POST":
  63. #sta_post = time.time()
  64. data = request.get_data().decode()
  65. data = json.loads(data)
  66. question = data['question']
  67. answer = CorpusSearch_model.search_answer(question)
  68. return json.dumps(answer,ensure_ascii=False)
  69. @app.route('/GraphSearch', methods=['GET', 'POST'])
  70. @cross_origin()
  71. def test_GraphSearch():
  72. if request.method == "POST":
  73. #sta_post = time.time()
  74. data = request.get_data().decode()
  75. data = json.loads(data)
  76. question = data['question']
  77. answer = GraphSearch_model.search_answer(question)
  78. return json.dumps(answer,ensure_ascii=False)
  79. @app.route('/InterNet', methods=['GET', 'POST'])
  80. @cross_origin()
  81. def test_InterNet():
  82. if request.method == "POST":
  83. #sta_post = time.time()
  84. data = request.get_data().decode()
  85. data = json.loads(data)
  86. question = data['question']
  87. if '是谁' in question or '关系' in question:
  88. return json.dumps(None,ensure_ascii=False)
  89. try:
  90. answer = InterNet_model.search_answer(question)
  91. except:
  92. answer = None
  93. # except:
  94. # answer = '对不起啊,小智无法解决这个问题'
  95. return json.dumps(answer,ensure_ascii=False)
  96. if __name__ == "__main__":
  97. app.run(host='0.0.0.0',port=8080,threaded=True)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/820861
推荐阅读
相关标签
  

闽ICP备14008679号