rasa-pro 3.9.18__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of rasa-pro might be problematic. Click here for more details.

Files changed (662) hide show
  1. README.md +415 -0
  2. rasa/__init__.py +10 -0
  3. rasa/__main__.py +156 -0
  4. rasa/anonymization/__init__.py +2 -0
  5. rasa/anonymization/anonymisation_rule_yaml_reader.py +91 -0
  6. rasa/anonymization/anonymization_pipeline.py +286 -0
  7. rasa/anonymization/anonymization_rule_executor.py +260 -0
  8. rasa/anonymization/anonymization_rule_orchestrator.py +120 -0
  9. rasa/anonymization/schemas/config.yml +47 -0
  10. rasa/anonymization/utils.py +118 -0
  11. rasa/api.py +146 -0
  12. rasa/cli/__init__.py +5 -0
  13. rasa/cli/arguments/__init__.py +0 -0
  14. rasa/cli/arguments/data.py +81 -0
  15. rasa/cli/arguments/default_arguments.py +165 -0
  16. rasa/cli/arguments/evaluate.py +65 -0
  17. rasa/cli/arguments/export.py +51 -0
  18. rasa/cli/arguments/interactive.py +74 -0
  19. rasa/cli/arguments/run.py +204 -0
  20. rasa/cli/arguments/shell.py +13 -0
  21. rasa/cli/arguments/test.py +211 -0
  22. rasa/cli/arguments/train.py +263 -0
  23. rasa/cli/arguments/visualize.py +34 -0
  24. rasa/cli/arguments/x.py +30 -0
  25. rasa/cli/data.py +292 -0
  26. rasa/cli/e2e_test.py +586 -0
  27. rasa/cli/evaluate.py +222 -0
  28. rasa/cli/export.py +250 -0
  29. rasa/cli/inspect.py +63 -0
  30. rasa/cli/interactive.py +164 -0
  31. rasa/cli/license.py +65 -0
  32. rasa/cli/markers.py +78 -0
  33. rasa/cli/project_templates/__init__.py +0 -0
  34. rasa/cli/project_templates/calm/actions/__init__.py +0 -0
  35. rasa/cli/project_templates/calm/actions/action_template.py +27 -0
  36. rasa/cli/project_templates/calm/actions/add_contact.py +30 -0
  37. rasa/cli/project_templates/calm/actions/db.py +57 -0
  38. rasa/cli/project_templates/calm/actions/list_contacts.py +22 -0
  39. rasa/cli/project_templates/calm/actions/remove_contact.py +35 -0
  40. rasa/cli/project_templates/calm/config.yml +12 -0
  41. rasa/cli/project_templates/calm/credentials.yml +33 -0
  42. rasa/cli/project_templates/calm/data/flows/add_contact.yml +31 -0
  43. rasa/cli/project_templates/calm/data/flows/list_contacts.yml +14 -0
  44. rasa/cli/project_templates/calm/data/flows/remove_contact.yml +29 -0
  45. rasa/cli/project_templates/calm/db/contacts.json +10 -0
  46. rasa/cli/project_templates/calm/domain/add_contact.yml +39 -0
  47. rasa/cli/project_templates/calm/domain/list_contacts.yml +17 -0
  48. rasa/cli/project_templates/calm/domain/remove_contact.yml +38 -0
  49. rasa/cli/project_templates/calm/domain/shared.yml +10 -0
  50. rasa/cli/project_templates/calm/e2e_tests/cancelations/user_cancels_during_a_correction.yml +16 -0
  51. rasa/cli/project_templates/calm/e2e_tests/cancelations/user_changes_mind_on_a_whim.yml +7 -0
  52. rasa/cli/project_templates/calm/e2e_tests/corrections/user_corrects_contact_handle.yml +20 -0
  53. rasa/cli/project_templates/calm/e2e_tests/corrections/user_corrects_contact_name.yml +19 -0
  54. rasa/cli/project_templates/calm/e2e_tests/happy_paths/user_adds_contact_to_their_list.yml +15 -0
  55. rasa/cli/project_templates/calm/e2e_tests/happy_paths/user_lists_contacts.yml +5 -0
  56. rasa/cli/project_templates/calm/e2e_tests/happy_paths/user_removes_contact.yml +11 -0
  57. rasa/cli/project_templates/calm/e2e_tests/happy_paths/user_removes_contact_from_list.yml +12 -0
  58. rasa/cli/project_templates/calm/endpoints.yml +45 -0
  59. rasa/cli/project_templates/default/actions/__init__.py +0 -0
  60. rasa/cli/project_templates/default/actions/actions.py +27 -0
  61. rasa/cli/project_templates/default/config.yml +44 -0
  62. rasa/cli/project_templates/default/credentials.yml +33 -0
  63. rasa/cli/project_templates/default/data/nlu.yml +91 -0
  64. rasa/cli/project_templates/default/data/rules.yml +13 -0
  65. rasa/cli/project_templates/default/data/stories.yml +30 -0
  66. rasa/cli/project_templates/default/domain.yml +34 -0
  67. rasa/cli/project_templates/default/endpoints.yml +42 -0
  68. rasa/cli/project_templates/default/tests/test_stories.yml +91 -0
  69. rasa/cli/project_templates/tutorial/actions.py +22 -0
  70. rasa/cli/project_templates/tutorial/config.yml +11 -0
  71. rasa/cli/project_templates/tutorial/credentials.yml +33 -0
  72. rasa/cli/project_templates/tutorial/data/flows.yml +8 -0
  73. rasa/cli/project_templates/tutorial/data/patterns.yml +6 -0
  74. rasa/cli/project_templates/tutorial/domain.yml +21 -0
  75. rasa/cli/project_templates/tutorial/endpoints.yml +45 -0
  76. rasa/cli/run.py +135 -0
  77. rasa/cli/scaffold.py +269 -0
  78. rasa/cli/shell.py +141 -0
  79. rasa/cli/studio/__init__.py +0 -0
  80. rasa/cli/studio/download.py +62 -0
  81. rasa/cli/studio/studio.py +266 -0
  82. rasa/cli/studio/train.py +59 -0
  83. rasa/cli/studio/upload.py +77 -0
  84. rasa/cli/telemetry.py +102 -0
  85. rasa/cli/test.py +280 -0
  86. rasa/cli/train.py +260 -0
  87. rasa/cli/utils.py +464 -0
  88. rasa/cli/visualize.py +40 -0
  89. rasa/cli/x.py +206 -0
  90. rasa/constants.py +37 -0
  91. rasa/core/__init__.py +17 -0
  92. rasa/core/actions/__init__.py +0 -0
  93. rasa/core/actions/action.py +1225 -0
  94. rasa/core/actions/action_clean_stack.py +59 -0
  95. rasa/core/actions/action_exceptions.py +24 -0
  96. rasa/core/actions/action_run_slot_rejections.py +207 -0
  97. rasa/core/actions/action_trigger_chitchat.py +31 -0
  98. rasa/core/actions/action_trigger_flow.py +109 -0
  99. rasa/core/actions/action_trigger_search.py +31 -0
  100. rasa/core/actions/constants.py +5 -0
  101. rasa/core/actions/custom_action_executor.py +188 -0
  102. rasa/core/actions/forms.py +741 -0
  103. rasa/core/actions/grpc_custom_action_executor.py +251 -0
  104. rasa/core/actions/http_custom_action_executor.py +140 -0
  105. rasa/core/actions/loops.py +114 -0
  106. rasa/core/actions/two_stage_fallback.py +186 -0
  107. rasa/core/agent.py +555 -0
  108. rasa/core/auth_retry_tracker_store.py +122 -0
  109. rasa/core/brokers/__init__.py +0 -0
  110. rasa/core/brokers/broker.py +126 -0
  111. rasa/core/brokers/file.py +58 -0
  112. rasa/core/brokers/kafka.py +322 -0
  113. rasa/core/brokers/pika.py +386 -0
  114. rasa/core/brokers/sql.py +86 -0
  115. rasa/core/channels/__init__.py +55 -0
  116. rasa/core/channels/audiocodes.py +463 -0
  117. rasa/core/channels/botframework.py +338 -0
  118. rasa/core/channels/callback.py +84 -0
  119. rasa/core/channels/channel.py +419 -0
  120. rasa/core/channels/console.py +241 -0
  121. rasa/core/channels/development_inspector.py +93 -0
  122. rasa/core/channels/facebook.py +419 -0
  123. rasa/core/channels/hangouts.py +329 -0
  124. rasa/core/channels/inspector/.eslintrc.cjs +25 -0
  125. rasa/core/channels/inspector/.gitignore +23 -0
  126. rasa/core/channels/inspector/README.md +54 -0
  127. rasa/core/channels/inspector/assets/favicon.ico +0 -0
  128. rasa/core/channels/inspector/assets/rasa-chat.js +2 -0
  129. rasa/core/channels/inspector/custom.d.ts +3 -0
  130. rasa/core/channels/inspector/dist/assets/arc-b6e548fe.js +1 -0
  131. rasa/core/channels/inspector/dist/assets/array-9f3ba611.js +1 -0
  132. rasa/core/channels/inspector/dist/assets/c4Diagram-d0fbc5ce-fa03ac9e.js +10 -0
  133. rasa/core/channels/inspector/dist/assets/classDiagram-936ed81e-ee67392a.js +2 -0
  134. rasa/core/channels/inspector/dist/assets/classDiagram-v2-c3cb15f1-9b283fae.js +2 -0
  135. rasa/core/channels/inspector/dist/assets/createText-62fc7601-8b6fcc2a.js +7 -0
  136. rasa/core/channels/inspector/dist/assets/edges-f2ad444c-22e77f4f.js +4 -0
  137. rasa/core/channels/inspector/dist/assets/erDiagram-9d236eb7-60ffc87f.js +51 -0
  138. rasa/core/channels/inspector/dist/assets/flowDb-1972c806-9dd802e4.js +6 -0
  139. rasa/core/channels/inspector/dist/assets/flowDiagram-7ea5b25a-5fa1912f.js +4 -0
  140. rasa/core/channels/inspector/dist/assets/flowDiagram-v2-855bc5b3-1844e5a5.js +1 -0
  141. rasa/core/channels/inspector/dist/assets/flowchart-elk-definition-abe16c3d-622a1fd2.js +139 -0
  142. rasa/core/channels/inspector/dist/assets/ganttDiagram-9b5ea136-e285a63a.js +266 -0
  143. rasa/core/channels/inspector/dist/assets/gitGraphDiagram-99d0ae7c-f237bdca.js +70 -0
  144. rasa/core/channels/inspector/dist/assets/ibm-plex-mono-v4-latin-regular-128cfa44.ttf +0 -0
  145. rasa/core/channels/inspector/dist/assets/ibm-plex-mono-v4-latin-regular-21dbcb97.woff +0 -0
  146. rasa/core/channels/inspector/dist/assets/ibm-plex-mono-v4-latin-regular-222b5e26.svg +329 -0
  147. rasa/core/channels/inspector/dist/assets/ibm-plex-mono-v4-latin-regular-9ad89b2a.woff2 +0 -0
  148. rasa/core/channels/inspector/dist/assets/index-2c4b9a3b-4b03d70e.js +1 -0
  149. rasa/core/channels/inspector/dist/assets/index-3ee28881.css +1 -0
  150. rasa/core/channels/inspector/dist/assets/index-a5d3e69d.js +1040 -0
  151. rasa/core/channels/inspector/dist/assets/infoDiagram-736b4530-72a0fa5f.js +7 -0
  152. rasa/core/channels/inspector/dist/assets/init-77b53fdd.js +1 -0
  153. rasa/core/channels/inspector/dist/assets/journeyDiagram-df861f2b-82218c41.js +139 -0
  154. rasa/core/channels/inspector/dist/assets/lato-v14-latin-700-60c05ee4.woff +0 -0
  155. rasa/core/channels/inspector/dist/assets/lato-v14-latin-700-8335d9b8.svg +438 -0
  156. rasa/core/channels/inspector/dist/assets/lato-v14-latin-700-9cc39c75.ttf +0 -0
  157. rasa/core/channels/inspector/dist/assets/lato-v14-latin-700-ead13ccf.woff2 +0 -0
  158. rasa/core/channels/inspector/dist/assets/lato-v14-latin-regular-16705655.woff2 +0 -0
  159. rasa/core/channels/inspector/dist/assets/lato-v14-latin-regular-5aeb07f9.woff +0 -0
  160. rasa/core/channels/inspector/dist/assets/lato-v14-latin-regular-9c459044.ttf +0 -0
  161. rasa/core/channels/inspector/dist/assets/lato-v14-latin-regular-9e2898a4.svg +435 -0
  162. rasa/core/channels/inspector/dist/assets/layout-78cff630.js +1 -0
  163. rasa/core/channels/inspector/dist/assets/line-5038b469.js +1 -0
  164. rasa/core/channels/inspector/dist/assets/linear-c4fc4098.js +1 -0
  165. rasa/core/channels/inspector/dist/assets/mindmap-definition-beec6740-c33c8ea6.js +109 -0
  166. rasa/core/channels/inspector/dist/assets/ordinal-ba9b4969.js +1 -0
  167. rasa/core/channels/inspector/dist/assets/path-53f90ab3.js +1 -0
  168. rasa/core/channels/inspector/dist/assets/pieDiagram-dbbf0591-a8d03059.js +35 -0
  169. rasa/core/channels/inspector/dist/assets/quadrantDiagram-4d7f4fd6-6a0e56b2.js +7 -0
  170. rasa/core/channels/inspector/dist/assets/requirementDiagram-6fc4c22a-2dc7c7bd.js +52 -0
  171. rasa/core/channels/inspector/dist/assets/sankeyDiagram-8f13d901-2360fe39.js +8 -0
  172. rasa/core/channels/inspector/dist/assets/sequenceDiagram-b655622a-41b9f9ad.js +122 -0
  173. rasa/core/channels/inspector/dist/assets/stateDiagram-59f0c015-0aad326f.js +1 -0
  174. rasa/core/channels/inspector/dist/assets/stateDiagram-v2-2b26beab-9847d984.js +1 -0
  175. rasa/core/channels/inspector/dist/assets/styles-080da4f6-564d890e.js +110 -0
  176. rasa/core/channels/inspector/dist/assets/styles-3dcbcfbf-38957613.js +159 -0
  177. rasa/core/channels/inspector/dist/assets/styles-9c745c82-f0fc6921.js +207 -0
  178. rasa/core/channels/inspector/dist/assets/svgDrawCommon-4835440b-ef3c5a77.js +1 -0
  179. rasa/core/channels/inspector/dist/assets/timeline-definition-5b62e21b-bf3e91c1.js +61 -0
  180. rasa/core/channels/inspector/dist/assets/xychartDiagram-2b33534f-4d4026c0.js +7 -0
  181. rasa/core/channels/inspector/dist/index.html +41 -0
  182. rasa/core/channels/inspector/index.html +39 -0
  183. rasa/core/channels/inspector/jest.config.ts +13 -0
  184. rasa/core/channels/inspector/package.json +48 -0
  185. rasa/core/channels/inspector/setupTests.ts +2 -0
  186. rasa/core/channels/inspector/src/App.tsx +170 -0
  187. rasa/core/channels/inspector/src/components/DiagramFlow.tsx +107 -0
  188. rasa/core/channels/inspector/src/components/DialogueInformation.tsx +187 -0
  189. rasa/core/channels/inspector/src/components/DialogueStack.tsx +151 -0
  190. rasa/core/channels/inspector/src/components/ExpandIcon.tsx +16 -0
  191. rasa/core/channels/inspector/src/components/FullscreenButton.tsx +45 -0
  192. rasa/core/channels/inspector/src/components/LoadingSpinner.tsx +19 -0
  193. rasa/core/channels/inspector/src/components/NoActiveFlow.tsx +21 -0
  194. rasa/core/channels/inspector/src/components/RasaLogo.tsx +32 -0
  195. rasa/core/channels/inspector/src/components/SaraDiagrams.tsx +39 -0
  196. rasa/core/channels/inspector/src/components/Slots.tsx +91 -0
  197. rasa/core/channels/inspector/src/components/Welcome.tsx +54 -0
  198. rasa/core/channels/inspector/src/helpers/formatters.test.ts +382 -0
  199. rasa/core/channels/inspector/src/helpers/formatters.ts +240 -0
  200. rasa/core/channels/inspector/src/helpers/utils.ts +42 -0
  201. rasa/core/channels/inspector/src/main.tsx +13 -0
  202. rasa/core/channels/inspector/src/theme/Button/Button.ts +29 -0
  203. rasa/core/channels/inspector/src/theme/Heading/Heading.ts +31 -0
  204. rasa/core/channels/inspector/src/theme/Input/Input.ts +27 -0
  205. rasa/core/channels/inspector/src/theme/Link/Link.ts +10 -0
  206. rasa/core/channels/inspector/src/theme/Modal/Modal.ts +47 -0
  207. rasa/core/channels/inspector/src/theme/Table/Table.tsx +38 -0
  208. rasa/core/channels/inspector/src/theme/Tooltip/Tooltip.ts +12 -0
  209. rasa/core/channels/inspector/src/theme/base/breakpoints.ts +8 -0
  210. rasa/core/channels/inspector/src/theme/base/colors.ts +88 -0
  211. rasa/core/channels/inspector/src/theme/base/fonts/fontFaces.css +29 -0
  212. rasa/core/channels/inspector/src/theme/base/fonts/ibm-plex-mono-v4-latin/ibm-plex-mono-v4-latin-regular.eot +0 -0
  213. rasa/core/channels/inspector/src/theme/base/fonts/ibm-plex-mono-v4-latin/ibm-plex-mono-v4-latin-regular.svg +329 -0
  214. rasa/core/channels/inspector/src/theme/base/fonts/ibm-plex-mono-v4-latin/ibm-plex-mono-v4-latin-regular.ttf +0 -0
  215. rasa/core/channels/inspector/src/theme/base/fonts/ibm-plex-mono-v4-latin/ibm-plex-mono-v4-latin-regular.woff +0 -0
  216. rasa/core/channels/inspector/src/theme/base/fonts/ibm-plex-mono-v4-latin/ibm-plex-mono-v4-latin-regular.woff2 +0 -0
  217. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-700.eot +0 -0
  218. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-700.svg +438 -0
  219. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-700.ttf +0 -0
  220. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-700.woff +0 -0
  221. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-700.woff2 +0 -0
  222. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-regular.eot +0 -0
  223. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-regular.svg +435 -0
  224. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-regular.ttf +0 -0
  225. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-regular.woff +0 -0
  226. rasa/core/channels/inspector/src/theme/base/fonts/lato-v14-latin/lato-v14-latin-regular.woff2 +0 -0
  227. rasa/core/channels/inspector/src/theme/base/radii.ts +9 -0
  228. rasa/core/channels/inspector/src/theme/base/shadows.ts +7 -0
  229. rasa/core/channels/inspector/src/theme/base/sizes.ts +7 -0
  230. rasa/core/channels/inspector/src/theme/base/space.ts +15 -0
  231. rasa/core/channels/inspector/src/theme/base/styles.ts +13 -0
  232. rasa/core/channels/inspector/src/theme/base/typography.ts +24 -0
  233. rasa/core/channels/inspector/src/theme/base/zIndices.ts +19 -0
  234. rasa/core/channels/inspector/src/theme/index.ts +101 -0
  235. rasa/core/channels/inspector/src/types.ts +64 -0
  236. rasa/core/channels/inspector/src/vite-env.d.ts +1 -0
  237. rasa/core/channels/inspector/tests/__mocks__/fileMock.ts +1 -0
  238. rasa/core/channels/inspector/tests/__mocks__/matchMedia.ts +16 -0
  239. rasa/core/channels/inspector/tests/__mocks__/styleMock.ts +1 -0
  240. rasa/core/channels/inspector/tests/renderWithProviders.tsx +14 -0
  241. rasa/core/channels/inspector/tsconfig.json +26 -0
  242. rasa/core/channels/inspector/tsconfig.node.json +10 -0
  243. rasa/core/channels/inspector/vite.config.ts +8 -0
  244. rasa/core/channels/inspector/yarn.lock +6156 -0
  245. rasa/core/channels/mattermost.py +229 -0
  246. rasa/core/channels/rasa_chat.py +126 -0
  247. rasa/core/channels/rest.py +225 -0
  248. rasa/core/channels/rocketchat.py +174 -0
  249. rasa/core/channels/slack.py +620 -0
  250. rasa/core/channels/socketio.py +274 -0
  251. rasa/core/channels/telegram.py +298 -0
  252. rasa/core/channels/twilio.py +169 -0
  253. rasa/core/channels/twilio_voice.py +367 -0
  254. rasa/core/channels/vier_cvg.py +374 -0
  255. rasa/core/channels/webexteams.py +134 -0
  256. rasa/core/concurrent_lock_store.py +210 -0
  257. rasa/core/constants.py +107 -0
  258. rasa/core/evaluation/__init__.py +0 -0
  259. rasa/core/evaluation/marker.py +267 -0
  260. rasa/core/evaluation/marker_base.py +923 -0
  261. rasa/core/evaluation/marker_stats.py +293 -0
  262. rasa/core/evaluation/marker_tracker_loader.py +103 -0
  263. rasa/core/exceptions.py +29 -0
  264. rasa/core/exporter.py +284 -0
  265. rasa/core/featurizers/__init__.py +0 -0
  266. rasa/core/featurizers/precomputation.py +410 -0
  267. rasa/core/featurizers/single_state_featurizer.py +421 -0
  268. rasa/core/featurizers/tracker_featurizers.py +1262 -0
  269. rasa/core/http_interpreter.py +89 -0
  270. rasa/core/information_retrieval/__init__.py +7 -0
  271. rasa/core/information_retrieval/faiss.py +121 -0
  272. rasa/core/information_retrieval/information_retrieval.py +129 -0
  273. rasa/core/information_retrieval/milvus.py +52 -0
  274. rasa/core/information_retrieval/qdrant.py +95 -0
  275. rasa/core/jobs.py +63 -0
  276. rasa/core/lock.py +139 -0
  277. rasa/core/lock_store.py +343 -0
  278. rasa/core/migrate.py +403 -0
  279. rasa/core/nlg/__init__.py +3 -0
  280. rasa/core/nlg/callback.py +146 -0
  281. rasa/core/nlg/contextual_response_rephraser.py +270 -0
  282. rasa/core/nlg/generator.py +230 -0
  283. rasa/core/nlg/interpolator.py +143 -0
  284. rasa/core/nlg/response.py +155 -0
  285. rasa/core/nlg/summarize.py +69 -0
  286. rasa/core/policies/__init__.py +0 -0
  287. rasa/core/policies/ensemble.py +329 -0
  288. rasa/core/policies/enterprise_search_policy.py +781 -0
  289. rasa/core/policies/enterprise_search_prompt_template.jinja2 +25 -0
  290. rasa/core/policies/enterprise_search_prompt_with_citation_template.jinja2 +60 -0
  291. rasa/core/policies/flow_policy.py +205 -0
  292. rasa/core/policies/flows/__init__.py +0 -0
  293. rasa/core/policies/flows/flow_exceptions.py +44 -0
  294. rasa/core/policies/flows/flow_executor.py +705 -0
  295. rasa/core/policies/flows/flow_step_result.py +43 -0
  296. rasa/core/policies/intentless_policy.py +922 -0
  297. rasa/core/policies/intentless_prompt_template.jinja2 +22 -0
  298. rasa/core/policies/memoization.py +538 -0
  299. rasa/core/policies/policy.py +725 -0
  300. rasa/core/policies/rule_policy.py +1273 -0
  301. rasa/core/policies/ted_policy.py +2169 -0
  302. rasa/core/policies/unexpected_intent_policy.py +1022 -0
  303. rasa/core/processor.py +1422 -0
  304. rasa/core/run.py +331 -0
  305. rasa/core/secrets_manager/__init__.py +0 -0
  306. rasa/core/secrets_manager/constants.py +32 -0
  307. rasa/core/secrets_manager/endpoints.py +391 -0
  308. rasa/core/secrets_manager/factory.py +233 -0
  309. rasa/core/secrets_manager/secret_manager.py +262 -0
  310. rasa/core/secrets_manager/vault.py +574 -0
  311. rasa/core/test.py +1335 -0
  312. rasa/core/tracker_store.py +1699 -0
  313. rasa/core/train.py +105 -0
  314. rasa/core/training/__init__.py +89 -0
  315. rasa/core/training/converters/__init__.py +0 -0
  316. rasa/core/training/converters/responses_prefix_converter.py +119 -0
  317. rasa/core/training/interactive.py +1745 -0
  318. rasa/core/training/story_conflict.py +381 -0
  319. rasa/core/training/training.py +93 -0
  320. rasa/core/utils.py +339 -0
  321. rasa/core/visualize.py +70 -0
  322. rasa/dialogue_understanding/__init__.py +0 -0
  323. rasa/dialogue_understanding/coexistence/__init__.py +0 -0
  324. rasa/dialogue_understanding/coexistence/constants.py +4 -0
  325. rasa/dialogue_understanding/coexistence/intent_based_router.py +196 -0
  326. rasa/dialogue_understanding/coexistence/llm_based_router.py +260 -0
  327. rasa/dialogue_understanding/coexistence/router_template.jinja2 +12 -0
  328. rasa/dialogue_understanding/commands/__init__.py +49 -0
  329. rasa/dialogue_understanding/commands/can_not_handle_command.py +70 -0
  330. rasa/dialogue_understanding/commands/cancel_flow_command.py +125 -0
  331. rasa/dialogue_understanding/commands/change_flow_command.py +44 -0
  332. rasa/dialogue_understanding/commands/chit_chat_answer_command.py +57 -0
  333. rasa/dialogue_understanding/commands/clarify_command.py +86 -0
  334. rasa/dialogue_understanding/commands/command.py +85 -0
  335. rasa/dialogue_understanding/commands/correct_slots_command.py +297 -0
  336. rasa/dialogue_understanding/commands/error_command.py +79 -0
  337. rasa/dialogue_understanding/commands/free_form_answer_command.py +9 -0
  338. rasa/dialogue_understanding/commands/handle_code_change_command.py +73 -0
  339. rasa/dialogue_understanding/commands/human_handoff_command.py +66 -0
  340. rasa/dialogue_understanding/commands/knowledge_answer_command.py +57 -0
  341. rasa/dialogue_understanding/commands/noop_command.py +54 -0
  342. rasa/dialogue_understanding/commands/set_slot_command.py +160 -0
  343. rasa/dialogue_understanding/commands/skip_question_command.py +75 -0
  344. rasa/dialogue_understanding/commands/start_flow_command.py +107 -0
  345. rasa/dialogue_understanding/generator/__init__.py +21 -0
  346. rasa/dialogue_understanding/generator/command_generator.py +343 -0
  347. rasa/dialogue_understanding/generator/constants.py +18 -0
  348. rasa/dialogue_understanding/generator/flow_document_template.jinja2 +4 -0
  349. rasa/dialogue_understanding/generator/flow_retrieval.py +412 -0
  350. rasa/dialogue_understanding/generator/llm_based_command_generator.py +467 -0
  351. rasa/dialogue_understanding/generator/llm_command_generator.py +67 -0
  352. rasa/dialogue_understanding/generator/multi_step/__init__.py +0 -0
  353. rasa/dialogue_understanding/generator/multi_step/fill_slots_prompt.jinja2 +62 -0
  354. rasa/dialogue_understanding/generator/multi_step/handle_flows_prompt.jinja2 +38 -0
  355. rasa/dialogue_understanding/generator/multi_step/multi_step_llm_command_generator.py +827 -0
  356. rasa/dialogue_understanding/generator/nlu_command_adapter.py +218 -0
  357. rasa/dialogue_understanding/generator/single_step/__init__.py +0 -0
  358. rasa/dialogue_understanding/generator/single_step/command_prompt_template.jinja2 +57 -0
  359. rasa/dialogue_understanding/generator/single_step/single_step_llm_command_generator.py +345 -0
  360. rasa/dialogue_understanding/patterns/__init__.py +0 -0
  361. rasa/dialogue_understanding/patterns/cancel.py +111 -0
  362. rasa/dialogue_understanding/patterns/cannot_handle.py +43 -0
  363. rasa/dialogue_understanding/patterns/chitchat.py +37 -0
  364. rasa/dialogue_understanding/patterns/clarify.py +97 -0
  365. rasa/dialogue_understanding/patterns/code_change.py +41 -0
  366. rasa/dialogue_understanding/patterns/collect_information.py +90 -0
  367. rasa/dialogue_understanding/patterns/completed.py +40 -0
  368. rasa/dialogue_understanding/patterns/continue_interrupted.py +42 -0
  369. rasa/dialogue_understanding/patterns/correction.py +278 -0
  370. rasa/dialogue_understanding/patterns/default_flows_for_patterns.yml +248 -0
  371. rasa/dialogue_understanding/patterns/human_handoff.py +37 -0
  372. rasa/dialogue_understanding/patterns/internal_error.py +47 -0
  373. rasa/dialogue_understanding/patterns/search.py +37 -0
  374. rasa/dialogue_understanding/patterns/skip_question.py +38 -0
  375. rasa/dialogue_understanding/processor/__init__.py +0 -0
  376. rasa/dialogue_understanding/processor/command_processor.py +687 -0
  377. rasa/dialogue_understanding/processor/command_processor_component.py +39 -0
  378. rasa/dialogue_understanding/stack/__init__.py +0 -0
  379. rasa/dialogue_understanding/stack/dialogue_stack.py +178 -0
  380. rasa/dialogue_understanding/stack/frames/__init__.py +19 -0
  381. rasa/dialogue_understanding/stack/frames/chit_chat_frame.py +27 -0
  382. rasa/dialogue_understanding/stack/frames/dialogue_stack_frame.py +137 -0
  383. rasa/dialogue_understanding/stack/frames/flow_stack_frame.py +157 -0
  384. rasa/dialogue_understanding/stack/frames/pattern_frame.py +10 -0
  385. rasa/dialogue_understanding/stack/frames/search_frame.py +27 -0
  386. rasa/dialogue_understanding/stack/utils.py +211 -0
  387. rasa/e2e_test/__init__.py +0 -0
  388. rasa/e2e_test/constants.py +11 -0
  389. rasa/e2e_test/e2e_test_case.py +366 -0
  390. rasa/e2e_test/e2e_test_result.py +34 -0
  391. rasa/e2e_test/e2e_test_runner.py +768 -0
  392. rasa/e2e_test/e2e_test_schema.yml +85 -0
  393. rasa/engine/__init__.py +0 -0
  394. rasa/engine/caching.py +463 -0
  395. rasa/engine/constants.py +17 -0
  396. rasa/engine/exceptions.py +14 -0
  397. rasa/engine/graph.py +637 -0
  398. rasa/engine/loader.py +36 -0
  399. rasa/engine/recipes/__init__.py +0 -0
  400. rasa/engine/recipes/config_files/default_config.yml +44 -0
  401. rasa/engine/recipes/default_components.py +99 -0
  402. rasa/engine/recipes/default_recipe.py +1251 -0
  403. rasa/engine/recipes/graph_recipe.py +79 -0
  404. rasa/engine/recipes/recipe.py +93 -0
  405. rasa/engine/runner/__init__.py +0 -0
  406. rasa/engine/runner/dask.py +250 -0
  407. rasa/engine/runner/interface.py +49 -0
  408. rasa/engine/storage/__init__.py +0 -0
  409. rasa/engine/storage/local_model_storage.py +246 -0
  410. rasa/engine/storage/resource.py +110 -0
  411. rasa/engine/storage/storage.py +203 -0
  412. rasa/engine/training/__init__.py +0 -0
  413. rasa/engine/training/components.py +176 -0
  414. rasa/engine/training/fingerprinting.py +64 -0
  415. rasa/engine/training/graph_trainer.py +256 -0
  416. rasa/engine/training/hooks.py +164 -0
  417. rasa/engine/validation.py +873 -0
  418. rasa/env.py +5 -0
  419. rasa/exceptions.py +69 -0
  420. rasa/graph_components/__init__.py +0 -0
  421. rasa/graph_components/converters/__init__.py +0 -0
  422. rasa/graph_components/converters/nlu_message_converter.py +48 -0
  423. rasa/graph_components/providers/__init__.py +0 -0
  424. rasa/graph_components/providers/domain_for_core_training_provider.py +87 -0
  425. rasa/graph_components/providers/domain_provider.py +71 -0
  426. rasa/graph_components/providers/flows_provider.py +74 -0
  427. rasa/graph_components/providers/forms_provider.py +44 -0
  428. rasa/graph_components/providers/nlu_training_data_provider.py +56 -0
  429. rasa/graph_components/providers/responses_provider.py +44 -0
  430. rasa/graph_components/providers/rule_only_provider.py +49 -0
  431. rasa/graph_components/providers/story_graph_provider.py +43 -0
  432. rasa/graph_components/providers/training_tracker_provider.py +55 -0
  433. rasa/graph_components/validators/__init__.py +0 -0
  434. rasa/graph_components/validators/default_recipe_validator.py +550 -0
  435. rasa/graph_components/validators/finetuning_validator.py +302 -0
  436. rasa/hooks.py +112 -0
  437. rasa/jupyter.py +63 -0
  438. rasa/markers/__init__.py +0 -0
  439. rasa/markers/marker.py +269 -0
  440. rasa/markers/marker_base.py +828 -0
  441. rasa/markers/upload.py +74 -0
  442. rasa/markers/validate.py +21 -0
  443. rasa/model.py +118 -0
  444. rasa/model_testing.py +457 -0
  445. rasa/model_training.py +536 -0
  446. rasa/nlu/__init__.py +7 -0
  447. rasa/nlu/classifiers/__init__.py +3 -0
  448. rasa/nlu/classifiers/classifier.py +5 -0
  449. rasa/nlu/classifiers/diet_classifier.py +1881 -0
  450. rasa/nlu/classifiers/fallback_classifier.py +192 -0
  451. rasa/nlu/classifiers/keyword_intent_classifier.py +188 -0
  452. rasa/nlu/classifiers/llm_intent_classifier.py +519 -0
  453. rasa/nlu/classifiers/logistic_regression_classifier.py +253 -0
  454. rasa/nlu/classifiers/mitie_intent_classifier.py +156 -0
  455. rasa/nlu/classifiers/regex_message_handler.py +56 -0
  456. rasa/nlu/classifiers/sklearn_intent_classifier.py +330 -0
  457. rasa/nlu/constants.py +77 -0
  458. rasa/nlu/convert.py +40 -0
  459. rasa/nlu/emulators/__init__.py +0 -0
  460. rasa/nlu/emulators/dialogflow.py +55 -0
  461. rasa/nlu/emulators/emulator.py +49 -0
  462. rasa/nlu/emulators/luis.py +86 -0
  463. rasa/nlu/emulators/no_emulator.py +10 -0
  464. rasa/nlu/emulators/wit.py +56 -0
  465. rasa/nlu/extractors/__init__.py +0 -0
  466. rasa/nlu/extractors/crf_entity_extractor.py +715 -0
  467. rasa/nlu/extractors/duckling_entity_extractor.py +206 -0
  468. rasa/nlu/extractors/entity_synonyms.py +178 -0
  469. rasa/nlu/extractors/extractor.py +470 -0
  470. rasa/nlu/extractors/mitie_entity_extractor.py +293 -0
  471. rasa/nlu/extractors/regex_entity_extractor.py +220 -0
  472. rasa/nlu/extractors/spacy_entity_extractor.py +95 -0
  473. rasa/nlu/featurizers/__init__.py +0 -0
  474. rasa/nlu/featurizers/dense_featurizer/__init__.py +0 -0
  475. rasa/nlu/featurizers/dense_featurizer/convert_featurizer.py +445 -0
  476. rasa/nlu/featurizers/dense_featurizer/dense_featurizer.py +57 -0
  477. rasa/nlu/featurizers/dense_featurizer/lm_featurizer.py +768 -0
  478. rasa/nlu/featurizers/dense_featurizer/mitie_featurizer.py +170 -0
  479. rasa/nlu/featurizers/dense_featurizer/spacy_featurizer.py +132 -0
  480. rasa/nlu/featurizers/featurizer.py +89 -0
  481. rasa/nlu/featurizers/sparse_featurizer/__init__.py +0 -0
  482. rasa/nlu/featurizers/sparse_featurizer/count_vectors_featurizer.py +867 -0
  483. rasa/nlu/featurizers/sparse_featurizer/lexical_syntactic_featurizer.py +571 -0
  484. rasa/nlu/featurizers/sparse_featurizer/regex_featurizer.py +271 -0
  485. rasa/nlu/featurizers/sparse_featurizer/sparse_featurizer.py +9 -0
  486. rasa/nlu/model.py +24 -0
  487. rasa/nlu/persistor.py +282 -0
  488. rasa/nlu/run.py +27 -0
  489. rasa/nlu/selectors/__init__.py +0 -0
  490. rasa/nlu/selectors/response_selector.py +987 -0
  491. rasa/nlu/test.py +1940 -0
  492. rasa/nlu/tokenizers/__init__.py +0 -0
  493. rasa/nlu/tokenizers/jieba_tokenizer.py +148 -0
  494. rasa/nlu/tokenizers/mitie_tokenizer.py +75 -0
  495. rasa/nlu/tokenizers/spacy_tokenizer.py +72 -0
  496. rasa/nlu/tokenizers/tokenizer.py +239 -0
  497. rasa/nlu/tokenizers/whitespace_tokenizer.py +106 -0
  498. rasa/nlu/utils/__init__.py +35 -0
  499. rasa/nlu/utils/bilou_utils.py +462 -0
  500. rasa/nlu/utils/hugging_face/__init__.py +0 -0
  501. rasa/nlu/utils/hugging_face/registry.py +108 -0
  502. rasa/nlu/utils/hugging_face/transformers_pre_post_processors.py +311 -0
  503. rasa/nlu/utils/mitie_utils.py +113 -0
  504. rasa/nlu/utils/pattern_utils.py +168 -0
  505. rasa/nlu/utils/spacy_utils.py +310 -0
  506. rasa/plugin.py +90 -0
  507. rasa/server.py +1551 -0
  508. rasa/shared/__init__.py +0 -0
  509. rasa/shared/constants.py +192 -0
  510. rasa/shared/core/__init__.py +0 -0
  511. rasa/shared/core/command_payload_reader.py +109 -0
  512. rasa/shared/core/constants.py +167 -0
  513. rasa/shared/core/conversation.py +46 -0
  514. rasa/shared/core/domain.py +2107 -0
  515. rasa/shared/core/events.py +2504 -0
  516. rasa/shared/core/flows/__init__.py +7 -0
  517. rasa/shared/core/flows/flow.py +362 -0
  518. rasa/shared/core/flows/flow_step.py +146 -0
  519. rasa/shared/core/flows/flow_step_links.py +319 -0
  520. rasa/shared/core/flows/flow_step_sequence.py +70 -0
  521. rasa/shared/core/flows/flows_list.py +223 -0
  522. rasa/shared/core/flows/flows_yaml_schema.json +217 -0
  523. rasa/shared/core/flows/nlu_trigger.py +117 -0
  524. rasa/shared/core/flows/steps/__init__.py +24 -0
  525. rasa/shared/core/flows/steps/action.py +56 -0
  526. rasa/shared/core/flows/steps/call.py +64 -0
  527. rasa/shared/core/flows/steps/collect.py +112 -0
  528. rasa/shared/core/flows/steps/constants.py +5 -0
  529. rasa/shared/core/flows/steps/continuation.py +36 -0
  530. rasa/shared/core/flows/steps/end.py +22 -0
  531. rasa/shared/core/flows/steps/internal.py +44 -0
  532. rasa/shared/core/flows/steps/link.py +51 -0
  533. rasa/shared/core/flows/steps/no_operation.py +48 -0
  534. rasa/shared/core/flows/steps/set_slots.py +50 -0
  535. rasa/shared/core/flows/steps/start.py +30 -0
  536. rasa/shared/core/flows/validation.py +527 -0
  537. rasa/shared/core/flows/yaml_flows_io.py +278 -0
  538. rasa/shared/core/generator.py +908 -0
  539. rasa/shared/core/slot_mappings.py +526 -0
  540. rasa/shared/core/slots.py +649 -0
  541. rasa/shared/core/trackers.py +1177 -0
  542. rasa/shared/core/training_data/__init__.py +0 -0
  543. rasa/shared/core/training_data/loading.py +89 -0
  544. rasa/shared/core/training_data/story_reader/__init__.py +0 -0
  545. rasa/shared/core/training_data/story_reader/story_reader.py +129 -0
  546. rasa/shared/core/training_data/story_reader/story_step_builder.py +168 -0
  547. rasa/shared/core/training_data/story_reader/yaml_story_reader.py +888 -0
  548. rasa/shared/core/training_data/story_writer/__init__.py +0 -0
  549. rasa/shared/core/training_data/story_writer/story_writer.py +76 -0
  550. rasa/shared/core/training_data/story_writer/yaml_story_writer.py +444 -0
  551. rasa/shared/core/training_data/structures.py +838 -0
  552. rasa/shared/core/training_data/visualization.html +146 -0
  553. rasa/shared/core/training_data/visualization.py +603 -0
  554. rasa/shared/data.py +249 -0
  555. rasa/shared/engine/__init__.py +0 -0
  556. rasa/shared/engine/caching.py +26 -0
  557. rasa/shared/exceptions.py +163 -0
  558. rasa/shared/importers/__init__.py +0 -0
  559. rasa/shared/importers/importer.py +704 -0
  560. rasa/shared/importers/multi_project.py +203 -0
  561. rasa/shared/importers/rasa.py +99 -0
  562. rasa/shared/importers/utils.py +34 -0
  563. rasa/shared/nlu/__init__.py +0 -0
  564. rasa/shared/nlu/constants.py +47 -0
  565. rasa/shared/nlu/interpreter.py +10 -0
  566. rasa/shared/nlu/training_data/__init__.py +0 -0
  567. rasa/shared/nlu/training_data/entities_parser.py +208 -0
  568. rasa/shared/nlu/training_data/features.py +492 -0
  569. rasa/shared/nlu/training_data/formats/__init__.py +10 -0
  570. rasa/shared/nlu/training_data/formats/dialogflow.py +163 -0
  571. rasa/shared/nlu/training_data/formats/luis.py +87 -0
  572. rasa/shared/nlu/training_data/formats/rasa.py +135 -0
  573. rasa/shared/nlu/training_data/formats/rasa_yaml.py +603 -0
  574. rasa/shared/nlu/training_data/formats/readerwriter.py +244 -0
  575. rasa/shared/nlu/training_data/formats/wit.py +52 -0
  576. rasa/shared/nlu/training_data/loading.py +137 -0
  577. rasa/shared/nlu/training_data/lookup_tables_parser.py +30 -0
  578. rasa/shared/nlu/training_data/message.py +490 -0
  579. rasa/shared/nlu/training_data/schemas/__init__.py +0 -0
  580. rasa/shared/nlu/training_data/schemas/data_schema.py +85 -0
  581. rasa/shared/nlu/training_data/schemas/nlu.yml +53 -0
  582. rasa/shared/nlu/training_data/schemas/responses.yml +70 -0
  583. rasa/shared/nlu/training_data/synonyms_parser.py +42 -0
  584. rasa/shared/nlu/training_data/training_data.py +730 -0
  585. rasa/shared/nlu/training_data/util.py +223 -0
  586. rasa/shared/providers/__init__.py +0 -0
  587. rasa/shared/providers/openai/__init__.py +0 -0
  588. rasa/shared/providers/openai/clients.py +43 -0
  589. rasa/shared/providers/openai/session_handler.py +110 -0
  590. rasa/shared/utils/__init__.py +0 -0
  591. rasa/shared/utils/cli.py +72 -0
  592. rasa/shared/utils/common.py +308 -0
  593. rasa/shared/utils/constants.py +4 -0
  594. rasa/shared/utils/io.py +415 -0
  595. rasa/shared/utils/llm.py +404 -0
  596. rasa/shared/utils/pykwalify_extensions.py +27 -0
  597. rasa/shared/utils/schemas/__init__.py +0 -0
  598. rasa/shared/utils/schemas/config.yml +2 -0
  599. rasa/shared/utils/schemas/domain.yml +145 -0
  600. rasa/shared/utils/schemas/events.py +212 -0
  601. rasa/shared/utils/schemas/model_config.yml +46 -0
  602. rasa/shared/utils/schemas/stories.yml +173 -0
  603. rasa/shared/utils/yaml.py +786 -0
  604. rasa/studio/__init__.py +0 -0
  605. rasa/studio/auth.py +268 -0
  606. rasa/studio/config.py +127 -0
  607. rasa/studio/constants.py +18 -0
  608. rasa/studio/data_handler.py +359 -0
  609. rasa/studio/download.py +483 -0
  610. rasa/studio/results_logger.py +137 -0
  611. rasa/studio/train.py +135 -0
  612. rasa/studio/upload.py +433 -0
  613. rasa/telemetry.py +1737 -0
  614. rasa/tracing/__init__.py +0 -0
  615. rasa/tracing/config.py +353 -0
  616. rasa/tracing/constants.py +62 -0
  617. rasa/tracing/instrumentation/__init__.py +0 -0
  618. rasa/tracing/instrumentation/attribute_extractors.py +672 -0
  619. rasa/tracing/instrumentation/instrumentation.py +1185 -0
  620. rasa/tracing/instrumentation/intentless_policy_instrumentation.py +144 -0
  621. rasa/tracing/instrumentation/metrics.py +294 -0
  622. rasa/tracing/metric_instrument_provider.py +205 -0
  623. rasa/utils/__init__.py +0 -0
  624. rasa/utils/beta.py +83 -0
  625. rasa/utils/cli.py +28 -0
  626. rasa/utils/common.py +635 -0
  627. rasa/utils/converter.py +53 -0
  628. rasa/utils/endpoints.py +302 -0
  629. rasa/utils/io.py +260 -0
  630. rasa/utils/licensing.py +534 -0
  631. rasa/utils/log_utils.py +174 -0
  632. rasa/utils/mapper.py +210 -0
  633. rasa/utils/ml_utils.py +145 -0
  634. rasa/utils/plotting.py +362 -0
  635. rasa/utils/singleton.py +23 -0
  636. rasa/utils/tensorflow/__init__.py +0 -0
  637. rasa/utils/tensorflow/callback.py +112 -0
  638. rasa/utils/tensorflow/constants.py +116 -0
  639. rasa/utils/tensorflow/crf.py +492 -0
  640. rasa/utils/tensorflow/data_generator.py +440 -0
  641. rasa/utils/tensorflow/environment.py +161 -0
  642. rasa/utils/tensorflow/exceptions.py +5 -0
  643. rasa/utils/tensorflow/feature_array.py +366 -0
  644. rasa/utils/tensorflow/layers.py +1565 -0
  645. rasa/utils/tensorflow/layers_utils.py +113 -0
  646. rasa/utils/tensorflow/metrics.py +281 -0
  647. rasa/utils/tensorflow/model_data.py +798 -0
  648. rasa/utils/tensorflow/model_data_utils.py +499 -0
  649. rasa/utils/tensorflow/models.py +935 -0
  650. rasa/utils/tensorflow/rasa_layers.py +1094 -0
  651. rasa/utils/tensorflow/transformer.py +640 -0
  652. rasa/utils/tensorflow/types.py +6 -0
  653. rasa/utils/train_utils.py +572 -0
  654. rasa/utils/url_tools.py +53 -0
  655. rasa/utils/yaml.py +54 -0
  656. rasa/validator.py +1337 -0
  657. rasa/version.py +3 -0
  658. rasa_pro-3.9.18.dist-info/METADATA +563 -0
  659. rasa_pro-3.9.18.dist-info/NOTICE +5 -0
  660. rasa_pro-3.9.18.dist-info/RECORD +662 -0
  661. rasa_pro-3.9.18.dist-info/WHEEL +4 -0
  662. rasa_pro-3.9.18.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,1745 @@
1
+ import asyncio
2
+ import logging
3
+ import os
4
+ import textwrap
5
+ import uuid
6
+ import warnings
7
+ from functools import partial
8
+ from multiprocessing import Process
9
+ from typing import (
10
+ Any,
11
+ Callable,
12
+ Deque,
13
+ Dict,
14
+ List,
15
+ Optional,
16
+ Text,
17
+ Tuple,
18
+ Union,
19
+ Set,
20
+ cast,
21
+ )
22
+
23
+ from sanic import Sanic, response
24
+ from sanic.exceptions import NotFound
25
+ from sanic.request import Request
26
+ from sanic.response import HTTPResponse
27
+ from terminaltables import AsciiTable, SingleTable
28
+ import terminaltables.width_and_alignment
29
+ import numpy as np
30
+ from aiohttp import ClientError
31
+ from colorclass import Color
32
+ import questionary
33
+ from questionary import Choice, Form, Question
34
+
35
+ from rasa import telemetry
36
+ import rasa.shared.utils.cli
37
+ import rasa.shared.utils.io
38
+ import rasa.cli.utils
39
+ import rasa.shared.data
40
+ from rasa.shared.nlu.constants import TEXT, INTENT_NAME_KEY
41
+ from rasa.shared.nlu.training_data.loading import RASA, RASA_YAML
42
+ from rasa.shared.core.constants import (
43
+ USER_INTENT_RESTART,
44
+ ACTION_LISTEN_NAME,
45
+ LOOP_NAME,
46
+ ACTIVE_LOOP,
47
+ LOOP_REJECTED,
48
+ REQUESTED_SLOT,
49
+ LOOP_INTERRUPTED,
50
+ ACTION_UNLIKELY_INTENT_NAME,
51
+ )
52
+ from rasa.core import run, utils
53
+ import rasa.core.train
54
+ from rasa.core.constants import DEFAULT_SERVER_FORMAT, DEFAULT_SERVER_PORT
55
+ from rasa.shared.core.domain import (
56
+ Domain,
57
+ KEY_INTENTS,
58
+ KEY_ENTITIES,
59
+ KEY_RESPONSES,
60
+ KEY_ACTIONS,
61
+ KEY_RESPONSES_TEXT,
62
+ )
63
+ import rasa.shared.core.events
64
+ from rasa.shared.core.events import (
65
+ ActionExecuted,
66
+ ActionReverted,
67
+ BotUttered,
68
+ Event,
69
+ Restarted,
70
+ UserUttered,
71
+ UserUtteranceReverted,
72
+ )
73
+ from rasa.shared.constants import (
74
+ INTENT_MESSAGE_PREFIX,
75
+ DEFAULT_SENDER_ID,
76
+ UTTER_PREFIX,
77
+ DOCS_URL_NLU_BASED_POLICIES,
78
+ )
79
+ from rasa.shared.core.trackers import EventVerbosity, DialogueStateTracker
80
+ from rasa.shared.core.training_data import visualization
81
+ from rasa.shared.core.training_data.visualization import (
82
+ VISUALIZATION_TEMPLATE_PATH,
83
+ visualize_neighborhood,
84
+ )
85
+ from rasa.core.utils import AvailableEndpoints
86
+ from rasa.shared.importers.rasa import TrainingDataImporter
87
+ from rasa.utils.common import update_sanic_log_level
88
+ from rasa.utils.endpoints import EndpointConfig
89
+ from rasa.shared.exceptions import InvalidConfigException
90
+
91
+ # noinspection PyProtectedMember
92
+ from rasa.shared.nlu.training_data import loading
93
+ from rasa.shared.nlu.training_data.message import Message
94
+
95
+ # WARNING: This command line UI is using an external library
96
+ # communicating with the shell - these functions are hard to test
97
+ # automatically. If you change anything in here, please make sure to
98
+ # run the interactive learning and check if your part of the "ui"
99
+ # still works.
100
+ import rasa.utils.io as io_utils
101
+
102
+ from rasa.shared.core.generator import TrackerWithCachedStates
103
+
104
+ logger = logging.getLogger(__name__)
105
+
106
+ PATHS = {
107
+ "stories": "data/stories.yml",
108
+ "nlu": "data/nlu.yml",
109
+ "backup": "data/nlu_interactive.yml",
110
+ "domain": "domain.yml",
111
+ }
112
+
113
+ SAVE_IN_E2E = False
114
+
115
+ # choose other intent, making sure this doesn't clash with an existing intent
116
+ OTHER_INTENT = uuid.uuid4().hex
117
+ OTHER_ACTION = uuid.uuid4().hex
118
+ NEW_ACTION = uuid.uuid4().hex
119
+
120
+ NEW_RESPONSES: Dict[Text, List[Dict[Text, Any]]] = {}
121
+
122
+ MAX_NUMBER_OF_TRAINING_STORIES_FOR_VISUALIZATION = 200
123
+
124
+ DEFAULT_STORY_GRAPH_FILE = "story_graph.dot"
125
+
126
+
127
+ class RestartConversation(Exception):
128
+ """Exception used to break out the flow and restart the conversation."""
129
+
130
+ pass
131
+
132
+
133
+ class ForkTracker(Exception):
134
+ """Exception used to break out the flow and fork at a previous step.
135
+
136
+ The tracker will be reset to the selected point in the past and the
137
+ conversation will continue from there.
138
+ """
139
+
140
+ pass
141
+
142
+
143
+ class UndoLastStep(Exception):
144
+ """Exception used to break out the flow and undo the last step.
145
+
146
+ The last step is either the most recent user message or the most
147
+ recent action run by the bot.
148
+ """
149
+
150
+ pass
151
+
152
+
153
+ class Abort(Exception):
154
+ """Exception used to abort the interactive learning and exit."""
155
+
156
+ pass
157
+
158
+
159
+ async def send_message(
160
+ endpoint: EndpointConfig,
161
+ conversation_id: Text,
162
+ message: Text,
163
+ parse_data: Optional[Dict[Text, Any]] = None,
164
+ ) -> Optional[Any]:
165
+ """Send a user message to a conversation."""
166
+ payload = {
167
+ "sender": UserUttered.type_name,
168
+ "text": message,
169
+ "parse_data": parse_data,
170
+ }
171
+
172
+ return await endpoint.request(
173
+ json=payload,
174
+ method="post",
175
+ subpath=f"/conversations/{conversation_id}/messages",
176
+ )
177
+
178
+
179
+ async def request_prediction(
180
+ endpoint: EndpointConfig, conversation_id: Text
181
+ ) -> Optional[Any]:
182
+ """Request the next action prediction from core."""
183
+ return await endpoint.request(
184
+ method="post", subpath=f"/conversations/{conversation_id}/predict"
185
+ )
186
+
187
+
188
+ async def retrieve_domain(endpoint: EndpointConfig) -> Optional[Any]:
189
+ """Retrieve the domain from core."""
190
+ return await endpoint.request(
191
+ method="get", subpath="/domain", headers={"Accept": "application/json"}
192
+ )
193
+
194
+
195
+ async def retrieve_status(endpoint: EndpointConfig) -> Optional[Any]:
196
+ """Retrieve the status from core."""
197
+ return await endpoint.request(method="get", subpath="/status")
198
+
199
+
200
+ async def retrieve_tracker(
201
+ endpoint: EndpointConfig,
202
+ conversation_id: Text,
203
+ verbosity: EventVerbosity = EventVerbosity.ALL,
204
+ ) -> Dict[Text, Any]:
205
+ """Retrieve a tracker from core."""
206
+ path = f"/conversations/{conversation_id}/tracker?include_events={verbosity.name}"
207
+ result = await endpoint.request(
208
+ method="get", subpath=path, headers={"Accept": "application/json"}
209
+ )
210
+
211
+ # If the request wasn't successful the previous call had already raised. Hence,
212
+ # we can be sure we have the tracker in the right format.
213
+ return cast(Dict[Text, Any], result)
214
+
215
+
216
+ async def send_action(
217
+ endpoint: EndpointConfig,
218
+ conversation_id: Text,
219
+ action_name: Text,
220
+ policy: Optional[Text] = None,
221
+ confidence: Optional[float] = None,
222
+ is_new_action: bool = False,
223
+ ) -> Optional[Any]:
224
+ """Log an action to a conversation."""
225
+ payload = ActionExecuted(action_name, policy, confidence).as_dict()
226
+
227
+ subpath = f"/conversations/{conversation_id}/execute"
228
+
229
+ try:
230
+ return await endpoint.request(json=payload, method="post", subpath=subpath)
231
+ except ClientError:
232
+ if is_new_action:
233
+ if action_name in NEW_RESPONSES:
234
+ warning_questions = questionary.confirm(
235
+ f"WARNING: You have created a new action: '{action_name}', "
236
+ f"with matching response: "
237
+ f"'{NEW_RESPONSES[action_name][0][KEY_RESPONSES_TEXT]}'. "
238
+ f"This action will not return its message in this session, "
239
+ f"but the new response will be saved to your domain file "
240
+ f"when you exit and save this session. "
241
+ f"You do not need to do anything further."
242
+ )
243
+ await _ask_questions(warning_questions, conversation_id, endpoint)
244
+ else:
245
+ warning_questions = questionary.confirm(
246
+ f"WARNING: You have created a new action: '{action_name}', "
247
+ f"which was not successfully executed. "
248
+ f"If this action does not return any events, "
249
+ f"you do not need to do anything. "
250
+ f"If this is a custom action which returns events, "
251
+ f"you are recommended to implement this action "
252
+ f"in your action server and try again."
253
+ )
254
+ await _ask_questions(warning_questions, conversation_id, endpoint)
255
+
256
+ payload = ActionExecuted(action_name).as_dict()
257
+ return await send_event(endpoint, conversation_id, payload)
258
+ else:
259
+ logger.error("failed to execute action!")
260
+ raise
261
+
262
+
263
+ async def send_event(
264
+ endpoint: EndpointConfig,
265
+ conversation_id: Text,
266
+ evt: Union[List[Dict[Text, Any]], Dict[Text, Any]],
267
+ ) -> Optional[Any]:
268
+ """Log an event to a conversation."""
269
+ subpath = f"/conversations/{conversation_id}/tracker/events"
270
+
271
+ return await endpoint.request(json=evt, method="post", subpath=subpath)
272
+
273
+
274
+ def format_bot_output(message: BotUttered) -> Text:
275
+ """Format a bot response to be displayed in the history table."""
276
+ # First, add text to output
277
+ output = message.text or ""
278
+
279
+ # Then, append all additional items
280
+ data = message.data or {}
281
+ if not data:
282
+ return output
283
+
284
+ if "image" in data and data["image"] is not None:
285
+ output += "\nImage: " + data["image"]
286
+
287
+ if "attachment" in data and data["attachment"] is not None:
288
+ output += "\nAttachment: " + data["attachment"]
289
+
290
+ if "buttons" in data and data["buttons"] is not None:
291
+ output += "\nButtons:"
292
+ choices = rasa.cli.utils.button_choices_from_message_data(
293
+ data, allow_free_text_input=True
294
+ )
295
+ for choice in choices:
296
+ output += "\n" + choice
297
+
298
+ if "elements" in data and data["elements"] is not None:
299
+ output += "\nElements:"
300
+ for idx, element in enumerate(data["elements"]):
301
+ element_str = rasa.cli.utils.element_to_string(element, idx)
302
+ output += "\n" + element_str
303
+
304
+ if "quick_replies" in data and data["quick_replies"] is not None:
305
+ output += "\nQuick replies:"
306
+ for idx, element in enumerate(data["quick_replies"]):
307
+ element_str = rasa.cli.utils.element_to_string(element, idx)
308
+ output += "\n" + element_str
309
+ return output
310
+
311
+
312
+ def latest_user_message(events: List[Dict[Text, Any]]) -> Optional[Dict[Text, Any]]:
313
+ """Return most recent user message."""
314
+ for i, e in enumerate(reversed(events)):
315
+ if e.get("event") == UserUttered.type_name:
316
+ return e
317
+ return None
318
+
319
+
320
+ async def _ask_questions(
321
+ questions: Union[Form, Question],
322
+ conversation_id: Text,
323
+ endpoint: EndpointConfig,
324
+ is_abort: Callable[[Dict[Text, Any]], bool] = lambda x: False,
325
+ ) -> Any:
326
+ """Ask the user a question, if Ctrl-C is pressed provide user with menu."""
327
+ should_retry = True
328
+ answers: Any = {}
329
+
330
+ while should_retry:
331
+ answers = await questions.ask_async()
332
+ if answers is None or is_abort(answers):
333
+ should_retry = await _ask_if_quit(conversation_id, endpoint)
334
+ else:
335
+ should_retry = False
336
+ return answers
337
+
338
+
339
+ def _selection_choices_from_intent_prediction(
340
+ predictions: List[Dict[Text, Any]],
341
+ ) -> List[Dict[Text, Any]]:
342
+ """Given a list of ML predictions create a UI choice list."""
343
+ sorted_intents = sorted(
344
+ predictions, key=lambda k: (-k["confidence"], k[INTENT_NAME_KEY])
345
+ )
346
+
347
+ choices = []
348
+ for p in sorted_intents:
349
+ name_with_confidence = (
350
+ f'{p.get("confidence"):03.2f} {p.get(INTENT_NAME_KEY):40}'
351
+ )
352
+ choice = {
353
+ INTENT_NAME_KEY: name_with_confidence,
354
+ "value": p.get(INTENT_NAME_KEY),
355
+ }
356
+ choices.append(choice)
357
+
358
+ return choices
359
+
360
+
361
+ async def _request_free_text_intent(
362
+ conversation_id: Text, endpoint: EndpointConfig
363
+ ) -> Text:
364
+ question = questionary.text(
365
+ message="Please type the intent name:",
366
+ validate=io_utils.not_empty_validator("Please enter an intent name"),
367
+ )
368
+ return await _ask_questions(question, conversation_id, endpoint)
369
+
370
+
371
+ async def _request_free_text_action(
372
+ conversation_id: Text, endpoint: EndpointConfig
373
+ ) -> Text:
374
+ question = questionary.text(
375
+ message="Please type the action name:",
376
+ validate=io_utils.not_empty_validator("Please enter an action name"),
377
+ )
378
+ return await _ask_questions(question, conversation_id, endpoint)
379
+
380
+
381
+ async def _request_free_text_utterance(
382
+ conversation_id: Text, endpoint: EndpointConfig, action: Text
383
+ ) -> Text:
384
+ question = questionary.text(
385
+ message=(f"Please type the message for your new bot response '{action}':"),
386
+ validate=io_utils.not_empty_validator("Please enter a response"),
387
+ )
388
+ return await _ask_questions(question, conversation_id, endpoint)
389
+
390
+
391
+ async def _request_selection_from_intents(
392
+ intents: List[Dict[Text, Text]], conversation_id: Text, endpoint: EndpointConfig
393
+ ) -> Text:
394
+ question = questionary.select("What intent is it?", choices=intents)
395
+ return await _ask_questions(question, conversation_id, endpoint)
396
+
397
+
398
+ async def _request_fork_point_from_list(
399
+ forks: List[Dict[Text, Text]], conversation_id: Text, endpoint: EndpointConfig
400
+ ) -> Text:
401
+ question = questionary.select(
402
+ "Before which user message do you want to fork?", choices=forks
403
+ )
404
+ return await _ask_questions(question, conversation_id, endpoint)
405
+
406
+
407
+ async def _request_fork_from_user(
408
+ conversation_id: Text, endpoint: EndpointConfig
409
+ ) -> Optional[List[Dict[Text, Any]]]:
410
+ """Take in a conversation and ask at which point to fork the conversation.
411
+
412
+ Returns the list of events that should be kept. Forking means, the
413
+ conversation will be reset and continued from this previous point.
414
+ """
415
+ tracker = await retrieve_tracker(
416
+ endpoint, conversation_id, EventVerbosity.AFTER_RESTART
417
+ )
418
+
419
+ choices = []
420
+ for i, e in enumerate(tracker.get("events", [])):
421
+ if e.get("event") == UserUttered.type_name:
422
+ choices.append({"name": e.get("text"), "value": i})
423
+
424
+ fork_idx = await _request_fork_point_from_list(
425
+ list(reversed(choices)), conversation_id, endpoint
426
+ )
427
+
428
+ if fork_idx is not None:
429
+ return tracker.get("events", [])[: int(fork_idx)]
430
+ else:
431
+ return None
432
+
433
+
434
+ async def _request_intent_from_user(
435
+ latest_message: Dict[Text, Any],
436
+ intents: List[Text],
437
+ conversation_id: Text,
438
+ endpoint: EndpointConfig,
439
+ ) -> Dict[Text, Any]:
440
+ """Take in latest message and ask which intent it should have been.
441
+
442
+ Returns the intent dict that has been selected by the user.
443
+ """
444
+ predictions = latest_message.get("parse_data", {}).get("intent_ranking", [])
445
+
446
+ predicted_intents = {p[INTENT_NAME_KEY] for p in predictions}
447
+
448
+ for i in intents:
449
+ if i not in predicted_intents:
450
+ predictions.append({INTENT_NAME_KEY: i, "confidence": 0.0})
451
+
452
+ # convert intents to ui list and add <other> as a free text alternative
453
+ choices = [
454
+ {INTENT_NAME_KEY: "<create_new_intent>", "value": OTHER_INTENT}
455
+ ] + _selection_choices_from_intent_prediction(predictions)
456
+
457
+ intent_name = await _request_selection_from_intents(
458
+ choices, conversation_id, endpoint
459
+ )
460
+
461
+ if intent_name == OTHER_INTENT:
462
+ intent_name = await _request_free_text_intent(conversation_id, endpoint)
463
+ selected_intent = {INTENT_NAME_KEY: intent_name, "confidence": 1.0}
464
+ else:
465
+ # returns the selected intent with the original probability value
466
+ selected_intent = next(
467
+ (x for x in predictions if x[INTENT_NAME_KEY] == intent_name),
468
+ {INTENT_NAME_KEY: None},
469
+ )
470
+
471
+ return selected_intent
472
+
473
+
474
+ async def _print_history(conversation_id: Text, endpoint: EndpointConfig) -> None:
475
+ """Print information about the conversation for the user."""
476
+ tracker_dump = await retrieve_tracker(
477
+ endpoint, conversation_id, EventVerbosity.AFTER_RESTART
478
+ )
479
+ events = tracker_dump.get("events", [])
480
+
481
+ table = _chat_history_table(events)
482
+ slot_strings = _slot_history(tracker_dump)
483
+
484
+ print("------")
485
+ print("Chat History\n")
486
+ loop = asyncio.get_running_loop()
487
+ loop.run_in_executor(None, print, table)
488
+
489
+ if slot_strings:
490
+ print("\n")
491
+ slots_info = f"Current slots: \n\t{', '.join(slot_strings)}\n"
492
+ loop.run_in_executor(None, print, slots_info)
493
+
494
+ loop.run_in_executor(None, print, "------")
495
+
496
+
497
+ def _chat_history_table(events: List[Dict[Text, Any]]) -> Text:
498
+ """Create a table containing bot and user messages.
499
+
500
+ Also includes additional information, like any events and
501
+ prediction probabilities.
502
+ """
503
+
504
+ def wrap(txt: Text, max_width: int) -> Text:
505
+ true_wrapping_width = calc_true_wrapping_width(txt, max_width)
506
+ return "\n".join(
507
+ textwrap.wrap(txt, true_wrapping_width, replace_whitespace=False)
508
+ )
509
+
510
+ def colored(txt: Text, color: Text) -> Text:
511
+ return "{" + color + "}" + txt + "{/" + color + "}"
512
+
513
+ def format_user_msg(user_event: UserUttered, max_width: int) -> Text:
514
+ intent = user_event.intent or {}
515
+ intent_name = intent.get(INTENT_NAME_KEY, "")
516
+ _confidence = intent.get("confidence", 1.0)
517
+ _md = _as_md_message(user_event.parse_data)
518
+
519
+ _lines = [
520
+ colored(wrap(_md, max_width), "hired"),
521
+ f"intent: {intent_name} {_confidence:03.2f}",
522
+ ]
523
+ return "\n".join(_lines)
524
+
525
+ def bot_width(_table: AsciiTable) -> int:
526
+ return _table.column_max_width(1)
527
+
528
+ def user_width(_table: AsciiTable) -> int:
529
+ return _table.column_max_width(3)
530
+
531
+ def add_bot_cell(data: List[List[Union[Text, Color]]], cell: Text) -> None:
532
+ data.append([len(data), Color(cell), "", ""])
533
+
534
+ def add_user_cell(data: List[List[Union[Text, Color]]], cell: Text) -> None:
535
+ data.append([len(data), "", "", Color(cell)])
536
+
537
+ # prints the historical interactions between the bot and the user,
538
+ # to help with correctly identifying the action
539
+ table_data = [
540
+ [
541
+ "# ",
542
+ Color(colored("Bot ", "autoblue")),
543
+ " ",
544
+ Color(colored("You ", "hired")),
545
+ ]
546
+ ]
547
+
548
+ table = SingleTable(table_data, "Chat History")
549
+
550
+ bot_column = []
551
+
552
+ tracker = DialogueStateTracker.from_dict("any", events)
553
+ applied_events = tracker.applied_events()
554
+
555
+ for idx, event in enumerate(applied_events):
556
+ if isinstance(event, ActionExecuted):
557
+ if (
558
+ event.action_name == ACTION_UNLIKELY_INTENT_NAME
559
+ and event.confidence == 0
560
+ ):
561
+ continue
562
+ bot_column.append(colored(str(event), "autocyan"))
563
+ if event.confidence is not None:
564
+ bot_column[-1] += colored(f" {event.confidence:03.2f}", "autowhite")
565
+
566
+ elif isinstance(event, UserUttered):
567
+ if bot_column:
568
+ text = "\n".join(bot_column)
569
+ add_bot_cell(table_data, text)
570
+ bot_column = []
571
+
572
+ msg = format_user_msg(event, user_width(table))
573
+ add_user_cell(table_data, msg)
574
+
575
+ elif isinstance(event, BotUttered):
576
+ wrapped = wrap(format_bot_output(event), bot_width(table))
577
+ bot_column.append(colored(wrapped, "autoblue"))
578
+
579
+ else:
580
+ if event.as_story_string():
581
+ bot_column.append(wrap(event.as_story_string(), bot_width(table)))
582
+
583
+ if bot_column:
584
+ text = "\n".join(bot_column)
585
+ add_bot_cell(table_data, text)
586
+
587
+ table.inner_heading_row_border = False
588
+ table.inner_row_border = True
589
+ table.inner_column_border = False
590
+ table.outer_border = False
591
+ table.justify_columns = {0: "left", 1: "left", 2: "center", 3: "right"}
592
+
593
+ return table.table
594
+
595
+
596
+ def _slot_history(tracker_dump: Dict[Text, Any]) -> List[Text]:
597
+ """Create an array of slot representations to be displayed."""
598
+ slot_strings = []
599
+ for k, s in tracker_dump.get("slots", {}).items():
600
+ colored_value = rasa.shared.utils.io.wrap_with_color(
601
+ str(s), color=rasa.shared.utils.io.bcolors.WARNING
602
+ )
603
+ slot_strings.append(f"{k}: {colored_value}")
604
+ return slot_strings
605
+
606
+
607
+ async def _retry_on_error(
608
+ func: Callable, export_path: Text, *args: Any, **kwargs: Any
609
+ ) -> None:
610
+ while True:
611
+ try:
612
+ return func(export_path, *args, **kwargs)
613
+ except OSError as e:
614
+ answer = await questionary.confirm(
615
+ f"Failed to export '{export_path}': {e}. Please make sure 'rasa' "
616
+ f"has read and write access to this file. Would you like to retry?"
617
+ ).ask_async()
618
+ if not answer:
619
+ raise e
620
+
621
+
622
+ async def _write_data_to_file(conversation_id: Text, endpoint: EndpointConfig) -> None:
623
+ """Write stories and nlu data to file."""
624
+ story_path, nlu_path, domain_path = await _request_export_info()
625
+
626
+ tracker = await retrieve_tracker(endpoint, conversation_id)
627
+ events = tracker.get("events", [])
628
+
629
+ serialised_domain = await retrieve_domain(endpoint)
630
+ domain = Domain.from_dict(serialised_domain)
631
+
632
+ await _retry_on_error(_write_stories_to_file, story_path, events, domain)
633
+ await _retry_on_error(_write_nlu_to_file, nlu_path, events)
634
+ await _retry_on_error(_write_domain_to_file, domain_path, events, domain)
635
+
636
+ logger.info("Successfully wrote stories and NLU data")
637
+
638
+
639
+ async def _ask_if_quit(conversation_id: Text, endpoint: EndpointConfig) -> bool:
640
+ """Display the exit menu.
641
+
642
+ Return `True` if the previous question should be retried.
643
+ """
644
+ answer = await questionary.select(
645
+ message="Do you want to stop?",
646
+ choices=[
647
+ Choice("Continue", "continue"),
648
+ Choice("Undo Last", "undo"),
649
+ Choice("Fork", "fork"),
650
+ Choice("Start Fresh", "restart"),
651
+ Choice("Export & Quit", "quit"),
652
+ ],
653
+ ).ask_async()
654
+
655
+ if not answer or answer == "quit":
656
+ # this is also the default answer if the user presses Ctrl-C
657
+ await _write_data_to_file(conversation_id, endpoint)
658
+ raise Abort()
659
+ elif answer == "undo":
660
+ raise UndoLastStep()
661
+ elif answer == "fork":
662
+ raise ForkTracker()
663
+ elif answer == "restart":
664
+ raise RestartConversation()
665
+ else: # `continue` or no answer
666
+ # in this case we will just return, and the original
667
+ # question will get asked again
668
+ return True
669
+
670
+
671
+ async def _request_action_from_user(
672
+ predictions: List[Dict[Text, Any]], conversation_id: Text, endpoint: EndpointConfig
673
+ ) -> Tuple[Text, bool]:
674
+ """Ask the user to correct an action prediction."""
675
+ await _print_history(conversation_id, endpoint)
676
+
677
+ choices = [
678
+ {"name": f'{a["score"]:03.2f} {a["action"]:40}', "value": a["action"]}
679
+ for a in predictions
680
+ ]
681
+
682
+ tracker = await retrieve_tracker(endpoint, conversation_id)
683
+ events = tracker.get("events", [])
684
+
685
+ session_actions_all = [a["name"] for a in _collect_actions(events)]
686
+ session_actions_unique = list(set(session_actions_all))
687
+ old_actions = [action["value"] for action in choices]
688
+ new_actions = [
689
+ {"name": action, "value": OTHER_ACTION + action}
690
+ for action in session_actions_unique
691
+ if action not in old_actions
692
+ ]
693
+ choices = (
694
+ [{"name": "<create new action>", "value": NEW_ACTION}] + new_actions + choices
695
+ )
696
+ question = questionary.select("What is the next action of the bot?", choices)
697
+
698
+ action_name = await _ask_questions(question, conversation_id, endpoint)
699
+ is_new_action = action_name == NEW_ACTION
700
+
701
+ if is_new_action:
702
+ # create new action
703
+ action_name = await _request_free_text_action(conversation_id, endpoint)
704
+ if action_name.startswith(UTTER_PREFIX):
705
+ utter_message = await _request_free_text_utterance(
706
+ conversation_id, endpoint, action_name
707
+ )
708
+ NEW_RESPONSES[action_name] = [{KEY_RESPONSES_TEXT: utter_message}]
709
+
710
+ elif action_name[:32] == OTHER_ACTION:
711
+ # action was newly created in the session, but not this turn
712
+ is_new_action = True
713
+ action_name = action_name[32:]
714
+
715
+ print(f"Thanks! The bot will now run {action_name}.\n")
716
+ return action_name, is_new_action
717
+
718
+
719
+ async def _request_export_info() -> Tuple[Text, Text, Text]:
720
+ import rasa.shared.data
721
+
722
+ """Request file path and export stories & nlu data to that path"""
723
+
724
+ # export training data and quit
725
+ questions = questionary.form(
726
+ export_stories=questionary.text(
727
+ message="Export stories to (if file exists, this "
728
+ "will append the stories)",
729
+ default=PATHS["stories"],
730
+ validate=io_utils.file_type_validator(
731
+ rasa.shared.data.YAML_FILE_EXTENSIONS,
732
+ "Please provide a valid export path for the stories, "
733
+ "e.g. 'stories.yml'.",
734
+ ),
735
+ ),
736
+ export_nlu=questionary.text(
737
+ message="Export NLU data to (if file exists, this will "
738
+ "merge learned data with previous training examples)",
739
+ default=PATHS["nlu"],
740
+ validate=io_utils.file_type_validator(
741
+ list(rasa.shared.data.TRAINING_DATA_EXTENSIONS),
742
+ "Please provide a valid export path for the NLU data, "
743
+ "e.g. 'nlu.yml'.",
744
+ ),
745
+ ),
746
+ export_domain=questionary.text(
747
+ message="Export domain file to (if file exists, this "
748
+ "will be overwritten)",
749
+ default=PATHS["domain"],
750
+ validate=io_utils.file_type_validator(
751
+ rasa.shared.data.YAML_FILE_EXTENSIONS,
752
+ "Please provide a valid export path for the domain file, "
753
+ "e.g. 'domain.yml'.",
754
+ ),
755
+ ),
756
+ )
757
+
758
+ answers = await questions.ask_async()
759
+ if not answers:
760
+ raise Abort()
761
+
762
+ return answers["export_stories"], answers["export_nlu"], answers["export_domain"]
763
+
764
+
765
+ def _split_conversation_at_restarts(
766
+ events: List[Dict[Text, Any]],
767
+ ) -> List[List[Dict[Text, Any]]]:
768
+ """Split a conversation at restart events.
769
+
770
+ Returns an array of event lists, without the restart events.
771
+ """
772
+ deserialized_events = [Event.from_parameters(event) for event in events]
773
+ split_events = rasa.shared.core.events.split_events(
774
+ deserialized_events, Restarted, include_splitting_event=False
775
+ )
776
+
777
+ return [[event.as_dict() for event in events] for events in split_events]
778
+
779
+
780
+ def _collect_messages(events: List[Dict[Text, Any]]) -> List[Message]:
781
+ """Collect the message text and parsed data from the UserMessage events
782
+ into a list.
783
+ """
784
+ import rasa.shared.nlu.training_data.util as rasa_nlu_training_data_utils
785
+
786
+ messages = []
787
+
788
+ for event in events:
789
+ if event.get("event") == UserUttered.type_name:
790
+ data = event.get("parse_data", {})
791
+ rasa_nlu_training_data_utils.remove_untrainable_entities_from(data)
792
+ msg = Message.build(
793
+ data["text"], data["intent"][INTENT_NAME_KEY], data["entities"]
794
+ )
795
+ messages.append(msg)
796
+ elif event.get("event") == UserUtteranceReverted.type_name and messages:
797
+ messages.pop() # user corrected the nlu, remove incorrect example
798
+
799
+ return messages
800
+
801
+
802
+ def _collect_actions(events: List[Dict[Text, Any]]) -> List[Dict[Text, Any]]:
803
+ """Collect all the `ActionExecuted` events into a list."""
804
+ return [evt for evt in events if evt.get("event") == ActionExecuted.type_name]
805
+
806
+
807
+ def _write_stories_to_file(
808
+ export_story_path: Text, events: List[Dict[Text, Any]], domain: Domain
809
+ ) -> None:
810
+ """Write the conversation of the conversation_id to the file paths."""
811
+ from rasa.shared.core.training_data.story_writer.yaml_story_writer import (
812
+ YAMLStoryWriter,
813
+ )
814
+
815
+ sub_conversations = _split_conversation_at_restarts(events)
816
+ io_utils.create_path(export_story_path)
817
+
818
+ if rasa.shared.data.is_likely_yaml_file(export_story_path):
819
+ writer = YAMLStoryWriter()
820
+
821
+ should_append_stories = False
822
+ if os.path.exists(export_story_path):
823
+ append_write = "a" # append if already exists
824
+ should_append_stories = True
825
+ else:
826
+ append_write = "w" # make a new file if not
827
+
828
+ with open(
829
+ export_story_path, append_write, encoding=rasa.shared.utils.io.DEFAULT_ENCODING
830
+ ) as f:
831
+ interactive_story_counter = 1
832
+ for conversation in sub_conversations:
833
+ parsed_events = rasa.shared.core.events.deserialise_events(conversation)
834
+ tracker = DialogueStateTracker.from_events(
835
+ f"interactive_story_{interactive_story_counter}",
836
+ evts=parsed_events,
837
+ slots=domain.slots,
838
+ )
839
+
840
+ if any(
841
+ isinstance(event, UserUttered) for event in tracker.applied_events()
842
+ ):
843
+ interactive_story_counter += 1
844
+ f.write(
845
+ "\n"
846
+ + tracker.export_stories(
847
+ writer=writer,
848
+ should_append_stories=should_append_stories,
849
+ e2e=SAVE_IN_E2E,
850
+ )
851
+ )
852
+
853
+
854
+ def _filter_messages(msgs: List[Message]) -> List[Message]:
855
+ """Filter messages removing those that start with INTENT_MESSAGE_PREFIX."""
856
+ filtered_messages = []
857
+ for msg in msgs:
858
+ if not msg.get(TEXT).startswith(INTENT_MESSAGE_PREFIX):
859
+ filtered_messages.append(msg)
860
+ return filtered_messages
861
+
862
+
863
+ def _write_nlu_to_file(export_nlu_path: Text, events: List[Dict[Text, Any]]) -> None:
864
+ """Write the nlu data of the conversation_id to the file paths."""
865
+ from rasa.shared.nlu.training_data.training_data import TrainingData
866
+
867
+ msgs = _collect_messages(events)
868
+ msgs = _filter_messages(msgs)
869
+
870
+ # noinspection PyBroadException
871
+ try:
872
+ previous_examples = loading.load_data(export_nlu_path)
873
+ except Exception as e:
874
+ logger.debug(f"An exception occurred while trying to load the NLU data. {e!s}")
875
+ # No previous file exists, use empty training data as replacement.
876
+ previous_examples = TrainingData()
877
+
878
+ nlu_data = previous_examples.merge(TrainingData(msgs))
879
+
880
+ # need to guess the format of the file before opening it to avoid a read
881
+ # in a write
882
+ nlu_format = _get_nlu_target_format(export_nlu_path)
883
+ if nlu_format == RASA_YAML:
884
+ stringified_training_data = nlu_data.nlu_as_yaml()
885
+ else:
886
+ stringified_training_data = nlu_data.nlu_as_json()
887
+
888
+ rasa.shared.utils.io.write_text_file(stringified_training_data, export_nlu_path)
889
+
890
+
891
+ def _get_nlu_target_format(export_path: Text) -> Text:
892
+ guessed_format = loading.guess_format(export_path)
893
+
894
+ if guessed_format not in {RASA, RASA_YAML}:
895
+ if rasa.shared.data.is_likely_json_file(export_path):
896
+ guessed_format = RASA
897
+ elif rasa.shared.data.is_likely_yaml_file(export_path):
898
+ guessed_format = RASA_YAML
899
+
900
+ return guessed_format
901
+
902
+
903
+ def _entities_from_messages(messages: List[Message]) -> List[Text]:
904
+ """Return all entities that occur in at least one of the messages."""
905
+ return list({e["entity"] for m in messages for e in m.data.get("entities", [])})
906
+
907
+
908
+ def _intents_from_messages(messages: List[Message]) -> Set[Text]:
909
+ """Return all intents that occur in at least one of the messages."""
910
+ # set of distinct intents
911
+ distinct_intents = {m.data["intent"] for m in messages if "intent" in m.data}
912
+
913
+ return distinct_intents
914
+
915
+
916
+ def _write_domain_to_file(
917
+ domain_path: Text, events: List[Dict[Text, Any]], old_domain: Domain
918
+ ) -> None:
919
+ """Write an updated domain file to the file path."""
920
+ io_utils.create_path(domain_path)
921
+
922
+ messages = _collect_messages(events)
923
+ actions = _collect_actions(events)
924
+ responses = NEW_RESPONSES
925
+
926
+ # TODO for now there is no way to distinguish between action and form
927
+ collected_actions = list(
928
+ {
929
+ e["name"]
930
+ for e in actions
931
+ if e["name"] not in rasa.shared.core.constants.DEFAULT_ACTION_NAMES
932
+ and e["name"] not in old_domain.form_names
933
+ }
934
+ )
935
+
936
+ new_domain = Domain.from_dict(
937
+ {
938
+ KEY_INTENTS: list(_intents_from_messages(messages)),
939
+ KEY_ENTITIES: _entities_from_messages(messages),
940
+ KEY_RESPONSES: responses,
941
+ KEY_ACTIONS: collected_actions,
942
+ }
943
+ )
944
+
945
+ old_domain.merge(new_domain).persist(domain_path)
946
+
947
+
948
+ async def _predict_till_next_listen(
949
+ endpoint: EndpointConfig,
950
+ conversation_id: Text,
951
+ conversation_ids: List[Text],
952
+ plot_file: Optional[Text],
953
+ ) -> None:
954
+ """Predict and validate actions until we need to wait for a user message."""
955
+ listen = False
956
+ while not listen:
957
+ result = await request_prediction(endpoint, conversation_id)
958
+ if result is None:
959
+ result = {}
960
+
961
+ predictions = result.get("scores", [])
962
+ if not predictions:
963
+ raise InvalidConfigException(
964
+ "Cannot continue as no action was predicted by the dialogue manager. "
965
+ "This can happen if you trained the assistant with no policy included "
966
+ "in the configuration. If so, please re-train the assistant with at "
967
+ f"least one policy ({DOCS_URL_NLU_BASED_POLICIES}) "
968
+ "included in the configuration."
969
+ )
970
+
971
+ probabilities = [prediction["score"] for prediction in predictions]
972
+ pred_out = int(np.argmax(probabilities))
973
+ action_name = predictions[pred_out].get("action")
974
+ policy = result.get("policy")
975
+ confidence = result.get("confidence")
976
+
977
+ await _print_history(conversation_id, endpoint)
978
+ await _plot_trackers(
979
+ conversation_ids,
980
+ plot_file,
981
+ endpoint,
982
+ unconfirmed=[ActionExecuted(action_name)],
983
+ )
984
+
985
+ listen = await _validate_action(
986
+ action_name, policy, confidence, predictions, endpoint, conversation_id
987
+ )
988
+
989
+ await _plot_trackers(conversation_ids, plot_file, endpoint)
990
+
991
+ tracker_dump = await retrieve_tracker(
992
+ endpoint, conversation_id, EventVerbosity.AFTER_RESTART
993
+ )
994
+ events = tracker_dump.get("events", [])
995
+
996
+ if len(events) >= 2:
997
+ last_event = events[-2] # last event before action_listen
998
+
999
+ # if bot message includes buttons the user will get a list choice to reply
1000
+ # the list choice is displayed in place of action listen
1001
+ if last_event.get("event") == BotUttered.type_name and last_event["data"].get(
1002
+ "buttons", None
1003
+ ):
1004
+ user_selection = await _get_button_choice(last_event)
1005
+ if user_selection != rasa.cli.utils.FREE_TEXT_INPUT_PROMPT:
1006
+ await send_message(endpoint, conversation_id, user_selection)
1007
+
1008
+
1009
+ async def _get_button_choice(last_event: Dict[Text, Any]) -> Text:
1010
+ data = last_event["data"]
1011
+ message = last_event.get("text", "")
1012
+
1013
+ choices = rasa.cli.utils.button_choices_from_message_data(
1014
+ data, allow_free_text_input=True
1015
+ )
1016
+ question = questionary.select(message, choices)
1017
+ return await rasa.cli.utils.payload_from_button_question(question)
1018
+
1019
+
1020
+ async def _correct_wrong_nlu(
1021
+ corrected_nlu: Dict[Text, Any],
1022
+ events: List[Dict[Text, Any]],
1023
+ endpoint: EndpointConfig,
1024
+ conversation_id: Text,
1025
+ ) -> None:
1026
+ """A wrong NLU prediction got corrected, update core's tracker."""
1027
+ revert_latest_user_utterance = UserUtteranceReverted().as_dict()
1028
+ # `UserUtteranceReverted` also removes the `ACTION_LISTEN` event before, hence we
1029
+ # have to replay it.
1030
+ listen_for_next_message = ActionExecuted(ACTION_LISTEN_NAME).as_dict()
1031
+ corrected_message = latest_user_message(events)
1032
+
1033
+ if corrected_message is None:
1034
+ raise Exception("Failed to correct NLU data. User message not found.")
1035
+
1036
+ corrected_message["parse_data"] = corrected_nlu
1037
+ await send_event(
1038
+ endpoint,
1039
+ conversation_id,
1040
+ [revert_latest_user_utterance, listen_for_next_message, corrected_message],
1041
+ )
1042
+
1043
+
1044
+ async def _correct_wrong_action(
1045
+ corrected_action: Text,
1046
+ endpoint: EndpointConfig,
1047
+ conversation_id: Text,
1048
+ is_new_action: bool = False,
1049
+ ) -> None:
1050
+ """A wrong action prediction got corrected, update core's tracker."""
1051
+ await send_action(
1052
+ endpoint, conversation_id, corrected_action, is_new_action=is_new_action
1053
+ )
1054
+
1055
+
1056
+ def _form_is_rejected(action_name: Text, tracker: Dict[Text, Any]) -> bool:
1057
+ """Check if the form got rejected with the most recent action name."""
1058
+ return (
1059
+ tracker.get(ACTIVE_LOOP, {}).get(LOOP_NAME)
1060
+ and action_name != tracker[ACTIVE_LOOP][LOOP_NAME]
1061
+ and action_name != ACTION_LISTEN_NAME
1062
+ )
1063
+
1064
+
1065
+ def _form_is_restored(action_name: Text, tracker: Dict[Text, Any]) -> bool:
1066
+ """Check whether the form is called again after it was rejected."""
1067
+ return (
1068
+ tracker.get(ACTIVE_LOOP, {}).get(LOOP_REJECTED)
1069
+ and tracker.get("latest_action_name") == ACTION_LISTEN_NAME
1070
+ and action_name == tracker.get(ACTIVE_LOOP, {}).get(LOOP_NAME)
1071
+ )
1072
+
1073
+
1074
+ async def _confirm_form_validation(
1075
+ action_name: Text,
1076
+ tracker: Dict[Text, Any],
1077
+ endpoint: EndpointConfig,
1078
+ conversation_id: Text,
1079
+ ) -> None:
1080
+ """Ask a user whether an input for a form should be validated.
1081
+
1082
+ Previous to this call, the active form was chosen after it was rejected.
1083
+ """
1084
+ requested_slot = tracker.get("slots", {}).get(REQUESTED_SLOT)
1085
+
1086
+ validation_questions = questionary.confirm(
1087
+ f"Should '{action_name}' validate user input to fill "
1088
+ f"the slot '{requested_slot}'?"
1089
+ )
1090
+ validate_input = await _ask_questions(
1091
+ validation_questions, conversation_id, endpoint
1092
+ )
1093
+
1094
+ if not validate_input:
1095
+ # notify form action to skip validation
1096
+ await send_event(
1097
+ endpoint,
1098
+ conversation_id,
1099
+ {
1100
+ "event": rasa.shared.core.events.LoopInterrupted.type_name,
1101
+ LOOP_INTERRUPTED: True,
1102
+ },
1103
+ )
1104
+
1105
+ elif tracker.get(ACTIVE_LOOP, {}).get(LOOP_INTERRUPTED):
1106
+ # handle contradiction with learned behaviour
1107
+ warning_question = questionary.confirm(
1108
+ "ERROR: FormPolicy predicted no form validation "
1109
+ "based on previous training stories. "
1110
+ "Make sure to remove contradictory stories "
1111
+ "from training data. "
1112
+ "Otherwise predicting no form validation "
1113
+ "will not work as expected."
1114
+ )
1115
+
1116
+ await _ask_questions(warning_question, conversation_id, endpoint)
1117
+ # notify form action to validate an input
1118
+ await send_event(
1119
+ endpoint,
1120
+ conversation_id,
1121
+ {
1122
+ "event": rasa.shared.core.events.LoopInterrupted.type_name,
1123
+ LOOP_INTERRUPTED: False,
1124
+ },
1125
+ )
1126
+
1127
+
1128
+ async def _validate_action(
1129
+ action_name: Text,
1130
+ policy: Text,
1131
+ confidence: float,
1132
+ predictions: List[Dict[Text, Any]],
1133
+ endpoint: EndpointConfig,
1134
+ conversation_id: Text,
1135
+ ) -> bool:
1136
+ """Query the user to validate if an action prediction is correct.
1137
+
1138
+ Returns `True` if the prediction is correct, `False` otherwise.
1139
+ """
1140
+ if action_name == ACTION_UNLIKELY_INTENT_NAME:
1141
+ question = questionary.confirm(
1142
+ f"The bot wants to run '{action_name}' "
1143
+ f"to indicate that the last user message was unexpected "
1144
+ f"at this point in the conversation. "
1145
+ f"Check out UnexpecTEDIntentPolicy "
1146
+ f"({DOCS_URL_NLU_BASED_POLICIES}#unexpected-intent-policy) "
1147
+ f"to learn more. Is that correct?"
1148
+ )
1149
+ else:
1150
+ question = questionary.confirm(
1151
+ f"The bot wants to run '{action_name}', correct?"
1152
+ )
1153
+
1154
+ is_correct = await _ask_questions(question, conversation_id, endpoint)
1155
+
1156
+ if not is_correct and action_name != ACTION_UNLIKELY_INTENT_NAME:
1157
+ action_name, is_new_action = await _request_action_from_user(
1158
+ predictions, conversation_id, endpoint
1159
+ )
1160
+ else:
1161
+ is_new_action = False
1162
+
1163
+ tracker = await retrieve_tracker(
1164
+ endpoint, conversation_id, EventVerbosity.AFTER_RESTART
1165
+ )
1166
+
1167
+ if _form_is_rejected(action_name, tracker):
1168
+ # notify the tracker that form was rejected
1169
+ await send_event(
1170
+ endpoint,
1171
+ conversation_id,
1172
+ {
1173
+ "event": "action_execution_rejected",
1174
+ LOOP_NAME: tracker[ACTIVE_LOOP][LOOP_NAME],
1175
+ },
1176
+ )
1177
+
1178
+ elif _form_is_restored(action_name, tracker):
1179
+ await _confirm_form_validation(action_name, tracker, endpoint, conversation_id)
1180
+
1181
+ if not is_correct:
1182
+ await _correct_wrong_action(
1183
+ action_name, endpoint, conversation_id, is_new_action=is_new_action
1184
+ )
1185
+ else:
1186
+ await send_action(endpoint, conversation_id, action_name, policy, confidence)
1187
+
1188
+ return action_name == ACTION_LISTEN_NAME
1189
+
1190
+
1191
+ def _as_md_message(parse_data: Dict[Text, Any]) -> Text:
1192
+ """Display the parse data of a message in markdown format."""
1193
+ from rasa.shared.nlu.training_data.formats.readerwriter import TrainingDataWriter
1194
+
1195
+ if parse_data.get("text", "").startswith(INTENT_MESSAGE_PREFIX):
1196
+ return parse_data["text"]
1197
+
1198
+ if not parse_data.get("entities"):
1199
+ parse_data["entities"] = []
1200
+
1201
+ return TrainingDataWriter.generate_message(parse_data)
1202
+
1203
+
1204
+ def _validate_user_regex(latest_message: Dict[Text, Any], intents: List[Text]) -> bool:
1205
+ """Validate if a users message input is correct.
1206
+
1207
+ This assumes the user entered an intent directly, e.g. using
1208
+ `/greet`. Return `True` if the intent is a known one.
1209
+ """
1210
+ parse_data = latest_message.get("parse_data", {})
1211
+ intent = parse_data.get("intent", {}).get(INTENT_NAME_KEY)
1212
+
1213
+ if intent in intents:
1214
+ return True
1215
+ else:
1216
+ return False
1217
+
1218
+
1219
+ async def _validate_user_text(
1220
+ latest_message: Dict[Text, Any], endpoint: EndpointConfig, conversation_id: Text
1221
+ ) -> bool:
1222
+ """Validate a user message input as free text.
1223
+
1224
+ This assumes the user message is a text message (so NOT `/greet`).
1225
+ """
1226
+ parse_data = latest_message.get("parse_data", {})
1227
+ text = _as_md_message(parse_data)
1228
+ intent = parse_data.get("intent", {}).get(INTENT_NAME_KEY)
1229
+ entities = parse_data.get("entities", [])
1230
+ if entities:
1231
+ message = (
1232
+ f"Is the intent '{intent}' correct for '{text}' and are "
1233
+ f"all entities labeled correctly?"
1234
+ )
1235
+ else:
1236
+ message = (
1237
+ f"Your NLU model classified '{text}' with intent '{intent}'"
1238
+ f" and there are no entities, is this correct?"
1239
+ )
1240
+
1241
+ if intent is None:
1242
+ print(f"The NLU classification for '{text}' returned '{intent}'")
1243
+ return False
1244
+ else:
1245
+ question = questionary.confirm(message)
1246
+
1247
+ return await _ask_questions(question, conversation_id, endpoint)
1248
+
1249
+
1250
+ async def _validate_nlu(
1251
+ intents: List[Text], endpoint: EndpointConfig, conversation_id: Text
1252
+ ) -> None:
1253
+ """Validate if a user message, either text or intent is correct.
1254
+
1255
+ If the prediction of the latest user message is incorrect,
1256
+ the tracker will be corrected with the correct intent / entities.
1257
+ """
1258
+ tracker = await retrieve_tracker(
1259
+ endpoint, conversation_id, EventVerbosity.AFTER_RESTART
1260
+ )
1261
+
1262
+ latest_message = latest_user_message(tracker.get("events", [])) or {}
1263
+
1264
+ if latest_message.get("text", "").startswith(INTENT_MESSAGE_PREFIX):
1265
+ valid = _validate_user_regex(latest_message, intents)
1266
+ else:
1267
+ valid = await _validate_user_text(latest_message, endpoint, conversation_id)
1268
+
1269
+ if not valid:
1270
+ corrected_intent = await _request_intent_from_user(
1271
+ latest_message, intents, conversation_id, endpoint
1272
+ )
1273
+ # corrected intents have confidence 1.0
1274
+ corrected_intent["confidence"] = 1.0
1275
+
1276
+ events = tracker.get("events", [])
1277
+
1278
+ entities = await _correct_entities(latest_message, endpoint, conversation_id)
1279
+ corrected_nlu = {
1280
+ "intent": corrected_intent,
1281
+ "entities": entities,
1282
+ "text": latest_message.get("text"),
1283
+ }
1284
+
1285
+ await _correct_wrong_nlu(corrected_nlu, events, endpoint, conversation_id)
1286
+
1287
+
1288
+ async def _correct_entities(
1289
+ latest_message: Dict[Text, Any], endpoint: EndpointConfig, conversation_id: Text
1290
+ ) -> List[Dict[Text, Any]]:
1291
+ """Validate the entities of a user message.
1292
+
1293
+ Returns the corrected entities.
1294
+ """
1295
+ from rasa.shared.nlu.training_data import entities_parser
1296
+
1297
+ parse_original = latest_message.get("parse_data", {})
1298
+ entity_str = _as_md_message(parse_original)
1299
+ question = questionary.text(
1300
+ "Please mark the entities using [value](type) notation", default=entity_str
1301
+ )
1302
+
1303
+ annotation = await _ask_questions(question, conversation_id, endpoint)
1304
+ parse_annotated = entities_parser.parse_training_example(annotation)
1305
+
1306
+ corrected_entities = _merge_annotated_and_original_entities(
1307
+ parse_annotated, parse_original
1308
+ )
1309
+
1310
+ return corrected_entities
1311
+
1312
+
1313
+ def _merge_annotated_and_original_entities(
1314
+ parse_annotated: Message, parse_original: Dict[Text, Any]
1315
+ ) -> List[Dict[Text, Any]]:
1316
+ # overwrite entities which have already been
1317
+ # annotated in the original annotation to preserve
1318
+ # additional entity parser information
1319
+ entities = parse_annotated.get("entities", [])[:]
1320
+ for i, entity in enumerate(entities):
1321
+ for original_entity in parse_original.get("entities", []):
1322
+ if _is_same_entity_annotation(entity, original_entity):
1323
+ entities[i] = original_entity
1324
+ break
1325
+ return entities
1326
+
1327
+
1328
+ def _is_same_entity_annotation(entity: Dict[Text, Any], other: Dict[Text, Any]) -> bool:
1329
+ return (
1330
+ entity["value"] == other["value"]
1331
+ and entity["entity"] == other["entity"]
1332
+ and entity.get("group") == other.get("group")
1333
+ and entity.get("role") == other.get("group")
1334
+ )
1335
+
1336
+
1337
+ async def _enter_user_message(conversation_id: Text, endpoint: EndpointConfig) -> None:
1338
+ """Request a new message from the user."""
1339
+ question = questionary.text("Your input ->")
1340
+
1341
+ message = await _ask_questions(question, conversation_id, endpoint, lambda a: not a)
1342
+
1343
+ if message == (INTENT_MESSAGE_PREFIX + USER_INTENT_RESTART):
1344
+ raise RestartConversation()
1345
+
1346
+ await send_message(endpoint, conversation_id, message)
1347
+
1348
+
1349
+ async def is_listening_for_message(
1350
+ conversation_id: Text, endpoint: EndpointConfig
1351
+ ) -> bool:
1352
+ """Check if the conversation is in need for a user message."""
1353
+ tracker = await retrieve_tracker(endpoint, conversation_id, EventVerbosity.APPLIED)
1354
+
1355
+ for i, e in enumerate(reversed(tracker.get("events", []))):
1356
+ if e.get("event") == UserUttered.type_name:
1357
+ return False
1358
+ elif e.get("event") == ActionExecuted.type_name:
1359
+ return e.get("name") == ACTION_LISTEN_NAME
1360
+ return False
1361
+
1362
+
1363
+ async def _undo_latest(conversation_id: Text, endpoint: EndpointConfig) -> None:
1364
+ """Undo either the latest bot action or user message, whatever is last."""
1365
+ tracker = await retrieve_tracker(endpoint, conversation_id, EventVerbosity.ALL)
1366
+
1367
+ # Get latest `UserUtterance` or `ActionExecuted` event.
1368
+ last_event_type = None
1369
+ for i, e in enumerate(reversed(tracker.get("events", []))):
1370
+ last_event_type = e.get("event")
1371
+ if last_event_type in {ActionExecuted.type_name, UserUttered.type_name}:
1372
+ break
1373
+ elif last_event_type == Restarted.type_name:
1374
+ break
1375
+
1376
+ if last_event_type == ActionExecuted.type_name:
1377
+ undo_action = ActionReverted().as_dict()
1378
+ await send_event(endpoint, conversation_id, undo_action)
1379
+ elif last_event_type == UserUttered.type_name:
1380
+ undo_user_message = UserUtteranceReverted().as_dict()
1381
+ listen_for_next_message = ActionExecuted(ACTION_LISTEN_NAME).as_dict()
1382
+
1383
+ await send_event(
1384
+ endpoint, conversation_id, [undo_user_message, listen_for_next_message]
1385
+ )
1386
+
1387
+
1388
+ async def _fetch_events(
1389
+ conversation_ids: List[Union[Text, List[Event]]], endpoint: EndpointConfig
1390
+ ) -> List[List[Event]]:
1391
+ """Retrieve all event trackers from the endpoint for all conversation ids."""
1392
+ event_sequences = []
1393
+ for conversation_id in conversation_ids:
1394
+ if isinstance(conversation_id, str):
1395
+ tracker = await retrieve_tracker(endpoint, conversation_id)
1396
+ events = tracker.get("events", [])
1397
+
1398
+ for conversation in _split_conversation_at_restarts(events):
1399
+ parsed_events = rasa.shared.core.events.deserialise_events(conversation)
1400
+ event_sequences.append(parsed_events)
1401
+ else:
1402
+ event_sequences.append(conversation_id)
1403
+ return event_sequences
1404
+
1405
+
1406
+ async def _plot_trackers(
1407
+ conversation_ids: List[Union[Text, List[Event]]],
1408
+ output_file: Optional[Text],
1409
+ endpoint: EndpointConfig,
1410
+ unconfirmed: Optional[List[Event]] = None,
1411
+ ) -> None:
1412
+ """Create a plot of the trackers of the passed conversation ids.
1413
+
1414
+ This assumes that the last conversation id is the conversation we are currently
1415
+ working on. If there are events that are not part of this active tracker
1416
+ yet, they can be passed as part of `unconfirmed`. They will be appended
1417
+ to the currently active conversation.
1418
+ """
1419
+ if not output_file or not conversation_ids:
1420
+ # if there is no output file provided, we are going to skip plotting
1421
+ # same happens if there are no conversation ids
1422
+ return
1423
+
1424
+ event_sequences = await _fetch_events(conversation_ids, endpoint)
1425
+
1426
+ if unconfirmed:
1427
+ event_sequences[-1].extend(unconfirmed)
1428
+
1429
+ graph = visualize_neighborhood(
1430
+ event_sequences[-1], event_sequences, output_file=None, max_history=2
1431
+ )
1432
+
1433
+ from networkx.drawing.nx_pydot import write_dot
1434
+
1435
+ with open(output_file, "w", encoding="utf-8") as f:
1436
+ write_dot(graph, f)
1437
+
1438
+
1439
+ def _print_help(skip_visualization: bool) -> None:
1440
+ """Print some initial help message for the user."""
1441
+ if not skip_visualization:
1442
+ visualization_url = DEFAULT_SERVER_FORMAT.format(
1443
+ "http", DEFAULT_SERVER_PORT + 1
1444
+ )
1445
+ visualization_help = (
1446
+ f"Visualisation at {visualization_url}/visualization.html ."
1447
+ )
1448
+ else:
1449
+ visualization_help = ""
1450
+
1451
+ rasa.shared.utils.cli.print_success(
1452
+ f"Bot loaded. {visualization_help}\n"
1453
+ f"Type a message and press enter "
1454
+ f"(press 'Ctrl-c' to exit)."
1455
+ )
1456
+
1457
+
1458
+ def intent_names_from_domain(domain: Any) -> List[Text]:
1459
+ """Get a list of the possible intents names from the domain specification.
1460
+
1461
+ This is its own function as intents are non-trivial to unpack and this
1462
+ warrants testing.
1463
+ """
1464
+ domain_intents = domain.get("intents", []) if domain is not None else []
1465
+
1466
+ # intents with properties such as `use_entities` or `ignore_entities`
1467
+ # are a dictionary which needs unpacking. Other intents are strings
1468
+ # and can be used as-is.
1469
+ return [next(iter(i)) if isinstance(i, dict) else i for i in domain_intents]
1470
+
1471
+
1472
+ async def record_messages(
1473
+ endpoint: EndpointConfig,
1474
+ file_importer: TrainingDataImporter,
1475
+ conversation_id: Text = DEFAULT_SENDER_ID,
1476
+ max_message_limit: Optional[int] = None,
1477
+ skip_visualization: bool = False,
1478
+ ) -> None:
1479
+ """Read messages from the command line and print bot responses."""
1480
+ try:
1481
+ try:
1482
+ domain = await retrieve_domain(endpoint)
1483
+ except ClientError:
1484
+ logger.exception(
1485
+ f"Failed to connect to Rasa Core server at '{endpoint.url}'. "
1486
+ f"Is the server running?"
1487
+ )
1488
+ return
1489
+
1490
+ intents = intent_names_from_domain(domain)
1491
+
1492
+ num_messages = 0
1493
+
1494
+ if not skip_visualization:
1495
+ events_including_current_user_id = _get_tracker_events_to_plot(
1496
+ domain, file_importer, conversation_id
1497
+ )
1498
+
1499
+ plot_file = DEFAULT_STORY_GRAPH_FILE
1500
+ await _plot_trackers(events_including_current_user_id, plot_file, endpoint)
1501
+ else:
1502
+ # `None` means that future `_plot_trackers` calls will also skip the
1503
+ # visualization.
1504
+ plot_file = None
1505
+ events_including_current_user_id = []
1506
+
1507
+ _print_help(skip_visualization)
1508
+
1509
+ while not utils.is_limit_reached(num_messages, max_message_limit):
1510
+ try:
1511
+ if await is_listening_for_message(conversation_id, endpoint):
1512
+ await _enter_user_message(conversation_id, endpoint)
1513
+ await _validate_nlu(intents, endpoint, conversation_id)
1514
+
1515
+ await _predict_till_next_listen(
1516
+ endpoint,
1517
+ conversation_id,
1518
+ events_including_current_user_id,
1519
+ plot_file,
1520
+ )
1521
+
1522
+ num_messages += 1
1523
+ except RestartConversation:
1524
+ await send_event(endpoint, conversation_id, Restarted().as_dict())
1525
+
1526
+ await send_event(
1527
+ endpoint,
1528
+ conversation_id,
1529
+ ActionExecuted(ACTION_LISTEN_NAME).as_dict(),
1530
+ )
1531
+
1532
+ logger.info("Restarted conversation, starting a new one.")
1533
+ except UndoLastStep:
1534
+ await _undo_latest(conversation_id, endpoint)
1535
+ await _print_history(conversation_id, endpoint)
1536
+ except ForkTracker:
1537
+ await _print_history(conversation_id, endpoint)
1538
+
1539
+ events_fork = await _request_fork_from_user(conversation_id, endpoint)
1540
+
1541
+ await send_event(endpoint, conversation_id, Restarted().as_dict())
1542
+
1543
+ if events_fork:
1544
+ for evt in events_fork:
1545
+ await send_event(endpoint, conversation_id, evt)
1546
+ logger.info("Restarted conversation at fork.")
1547
+
1548
+ await _print_history(conversation_id, endpoint)
1549
+ await _plot_trackers(
1550
+ events_including_current_user_id, plot_file, endpoint
1551
+ )
1552
+
1553
+ except Abort:
1554
+ return
1555
+ except Exception:
1556
+ logger.exception("An exception occurred while recording messages.")
1557
+ raise
1558
+
1559
+
1560
+ def _get_tracker_events_to_plot(
1561
+ domain: Dict[Text, Any], file_importer: TrainingDataImporter, conversation_id: Text
1562
+ ) -> List[Union[Text, Deque[Event]]]:
1563
+ training_trackers = _get_training_trackers(file_importer, domain)
1564
+ number_of_trackers = len(training_trackers)
1565
+ if number_of_trackers > MAX_NUMBER_OF_TRAINING_STORIES_FOR_VISUALIZATION:
1566
+ rasa.shared.utils.cli.print_warning(
1567
+ f"You have {number_of_trackers} different story paths in "
1568
+ f"your training data. Visualizing them is very resource "
1569
+ f"consuming. Hence, the visualization will only show the stories "
1570
+ f"which you created during interactive learning, but not your "
1571
+ f"training stories."
1572
+ )
1573
+ training_trackers = []
1574
+
1575
+ training_data_events: List[Union[Text, Deque[Event]]] = [
1576
+ t.events for t in training_trackers
1577
+ ]
1578
+ return training_data_events + [conversation_id]
1579
+
1580
+
1581
+ def _get_training_trackers(
1582
+ file_importer: TrainingDataImporter, domain: Dict[str, Any]
1583
+ ) -> List[TrackerWithCachedStates]:
1584
+ from rasa.core import training
1585
+
1586
+ return training.load_data(
1587
+ file_importer,
1588
+ Domain.from_dict(domain),
1589
+ augmentation_factor=0,
1590
+ use_story_concatenation=False,
1591
+ )
1592
+
1593
+
1594
+ def _serve_application(
1595
+ app: Sanic,
1596
+ file_importer: TrainingDataImporter,
1597
+ skip_visualization: bool,
1598
+ conversation_id: Text,
1599
+ port: int,
1600
+ ) -> Sanic:
1601
+ """Start a core server and attach the interactive learning IO."""
1602
+ endpoint = EndpointConfig(url=DEFAULT_SERVER_FORMAT.format("http", port))
1603
+
1604
+ @app.after_server_start
1605
+ async def run_interactive_io(running_app: Sanic) -> None:
1606
+ """Small wrapper to shut down the server once cmd io is done."""
1607
+ await record_messages(
1608
+ endpoint=endpoint,
1609
+ file_importer=file_importer,
1610
+ skip_visualization=skip_visualization,
1611
+ conversation_id=conversation_id,
1612
+ )
1613
+
1614
+ logger.info("Killing Sanic server now.")
1615
+
1616
+ running_app.stop() # kill the sanic server
1617
+
1618
+ update_sanic_log_level()
1619
+
1620
+ app.run(host="0.0.0.0", port=port, legacy=True)
1621
+
1622
+ return app
1623
+
1624
+
1625
+ def start_visualization(image_path: Text, port: int) -> None:
1626
+ """Add routes to serve the conversation visualization files."""
1627
+ app = Sanic("rasa_interactive")
1628
+
1629
+ # Reset Sanic warnings filter that allows the triggering of Sanic warnings
1630
+ warnings.filterwarnings("ignore", category=DeprecationWarning, module=r"sanic.*")
1631
+
1632
+ # noinspection PyUnusedLocal
1633
+ @app.exception(NotFound)
1634
+ async def ignore_404s(request: Request, exception: Exception) -> HTTPResponse:
1635
+ return response.text("Not found", status=404)
1636
+
1637
+ # noinspection PyUnusedLocal
1638
+ @app.route(VISUALIZATION_TEMPLATE_PATH, methods=["GET"])
1639
+ async def visualisation_html(request: Request) -> HTTPResponse:
1640
+ return await response.file(visualization.visualization_html_path())
1641
+
1642
+ # noinspection PyUnusedLocal
1643
+ @app.route("/visualization.dot", methods=["GET"])
1644
+ async def visualisation_png(request: Request) -> HTTPResponse:
1645
+ try:
1646
+ headers = {"Cache-Control": "no-cache"}
1647
+ return await response.file(os.path.abspath(image_path), headers=headers)
1648
+ except FileNotFoundError:
1649
+ return response.text("", 404)
1650
+
1651
+ update_sanic_log_level()
1652
+
1653
+ app.run(host="0.0.0.0", port=port, access_log=False, legacy=True)
1654
+
1655
+
1656
+ def run_interactive_learning(
1657
+ file_importer: TrainingDataImporter,
1658
+ skip_visualization: bool = False,
1659
+ conversation_id: Text = uuid.uuid4().hex,
1660
+ server_args: Optional[Dict[Text, Any]] = None,
1661
+ ) -> None:
1662
+ """Start the interactive learning with the model of the agent."""
1663
+ global SAVE_IN_E2E
1664
+ server_args = server_args or {}
1665
+
1666
+ if server_args.get("nlu_data"):
1667
+ PATHS["nlu"] = server_args["nlu_data"]
1668
+
1669
+ if server_args.get("stories"):
1670
+ PATHS["stories"] = server_args["stories"]
1671
+
1672
+ if server_args.get("domain"):
1673
+ PATHS["domain"] = server_args["domain"]
1674
+
1675
+ port = server_args.get("port", DEFAULT_SERVER_PORT)
1676
+
1677
+ SAVE_IN_E2E = server_args["e2e"]
1678
+
1679
+ if not skip_visualization:
1680
+ visualisation_port = port + 1
1681
+ p = Process(
1682
+ target=start_visualization,
1683
+ args=(DEFAULT_STORY_GRAPH_FILE, visualisation_port),
1684
+ daemon=True,
1685
+ )
1686
+ p.start()
1687
+ else:
1688
+ p = None
1689
+
1690
+ app = run.configure_app(port=port, conversation_id="default", enable_api=True)
1691
+ endpoints = AvailableEndpoints.read_endpoints(server_args.get("endpoints"))
1692
+
1693
+ # before_server_start handlers make sure the agent is loaded before the
1694
+ # interactive learning IO starts
1695
+ app.register_listener(
1696
+ partial(run.load_agent_on_start, server_args.get("model"), endpoints, None),
1697
+ "before_server_start",
1698
+ )
1699
+
1700
+ telemetry.track_interactive_learning_start(skip_visualization, SAVE_IN_E2E)
1701
+
1702
+ _serve_application(app, file_importer, skip_visualization, conversation_id, port)
1703
+
1704
+ if not skip_visualization and p is not None:
1705
+ p.terminate()
1706
+ p.join()
1707
+
1708
+
1709
+ def calc_true_wrapping_width(text: Text, monospace_wrapping_width: int) -> int:
1710
+ """Calculates a wrapping width that also works for CJK characters.
1711
+
1712
+ Chinese, Japanese and Korean characters are often broader than ascii
1713
+ characters:
1714
+ abcdefgh (8 chars)
1715
+ 我要去北京 (5 chars, roughly same visible width)
1716
+
1717
+ We need to account for that otherwise the wrapping doesn't work
1718
+ appropriately for long strings and the table overflows and creates
1719
+ errors.
1720
+
1721
+ params:
1722
+ text: text sequence that should be wrapped into multiple lines
1723
+ monospace_wrapping_width: the maximum width per line in number of
1724
+ standard ascii characters
1725
+ returns:
1726
+ The maximum line width for the given string that takes into account
1727
+ the strings visible width, so that it won't lead to table overflow.
1728
+ """
1729
+ true_wrapping_width = 0
1730
+
1731
+ # testing potential width from longest to shortest
1732
+ for potential_width in range(monospace_wrapping_width, -1, -1):
1733
+ lines = textwrap.wrap(text, potential_width)
1734
+ # test whether all lines' visible width fits the available width
1735
+ if all(
1736
+ [
1737
+ terminaltables.width_and_alignment.visible_width(line)
1738
+ <= monospace_wrapping_width
1739
+ for line in lines
1740
+ ]
1741
+ ):
1742
+ true_wrapping_width = potential_width
1743
+ break
1744
+
1745
+ return true_wrapping_width