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
rasa/telemetry.py ADDED
@@ -0,0 +1,1737 @@
1
+ import asyncio
2
+ import contextlib
3
+ import hashlib
4
+ import inspect
5
+ import json
6
+ import logging
7
+ import multiprocessing
8
+ import os
9
+ import platform
10
+ import sys
11
+ import textwrap
12
+ import typing
13
+ import uuid
14
+ from collections import defaultdict
15
+ from datetime import datetime
16
+ from functools import wraps
17
+ from pathlib import Path
18
+ from typing import Any, Callable, Dict, List, Optional, Text
19
+
20
+ import importlib_resources
21
+ import requests
22
+ from terminaltables import SingleTable
23
+
24
+ import rasa
25
+ import rasa.anonymization.utils
26
+ import rasa.shared.utils.io
27
+ import rasa.utils.io
28
+ from rasa import model
29
+ from rasa.constants import (
30
+ CONFIG_FILE_TELEMETRY_KEY,
31
+ CONFIG_TELEMETRY_DATE,
32
+ CONFIG_TELEMETRY_ENABLED,
33
+ CONFIG_TELEMETRY_ID,
34
+ )
35
+ from rasa.shared.constants import PROMPT_CONFIG_KEY, PROMPT_TEMPLATE_CONFIG_KEY
36
+ from rasa.engine.storage.local_model_storage import LocalModelStorage
37
+ from rasa.shared.constants import DOCS_URL_TELEMETRY, UTTER_ASK_PREFIX
38
+ from rasa.shared.core.flows import Flow
39
+ from rasa.shared.core.flows.steps import (
40
+ CollectInformationFlowStep,
41
+ SetSlotsFlowStep,
42
+ LinkFlowStep,
43
+ CallFlowStep,
44
+ )
45
+ from rasa.shared.exceptions import RasaException
46
+ from rasa.utils import common as rasa_utils
47
+
48
+ if typing.TYPE_CHECKING:
49
+ from rasa.core.brokers.broker import EventBroker
50
+ from rasa.core.tracker_store import TrackerStore
51
+ from rasa.core.channels.channel import InputChannel
52
+ from rasa.core.agent import Agent
53
+ from rasa.shared.nlu.training_data.training_data import TrainingData
54
+ from rasa.shared.importers.importer import TrainingDataImporter
55
+ from rasa.core.utils import AvailableEndpoints
56
+ from rasa.e2e_test.e2e_test_case import TestCase, Fixture, Metadata
57
+
58
+ logger = logging.getLogger(__name__)
59
+
60
+ SEGMENT_TRACK_ENDPOINT = "https://api.segment.io/v1/track"
61
+ SEGMENT_IDENTIFY_ENDPOINT = "https://api.segment.io/v1/identify"
62
+ SEGMENT_REQUEST_TIMEOUT = 5 # seconds
63
+
64
+ TELEMETRY_ENABLED_ENVIRONMENT_VARIABLE = "RASA_TELEMETRY_ENABLED"
65
+ TELEMETRY_DEBUG_ENVIRONMENT_VARIABLE = "RASA_TELEMETRY_DEBUG"
66
+ RASA_PRO_CONFIG_FILE_TELEMETRY_KEY = "traits"
67
+
68
+ # the environment variable can be used for local development to set a test key
69
+ # e.g. `RASA_TELEMETRY_WRITE_KEY=12354 rasa train`
70
+ TELEMETRY_WRITE_KEY_ENVIRONMENT_VARIABLE = "RASA_TELEMETRY_WRITE_KEY"
71
+ EXCEPTION_WRITE_KEY_ENVIRONMENT_VARIABLE = "RASA_EXCEPTION_WRITE_KEY"
72
+
73
+ TELEMETRY_ID = "metrics_id"
74
+ TELEMETRY_ENABLED_BY_DEFAULT = True
75
+
76
+ # if one of these environment variables is set, we assume to be running in CI env
77
+ CI_ENVIRONMENT_TELL = [
78
+ "bamboo.buildKey",
79
+ "BUILD_ID",
80
+ "BUILD_NUMBER",
81
+ "BUILDKITE",
82
+ "CI",
83
+ "CIRCLECI",
84
+ "CONTINUOUS_INTEGRATION",
85
+ "GITHUB_ACTIONS",
86
+ "HUDSON_URL",
87
+ "JENKINS_URL",
88
+ "TEAMCITY_VERSION",
89
+ "TRAVIS",
90
+ "CODEBUILD_BUILD_ARN",
91
+ "CODEBUILD_BUILD_ID",
92
+ "CODEBUILD_BATCH_BUILD_IDENTIFIER",
93
+ ]
94
+
95
+ # If updating or creating a new event, remember to update
96
+ # https://rasa.com/docs/rasa-pro/telemetry/telemetry OR
97
+ # https://rasa.com/docs/rasa-pro/telemetry/reference
98
+ TRAINING_STARTED_EVENT = "Training Started"
99
+ TRAINING_COMPLETED_EVENT = "Training Completed"
100
+ TELEMETRY_DISABLED_EVENT = "Telemetry Disabled"
101
+ TELEMETRY_DATA_SPLIT_EVENT = "Training Data Split"
102
+ TELEMETRY_DATA_VALIDATED_EVENT = "Training Data Validated"
103
+ TELEMETRY_DATA_CONVERTED_EVENT = "Training Data Converted"
104
+ TELEMETRY_TRACKER_EXPORTED_EVENT = "Tracker Exported"
105
+ TELEMETRY_INTERACTIVE_LEARNING_STARTED_EVENT = "Interactive Learning Started"
106
+ TELEMETRY_SERVER_STARTED_EVENT = "Server Started"
107
+ TELEMETRY_PROJECT_CREATED_EVENT = "Project Created"
108
+ TELEMETRY_SHELL_STARTED_EVENT = "Shell Started"
109
+ TELEMETRY_VISUALIZATION_STARTED_EVENT = "Story Visualization Started"
110
+ TELEMETRY_TEST_CORE_EVENT = "Model Core Tested"
111
+ TELEMETRY_TEST_NLU_EVENT = "Model NLU Tested"
112
+ TELEMETRY_MARKERS_EXTRACTION_INITIATED_EVENT = "Markers Extraction Initiated"
113
+ TELEMETRY_MARKERS_EXTRACTED_EVENT = "Markers Extracted"
114
+ TELEMETRY_MARKERS_STATS_COMPUTED_EVENT = "Markers Statistics Computed"
115
+ TELEMETRY_MARKERS_PARSED_COUNT = "Markers Parsed"
116
+
117
+ TELEMETRY_RESPONSE_REPHRASED_EVENT = "Response Rephrased"
118
+ TELEMETRY_INTENTLESS_POLICY_TRAINING_STARTED_EVENT = (
119
+ "Intentless Policy Training Started"
120
+ )
121
+ TELEMETRY_INTENTLESS_POLICY_TRAINING_COMPLETED_EVENT = (
122
+ "Intentless Policy Training Completed"
123
+ )
124
+ TELEMETRY_INTENTLESS_POLICY_PREDICT_EVENT = "Intentless Policy Predicted"
125
+ TELEMETRY_LLM_INTENT_PREDICT_EVENT = "LLM Intent Predicted"
126
+ TELEMETRY_LLM_INTENT_TRAIN_COMPLETED_EVENT = "LLM Intent Training Completed"
127
+ TELEMETRY_E2E_TEST_RUN_STARTED_EVENT = "E2E Test Run Started"
128
+ TELEMETRY_ENTERPRISE_SEARCH_POLICY_TRAINING_STARTED_EVENT = (
129
+ "Enterprise Search Policy Training Started"
130
+ )
131
+ TELEMETRY_ENTERPRISE_SEARCH_POLICY_TRAINING_COMPLETED_EVENT = (
132
+ "Enterprise Search Policy Training Completed"
133
+ )
134
+ TELEMETRY_ENTERPRISE_SEARCH_POLICY_PREDICT_EVENT = "Enterprise Search Policy Predicted"
135
+
136
+ # licensing events
137
+ TELEMETRY_CONVERSATION_COUNT = "Conversation Count"
138
+ TELEMETRY_CONVERSATION_SOFT_LIMIT_REACHED = "Conversation Soft Limit Reached"
139
+ TELEMETRY_CONVERSATION_HARD_LIMIT_REACHED = "Conversation Hard Limit Reached"
140
+
141
+ # used to calculate the context on the first call and cache it afterwards
142
+ TELEMETRY_CONTEXT = None
143
+
144
+ # constants used for the training started events
145
+ NUM_FLOWS = "num_flows"
146
+ NUM_FLOWS_WITH_NLU_TRIGGER = "num_flows_with_nlu_trigger"
147
+ NUM_FLOWS_WITH_FLOW_GUARDS = "num_flows_with_flow_guards"
148
+ NUM_FLOWS_ALWAYS_INCLUDED_IN_PROMPT = "num_flows_always_included_in_prompt"
149
+ NUM_FLOWS_WITH_NOT_STARTABLE_FLOW_GUARDS = "num_flows_with_not_startable_flow_guards"
150
+ NUM_COLLECT_STEPS = "num_collect_steps"
151
+ NUM_COLLECT_STEPS_WITH_SEPARATE_UTTER = "num_collect_steps_with_separate_utter"
152
+ NUM_COLLECT_STEPS_WITH_REJECTIONS = "num_collect_steps_with_rejections"
153
+ NUM_COLLECT_STEPS_WITH_NOT_RESET_AFTER_FLOW_ENDS = (
154
+ "num_collect_steps_with_not_reset_after_flow_ends"
155
+ )
156
+ NUM_SET_SLOT_STEPS = "num_set_slot_steps"
157
+ MAX_DEPTH_OF_IF_CONSTRUCT = "max_depth_of_if_construct"
158
+ NUM_LINK_STEPS = "num_link_steps"
159
+ NUM_CALL_STEPS = "num_call_steps"
160
+ NUM_SHARED_SLOTS_BETWEEN_FLOWS = "num_shared_slots_between_flows"
161
+ LLM_COMMAND_GENERATOR_MODEL_NAME = "llm_command_generator_model_name"
162
+ LLM_COMMAND_GENERATOR_CUSTOM_PROMPT_USED = "llm_command_generator_custom_prompt_used"
163
+ MULTI_STEP_LLM_COMMAND_GENERATOR_HANDLE_FLOWS_PROMPT_USED = (
164
+ "multi_step_llm_command_generator_custom_handle_flows_prompt_used"
165
+ )
166
+ MULTI_STEP_LLM_COMMAND_GENERATOR_FILL_SLOTS_PROMPT_USED = (
167
+ "multi_step_llm_command_generator_custom_fill_slots_prompt_used"
168
+ )
169
+ FLOW_RETRIEVAL_ENABLED = "flow_retrieval_enabled"
170
+ FLOW_RETRIEVAL_EMBEDDING_MODEL_NAME = "flow_retrieval_embedding_model_name"
171
+ TRACING_BACKEND = "tracing_backend"
172
+ METRICS_BACKEND = "metrics_backend"
173
+ VERSION = "version"
174
+
175
+
176
+ def print_telemetry_reporting_info() -> None:
177
+ """Print telemetry information to std out."""
178
+ message = textwrap.dedent(
179
+ f"""
180
+ Rasa Pro reports anonymous usage telemetry to help improve the product
181
+ for all its users.
182
+
183
+ If you'd like to opt-out, you can use `rasa telemetry disable`.
184
+ To learn more, check out {DOCS_URL_TELEMETRY}."""
185
+ ).strip()
186
+
187
+ table = SingleTable([[message]])
188
+ print(table.table)
189
+
190
+
191
+ def _default_telemetry_configuration(is_enabled: bool) -> Dict[Text, Any]:
192
+ return {
193
+ CONFIG_TELEMETRY_ENABLED: is_enabled,
194
+ CONFIG_TELEMETRY_ID: uuid.uuid4().hex,
195
+ CONFIG_TELEMETRY_DATE: datetime.now(),
196
+ }
197
+
198
+
199
+ def _write_default_telemetry_configuration(
200
+ is_enabled: bool = TELEMETRY_ENABLED_BY_DEFAULT,
201
+ ) -> bool:
202
+ new_config = _default_telemetry_configuration(is_enabled)
203
+
204
+ keys = [CONFIG_FILE_TELEMETRY_KEY, RASA_PRO_CONFIG_FILE_TELEMETRY_KEY]
205
+
206
+ success = all(
207
+ [rasa_utils.write_global_config_value(key, new_config) for key in keys]
208
+ )
209
+
210
+ # Do not show info if user has enabled/disabled telemetry via env var
211
+ telemetry_environ = os.environ.get(TELEMETRY_ENABLED_ENVIRONMENT_VARIABLE)
212
+ if is_enabled and success and telemetry_environ is None:
213
+ print_telemetry_reporting_info()
214
+
215
+ return success
216
+
217
+
218
+ def _is_telemetry_enabled_in_configuration() -> bool:
219
+ """Read telemetry configuration from the user's Rasa config file in $HOME.
220
+
221
+ Creates a default configuration if no configuration exists.
222
+
223
+ Returns:
224
+ `True`, if telemetry is enabled, `False` otherwise.
225
+ """
226
+ try:
227
+ stored_config = rasa_utils.read_global_config_value(
228
+ CONFIG_FILE_TELEMETRY_KEY, unavailable_ok=False
229
+ )
230
+
231
+ return stored_config[CONFIG_TELEMETRY_ENABLED]
232
+ except ValueError as e:
233
+ logger.debug(f"Could not read telemetry settings from configuration file: {e}")
234
+
235
+ # seems like there is no config, we'll create one and enable telemetry
236
+ success = _write_default_telemetry_configuration()
237
+ # if writing the configuration failed, telemetry will be disabled
238
+ return TELEMETRY_ENABLED_BY_DEFAULT and success
239
+
240
+
241
+ def is_telemetry_enabled() -> bool:
242
+ """Check if telemetry is enabled either in configuration or environment.
243
+
244
+ Returns:
245
+ `True`, if telemetry is enabled, `False` otherwise.
246
+ """
247
+ from rasa.utils import licensing
248
+
249
+ if licensing.is_champion_server_license():
250
+ logger.debug("Telemetry is enabled for developer licenses.")
251
+ return True
252
+
253
+ telemetry_environ = os.environ.get(TELEMETRY_ENABLED_ENVIRONMENT_VARIABLE)
254
+
255
+ if telemetry_environ is not None:
256
+ return telemetry_environ.lower() == "true"
257
+
258
+ try:
259
+ return rasa_utils.read_global_config_value(
260
+ CONFIG_FILE_TELEMETRY_KEY, unavailable_ok=False
261
+ )[CONFIG_TELEMETRY_ENABLED]
262
+ except ValueError:
263
+ return False
264
+
265
+
266
+ def initialize_telemetry() -> bool:
267
+ """Read telemetry configuration from the user's Rasa config file in $HOME.
268
+
269
+ Creates a default configuration if no configuration exists.
270
+
271
+ Returns:
272
+ `True`, if telemetry is enabled, `False` otherwise.
273
+ """
274
+ try:
275
+ # calling this even if the environment variable is set makes sure the
276
+ # configuration is created and there is a telemetry ID
277
+ is_enabled_in_configuration = _is_telemetry_enabled_in_configuration()
278
+
279
+ telemetry_environ = os.environ.get(TELEMETRY_ENABLED_ENVIRONMENT_VARIABLE)
280
+
281
+ if telemetry_environ is None:
282
+ return is_enabled_in_configuration
283
+
284
+ return telemetry_environ.lower() == "true"
285
+ except Exception as e: # skipcq:PYL-W0703
286
+ logger.exception(
287
+ f"Failed to initialize telemetry reporting: {e}."
288
+ f"Telemetry reporting will be disabled."
289
+ )
290
+ return False
291
+
292
+
293
+ def ensure_telemetry_enabled(f: Callable[..., Any]) -> Callable[..., Any]:
294
+ """Function decorator for telemetry functions that ensures telemetry is enabled.
295
+
296
+ WARNING: does not work as a decorator for async generators.
297
+
298
+ Args:
299
+ f: function to call if telemetry is enabled
300
+ Returns:
301
+ Return wrapped function
302
+ """
303
+ # allows us to use the decorator for async generator functions
304
+ if inspect.isasyncgenfunction(f):
305
+
306
+ @wraps(f)
307
+ async def decorated_async_gen(*args: Any, **kwargs: Any) -> Any:
308
+ if is_telemetry_enabled():
309
+ yield f(*args, **kwargs)
310
+
311
+ return decorated_async_gen
312
+
313
+ # allows us to use the decorator for async and non async functions
314
+ if asyncio.iscoroutinefunction(f):
315
+
316
+ @wraps(f)
317
+ async def decorated_coroutine(*args: Any, **kwargs: Any) -> Any:
318
+ if is_telemetry_enabled():
319
+ return await f(*args, **kwargs)
320
+ return None
321
+
322
+ return decorated_coroutine
323
+
324
+ @wraps(f)
325
+ def decorated(*args: Any, **kwargs: Any) -> Any:
326
+ if is_telemetry_enabled():
327
+ return f(*args, **kwargs)
328
+ return None
329
+
330
+ return decorated
331
+
332
+
333
+ def _fetch_write_key(tool: Text, environment_variable: Text) -> Optional[Text]:
334
+ """Read the write key from a tool from our set of keys.
335
+
336
+ Args:
337
+ tool: name of the tool we want to fetch a key for
338
+ environment_variable: name of the environment variable to set the key
339
+ Returns:
340
+ write key, if a key was present.
341
+ """
342
+ import importlib_resources
343
+ from rasa import __name__ as name
344
+
345
+ if os.environ.get(environment_variable):
346
+ # a write key set using the environment variable will always
347
+ # overwrite any key provided as part of the package (`keys` file)
348
+ return os.environ.get(environment_variable)
349
+
350
+ write_key_path = str(importlib_resources.files(name).joinpath("keys"))
351
+
352
+ # noinspection PyBroadException
353
+ try:
354
+ with open(write_key_path) as f:
355
+ return json.load(f).get(tool)
356
+ except Exception: # skipcq:PYL-W0703
357
+ return None
358
+
359
+
360
+ def telemetry_write_key() -> Optional[Text]:
361
+ """Read the Segment write key from the segment key text file.
362
+
363
+ The segment key text file should by present only in wheel/sdist packaged
364
+ versions of Rasa Pro. This avoids running telemetry locally when
365
+ developing on Rasa or when running CI builds.
366
+
367
+ In local development, this should always return `None` to avoid logging telemetry.
368
+
369
+ Returns:
370
+ Segment write key, if the key file was present.
371
+ """
372
+ return _fetch_write_key("segment", TELEMETRY_WRITE_KEY_ENVIRONMENT_VARIABLE)
373
+
374
+
375
+ def sentry_write_key() -> Optional[Text]:
376
+ """Read the sentry write key from the sentry key text file.
377
+
378
+ Returns:
379
+ Sentry write key, if the key file was present.
380
+ """
381
+ return _fetch_write_key("sentry", EXCEPTION_WRITE_KEY_ENVIRONMENT_VARIABLE)
382
+
383
+
384
+ def _encode_base64(original: Text, encoding: Text = "utf-8") -> Text:
385
+ """Encodes a string as a base64 string.
386
+
387
+ Args:
388
+ original: Text to be encoded.
389
+ encoding: Encoding used to convert text to binary.
390
+
391
+ Returns:
392
+ Encoded text.
393
+ """
394
+ import base64
395
+
396
+ return base64.b64encode(original.encode(encoding)).decode(encoding)
397
+
398
+
399
+ def segment_request_header(write_key: Text) -> Dict[Text, Any]:
400
+ """Use a segment write key to create authentication headers for the segment API.
401
+
402
+ Args:
403
+ write_key: Authentication key for segment.
404
+
405
+ Returns:
406
+ Authentication headers for segment.
407
+ """
408
+ return {
409
+ "Authorization": "Basic {}".format(_encode_base64(write_key + ":")),
410
+ "Content-Type": "application/json",
411
+ }
412
+
413
+
414
+ def segment_request_payload(
415
+ distinct_id: Text,
416
+ event_name: Text,
417
+ properties: Dict[Text, Any],
418
+ context: Dict[Text, Any],
419
+ ) -> Dict[Text, Any]:
420
+ """Compose a valid payload for the segment API.
421
+
422
+ Args:
423
+ distinct_id: Unique telemetry ID.
424
+ event_name: Name of the event.
425
+ properties: Values to report along the event.
426
+ context: Context information about the event.
427
+
428
+ Returns:
429
+ Valid segment payload.
430
+ """
431
+ return {
432
+ "userId": distinct_id,
433
+ "event": event_name,
434
+ "properties": properties,
435
+ "context": context,
436
+ }
437
+
438
+
439
+ def in_continuous_integration() -> bool:
440
+ """Returns `True` if currently running inside a continuous integration context."""
441
+ return any(env in os.environ for env in CI_ENVIRONMENT_TELL)
442
+
443
+
444
+ def _is_telemetry_debug_enabled() -> bool:
445
+ """Check if telemetry debug mode is enabled."""
446
+ return (
447
+ os.environ.get(TELEMETRY_DEBUG_ENVIRONMENT_VARIABLE, "false").lower() == "true"
448
+ )
449
+
450
+
451
+ def print_telemetry_payload(payload: Dict[Text, Any]) -> None:
452
+ """Print a telemetry payload to the commandline.
453
+
454
+ Args:
455
+ payload: payload to be delivered to segment.
456
+ """
457
+ payload_json = json.dumps(payload, indent=2)
458
+ logger.debug(f"Telemetry payload: {payload_json}")
459
+
460
+
461
+ def _get_telemetry_write_key() -> Optional[Text]:
462
+ if os.environ.get(TELEMETRY_WRITE_KEY_ENVIRONMENT_VARIABLE):
463
+ return os.environ.get(TELEMETRY_WRITE_KEY_ENVIRONMENT_VARIABLE)
464
+
465
+ write_key_path = str(importlib_resources.files(rasa.__name__).joinpath("keys"))
466
+
467
+ try:
468
+ with open(write_key_path) as f:
469
+ return json.load(f).get("segment")
470
+ except Exception:
471
+ return None
472
+
473
+
474
+ def _send_event(
475
+ distinct_id: Text,
476
+ event_name: Text,
477
+ properties: Dict[Text, Any],
478
+ context: Dict[Text, Any],
479
+ ) -> None:
480
+ """Report the contents segmentof an event to the /track Segment endpoint.
481
+
482
+ Documentation: https://.com/docs/sources/server/http/
483
+
484
+ Do not call this function from outside telemetry.py! This function does not
485
+ check if telemetry is enabled or not.
486
+
487
+ Args:
488
+ distinct_id: Unique telemetry ID.
489
+ event_name: Name of the event.
490
+ properties: Values to report along the event.
491
+ context: Context information about the event.
492
+ """
493
+ payload = segment_request_payload(distinct_id, event_name, properties, context)
494
+
495
+ _send_request(SEGMENT_TRACK_ENDPOINT, payload)
496
+
497
+
498
+ def _send_request(url: Text, payload: Dict[Text, Any]) -> None:
499
+ """Send a request to the Segment API.
500
+
501
+ Args:
502
+ url: URL of the Segment API endpoint
503
+ payload: payload to send to the Segment API
504
+ """
505
+ if _is_telemetry_debug_enabled():
506
+ print_telemetry_payload(payload)
507
+ return
508
+
509
+ write_key = _get_telemetry_write_key()
510
+ if not write_key:
511
+ # If RASA_TELEMETRY_WRITE_KEY is empty or `None`, telemetry has not
512
+ # been enabled for this build (e.g. because it is running from source)
513
+ logger.debug("Skipping request to external service: telemetry key not set.")
514
+ return
515
+
516
+ headers = rasa.telemetry.segment_request_header(write_key)
517
+
518
+ resp = requests.post(
519
+ url=url,
520
+ headers=headers,
521
+ json=payload,
522
+ timeout=SEGMENT_REQUEST_TIMEOUT,
523
+ )
524
+ # handle different failure cases
525
+ if resp.status_code != 200:
526
+ logger.debug(
527
+ f"Segment telemetry request returned a {resp.status_code} response. "
528
+ f"Body: {resp.text}"
529
+ )
530
+ else:
531
+ data = resp.json()
532
+ if not data.get("success"):
533
+ logger.debug(
534
+ f"Segment telemetry request returned a failure. Response: {data}"
535
+ )
536
+
537
+
538
+ def _hash_directory_path(path: Text) -> Optional[Text]:
539
+ """Create a hash for the directory.
540
+
541
+ Returns:
542
+ hash of the directories path
543
+ """
544
+ full_path = Path(path).absolute()
545
+ return hashlib.sha256(str(full_path).encode("utf-8")).hexdigest()
546
+
547
+
548
+ # noinspection PyBroadException
549
+ def _is_docker() -> bool:
550
+ """Guess if we are running in docker environment.
551
+
552
+ Returns:
553
+ `True` if we are running inside docker, `False` otherwise.
554
+ """
555
+ # first we try to use the env
556
+ try:
557
+ os.stat("/.dockerenv")
558
+ return True
559
+ except Exception: # skipcq:PYL-W0703
560
+ pass
561
+
562
+ # if that didn't work, try to use proc information
563
+ try:
564
+ return "docker" in rasa.shared.utils.io.read_file("/proc/self/cgroup", "utf8")
565
+ except Exception: # skipcq:PYL-W0703
566
+ return False
567
+
568
+
569
+ def with_default_context_fields(
570
+ context: Optional[Dict[Text, Any]] = None,
571
+ ) -> Dict[Text, Any]:
572
+ """Return a new context dictionary with default and provided field values merged.
573
+
574
+ The default fields contain only the OS information for now.
575
+
576
+ Args:
577
+ context: Context information about the event.
578
+
579
+ Return:
580
+ A new context.
581
+ """
582
+ context = context or {}
583
+
584
+ return {**_default_context_fields(), **context}
585
+
586
+
587
+ def _default_context_fields() -> Dict[Text, Any]:
588
+ """Return a dictionary that contains the default context values.
589
+
590
+ Return:
591
+ A new context containing information about the runtime environment.
592
+ """
593
+ from rasa.utils.licensing import property_of_active_license, get_license_hash
594
+
595
+ global TELEMETRY_CONTEXT
596
+
597
+ if not TELEMETRY_CONTEXT:
598
+ # Make sure to update the example in docs/docs/telemetry/telemetry.mdx
599
+ # if you change / add context
600
+ TELEMETRY_CONTEXT = {
601
+ "os": {"name": platform.system(), "version": platform.release()},
602
+ "ci": in_continuous_integration(),
603
+ "project": model.project_fingerprint(),
604
+ "directory": _hash_directory_path(os.getcwd()),
605
+ "python": sys.version.split(" ")[0],
606
+ "rasa_pro": rasa.__version__,
607
+ "cpu": multiprocessing.cpu_count(),
608
+ "docker": _is_docker(),
609
+ "license_hash": get_license_hash(),
610
+ "company": property_of_active_license(
611
+ lambda active_license: active_license.company
612
+ ),
613
+ }
614
+
615
+ # avoid returning the cached dict --> caller could modify the dictionary...
616
+ # usually we would use `lru_cache`, but that doesn't return a dict copy and
617
+ # doesn't work on inner functions, so we need to roll our own caching...
618
+ return TELEMETRY_CONTEXT.copy()
619
+
620
+
621
+ def _track(
622
+ event_name: Text,
623
+ properties: Optional[Dict[Text, Any]] = None,
624
+ context: Optional[Dict[Text, Any]] = None,
625
+ ) -> None:
626
+ """Tracks a telemetry event.
627
+
628
+ It is OK to use this function from outside telemetry.py, but note that it
629
+ is recommended to create a new track_xyz() function for complex telemetry
630
+ events, or events that are generated from many parts of the Rasa Pro code.
631
+
632
+ Args:
633
+ event_name: Name of the event.
634
+ properties: Dictionary containing the event's properties.
635
+ context: Dictionary containing some context for this event.
636
+ """
637
+ try:
638
+ telemetry_id = get_telemetry_id()
639
+
640
+ if not telemetry_id:
641
+ logger.debug("Will not report telemetry events as no ID was found.")
642
+ return
643
+
644
+ if not properties:
645
+ properties = {}
646
+
647
+ properties[TELEMETRY_ID] = telemetry_id
648
+
649
+ # this is an additional check in case _track() is called
650
+ # from a function that is not decorated with @ensure_telemetry_enabled
651
+ if is_telemetry_enabled():
652
+ _send_event(
653
+ telemetry_id,
654
+ event_name,
655
+ properties,
656
+ with_default_context_fields(context),
657
+ )
658
+ except Exception as e: # skipcq:PYL-W0703
659
+ logger.debug(f"Skipping telemetry reporting: {e}")
660
+
661
+
662
+ def _identify(
663
+ traits: Optional[Dict[Text, Any]] = None,
664
+ context: Optional[Dict[Text, Any]] = None,
665
+ ) -> None:
666
+ """Tracks telemetry traits.
667
+
668
+ It is OK to use this function from outside telemetry.py, but note that it
669
+ is recommended to create a new track_xyz() function for complex telemetry
670
+ traits, or traits that are generated from many parts of the Rasa Pro code.
671
+
672
+ Args:
673
+ traits: Dictionary containing the tracked traits.
674
+ context: Dictionary containing some context for the traits.
675
+ """
676
+ try:
677
+ telemetry_id = get_telemetry_id()
678
+
679
+ if not telemetry_id:
680
+ logger.debug("Will not report telemetry events as no ID was found.")
681
+ return
682
+
683
+ if not traits:
684
+ traits = {}
685
+
686
+ _send_traits(telemetry_id, traits, with_default_context_fields(context))
687
+ except Exception as e:
688
+ logger.debug(f"Skipping telemetry reporting: {e}")
689
+
690
+
691
+ def _send_traits(
692
+ distinct_id: Text,
693
+ traits: Dict[Text, Any],
694
+ context: Dict[Text, Any],
695
+ ) -> None:
696
+ """Report the contents of telemetry traits to the /identify Segment endpoint.
697
+
698
+ Do not call this function from outside telemetry.py! This function does not
699
+ check if telemetry is enabled or not.
700
+
701
+ Args:
702
+ distinct_id: Unique telemetry ID.
703
+ traits: Pieces of information to be recorded about
704
+ rasa_plus interface implementations.
705
+ context: Context information to be sent along with traits.
706
+ """
707
+ payload = segment_identify_request_payload(distinct_id, traits, context)
708
+
709
+ _send_request(SEGMENT_IDENTIFY_ENDPOINT, payload)
710
+
711
+
712
+ def segment_identify_request_payload(
713
+ distinct_id: Text,
714
+ traits: Dict[Text, Any],
715
+ context: Dict[Text, Any],
716
+ ) -> Dict[Text, Any]:
717
+ """Compose a valid payload for the segment API.
718
+
719
+ Args:
720
+ distinct_id: Unique telemetry ID.
721
+ traits: Pieces of information to be recorded about
722
+ rasa_plus interface implementations.
723
+ context: Context information to be sent along with traits.
724
+
725
+ Returns:
726
+ Valid segment payload.
727
+ """
728
+ return {
729
+ "userId": distinct_id,
730
+ "traits": traits,
731
+ "context": context,
732
+ }
733
+
734
+
735
+ def get_telemetry_id() -> Optional[Text]:
736
+ """Return the unique telemetry identifier for this Rasa Pro install.
737
+
738
+ The identifier can be based on the license.
739
+ Otherwise, it can be any string, but it should be a UUID.
740
+
741
+ Returns:
742
+ The identifier, if it is configured correctly.
743
+ """
744
+ from rasa.utils.licensing import property_of_active_license
745
+
746
+ return property_of_active_license(lambda active_license: active_license.jti)
747
+
748
+
749
+ def toggle_telemetry_reporting(is_enabled: bool) -> None:
750
+ """Write to the configuration if telemetry tracking should be enabled or disabled.
751
+
752
+ Args:
753
+ is_enabled: `True` if the telemetry reporting should be enabled,
754
+ `False` otherwise.
755
+ """
756
+ configuration = rasa_utils.read_global_config_value(CONFIG_FILE_TELEMETRY_KEY)
757
+
758
+ if configuration:
759
+ configuration[CONFIG_TELEMETRY_ENABLED] = is_enabled
760
+ else:
761
+ configuration = _default_telemetry_configuration(is_enabled)
762
+
763
+ rasa_utils.write_global_config_value(CONFIG_FILE_TELEMETRY_KEY, configuration)
764
+ rasa_utils.write_global_config_value(
765
+ RASA_PRO_CONFIG_FILE_TELEMETRY_KEY, configuration
766
+ )
767
+
768
+
769
+ def filter_errors(
770
+ event: Optional[Dict[Text, Any]], hint: Optional[Dict[Text, Any]] = None
771
+ ) -> Optional[Dict[Text, Any]]:
772
+ """Filter errors.
773
+
774
+ Args:
775
+ event: event to be logged to sentry
776
+ hint: some hinting information sent alongside of the event
777
+
778
+ Returns:
779
+ the event without any sensitive / PII data or `None` if the event constitutes
780
+ an `ImportError` which should be discarded.
781
+ """
782
+ if hint and "exc_info" in hint:
783
+ exc_type, exc_value, tb = hint["exc_info"]
784
+ if isinstance(exc_value, ImportError):
785
+ return None
786
+ return event
787
+
788
+
789
+ def before_send(
790
+ event: Dict[Text, Any], _unused_hint: Optional[Dict[Text, Any]] = None
791
+ ) -> Optional[Dict[Text, Any]]:
792
+ """Strips the sensitive data and filters errors before sending to sentry.
793
+
794
+ Args:
795
+ event: event to be logged to sentry
796
+ _unused_hint: some hinting information sent alongside of the event
797
+
798
+ Returns:
799
+ the event without any sensitive / PII data or `None` if the event should
800
+ be discarded.
801
+ """
802
+ cleaned_event = strip_sensitive_data_from_sentry_event(event, _unused_hint)
803
+ return filter_errors(cleaned_event, _unused_hint)
804
+
805
+
806
+ def strip_sensitive_data_from_sentry_event(
807
+ event: Dict[Text, Any], _unused_hint: Optional[Dict[Text, Any]] = None
808
+ ) -> Optional[Dict[Text, Any]]:
809
+ """Remove any sensitive data from the event (e.g. path names).
810
+
811
+ Args:
812
+ event: event to be logged to sentry
813
+ _unused_hint: some hinting information sent alongside of the event
814
+
815
+ Returns:
816
+ the event without any sensitive / PII data or `None` if the event should
817
+ be discarded.
818
+ """
819
+ # removes any paths from stack traces (avoids e.g. sending
820
+ # a users home directory name if package is installed there)
821
+ for value in event.get("exception", {}).get("values", []):
822
+ for frame in value.get("stacktrace", {}).get("frames", []):
823
+ frame["abs_path"] = ""
824
+
825
+ if f"rasa_sdk{os.path.sep}executor.py" in frame["filename"]:
826
+ # this looks a lot like an exception in the SDK and hence custom code
827
+ # no need for us to deal with that
828
+ return None
829
+ elif "site-packages" in frame["filename"]:
830
+ # drop site-packages and following slash / backslash
831
+ relative_name = frame["filename"].split("site-packages")[-1][1:]
832
+ frame["filename"] = os.path.join("site-packages", relative_name)
833
+ elif "dist-packages" in frame["filename"]:
834
+ # drop dist-packages and following slash / backslash
835
+ relative_name = frame["filename"].split("dist-packages")[-1][1:]
836
+ frame["filename"] = os.path.join("dist-packages", relative_name)
837
+ elif os.path.isabs(frame["filename"]):
838
+ # if the file path is absolute, we'll drop the whole event as this is
839
+ # very likely custom code. needs to happen after cleaning as
840
+ # site-packages / dist-packages paths are also absolute, but fine.
841
+ return None
842
+ return event
843
+
844
+
845
+ @ensure_telemetry_enabled
846
+ def initialize_error_reporting() -> None:
847
+ """Sets up automated error reporting.
848
+
849
+ Exceptions are reported to sentry. We avoid sending any metadata (local
850
+ variables, paths, ...) to make sure we don't compromise any data. Only the
851
+ exception and its stacktrace is logged and only if the exception origins
852
+ from the `rasa` package.
853
+ """
854
+ import sentry_sdk
855
+ from sentry_sdk import configure_scope
856
+ from sentry_sdk.integrations.atexit import AtexitIntegration
857
+ from sentry_sdk.integrations.dedupe import DedupeIntegration
858
+ from sentry_sdk.integrations.excepthook import ExcepthookIntegration
859
+
860
+ # key for local testing can be found at
861
+ # https://sentry.io/settings/rasahq/projects/rasa-open-source/install/python/
862
+ # for local testing, set the key using `RASA_EXCEPTION_WRITE_KEY=key rasa <command>`
863
+ key = sentry_write_key()
864
+
865
+ if not key:
866
+ return
867
+
868
+ telemetry_id = get_telemetry_id()
869
+
870
+ # this is a very defensive configuration, avoiding as many integrations as
871
+ # possible. it also submits very little data (exception with error message
872
+ # and line numbers).
873
+ sentry_sdk.init(
874
+ f"https://{key}.ingest.sentry.io/2801673",
875
+ before_send=before_send,
876
+ integrations=[
877
+ ExcepthookIntegration(),
878
+ DedupeIntegration(),
879
+ AtexitIntegration(lambda _, __: None),
880
+ ],
881
+ send_default_pii=False, # activate PII filter
882
+ server_name=telemetry_id or "UNKNOWN",
883
+ ignore_errors=[
884
+ # std lib errors
885
+ KeyboardInterrupt, # user hit the interrupt key (Ctrl+C)
886
+ MemoryError, # machine is running out of memory
887
+ NotImplementedError, # user is using a feature that is not implemented
888
+ asyncio.CancelledError, # an async operation has been cancelled by the user
889
+ # expected Rasa errors
890
+ RasaException,
891
+ OSError,
892
+ ],
893
+ in_app_include=["rasa"], # only submit errors in this package
894
+ with_locals=False, # don't submit local variables
895
+ release=f"rasa-{rasa.__version__}",
896
+ default_integrations=False,
897
+ environment="development" if in_continuous_integration() else "production",
898
+ )
899
+
900
+ if not telemetry_id:
901
+ return
902
+
903
+ with configure_scope() as scope:
904
+ # sentry added these more recently, just a protection in a case where a
905
+ # user has installed an older version of sentry
906
+ if hasattr(scope, "set_user"):
907
+ scope.set_user({"id": telemetry_id})
908
+
909
+ default_context = _default_context_fields()
910
+ if hasattr(scope, "set_context"):
911
+ if "os" in default_context:
912
+ # os is a nested dict, hence we report it separately
913
+ scope.set_context("Operating System", default_context.pop("os"))
914
+ scope.set_context("Environment", default_context)
915
+
916
+
917
+ @contextlib.contextmanager
918
+ def track_model_training(
919
+ training_data: "TrainingDataImporter", model_type: Text, is_finetuning: bool = False
920
+ ) -> typing.Generator[None, None, None]:
921
+ """Track a model training started.
922
+
923
+ WARNING: since this is a generator, it can't use the ensure telemetry
924
+ decorator. We need to manually add these checks here. This can be
925
+ fixed as soon as we drop python 3.6 support.
926
+
927
+ Args:
928
+ training_data: Training data used for the training.
929
+ model_type: Specifies the type of training, should be either "rasa", "core"
930
+ or "nlu".
931
+ is_finetuning: `True` if the model is trained by finetuning another model.
932
+ """
933
+ if not initialize_telemetry():
934
+ # telemetry reporting is disabled. we won't do any reporting
935
+ yield # runs the training
936
+ return
937
+
938
+ config = training_data.get_config()
939
+ stories = training_data.get_stories()
940
+ nlu_data = training_data.get_nlu_data()
941
+ domain = training_data.get_domain()
942
+ flows = training_data.get_flows()
943
+ count_conditional_responses = domain.count_conditional_response_variations()
944
+ (
945
+ count_total_mappings,
946
+ count_custom_mappings,
947
+ count_conditional_mappings,
948
+ ) = domain.count_slot_mapping_statistics()
949
+
950
+ training_id = uuid.uuid4().hex
951
+
952
+ tracking_data = {
953
+ "language": config.get("language"),
954
+ "training_id": training_id,
955
+ "type": model_type,
956
+ "pipeline": config.get("pipeline"),
957
+ "policies": config.get("policies"),
958
+ "train_schema": config.get("train_schema"),
959
+ "predict_schema": config.get("predict_schema"),
960
+ "num_intent_examples": len(nlu_data.intent_examples),
961
+ "num_entity_examples": len(nlu_data.entity_examples),
962
+ "num_actions": len(domain.action_names_or_texts),
963
+ # Old nomenclature from when 'responses' were still called
964
+ # 'templates' in the domain
965
+ "num_templates": len(domain.responses),
966
+ "num_conditional_response_variations": count_conditional_responses,
967
+ "num_slot_mappings": count_total_mappings,
968
+ "num_custom_slot_mappings": count_custom_mappings,
969
+ "num_conditional_slot_mappings": count_conditional_mappings,
970
+ "num_slots": len(domain.slots),
971
+ "num_forms": len(domain.forms),
972
+ "num_intents": len(domain.intents),
973
+ "num_entities": len(domain.entities),
974
+ "num_story_steps": len(stories.story_steps),
975
+ "num_lookup_tables": len(nlu_data.lookup_tables),
976
+ "num_synonyms": len(nlu_data.entity_synonyms),
977
+ "num_regexes": len(nlu_data.regex_features),
978
+ "is_finetuning": is_finetuning,
979
+ "recipe": config.get("recipe"),
980
+ }
981
+
982
+ flow_statistics = _collect_flow_statistics(flows.underlying_flows)
983
+ tracking_data.update(flow_statistics)
984
+ command_generator_settings = _get_llm_command_generator_config(config)
985
+ tracking_data.update(command_generator_settings)
986
+
987
+ # Make sure to update the example in docs/docs/telemetry/telemetry.mdx
988
+ # if you change / add any properties
989
+ _track(
990
+ TRAINING_STARTED_EVENT,
991
+ tracking_data,
992
+ )
993
+ start = datetime.now()
994
+ yield
995
+ runtime = datetime.now() - start
996
+
997
+ _track(
998
+ TRAINING_COMPLETED_EVENT,
999
+ {
1000
+ "training_id": training_id,
1001
+ "type": model_type,
1002
+ "runtime": int(runtime.total_seconds()),
1003
+ },
1004
+ )
1005
+
1006
+
1007
+ def _collect_flow_statistics(flows: List[Flow]) -> Dict[str, Any]:
1008
+ """Collects some statistics about the flows, such as number of specific steps."""
1009
+ data = {
1010
+ NUM_FLOWS: len(flows),
1011
+ NUM_FLOWS_WITH_NLU_TRIGGER: 0,
1012
+ NUM_FLOWS_WITH_FLOW_GUARDS: 0,
1013
+ NUM_FLOWS_ALWAYS_INCLUDED_IN_PROMPT: 0,
1014
+ NUM_FLOWS_WITH_NOT_STARTABLE_FLOW_GUARDS: 0,
1015
+ NUM_COLLECT_STEPS: 0,
1016
+ NUM_COLLECT_STEPS_WITH_SEPARATE_UTTER: 0,
1017
+ NUM_COLLECT_STEPS_WITH_REJECTIONS: 0,
1018
+ NUM_COLLECT_STEPS_WITH_NOT_RESET_AFTER_FLOW_ENDS: 0,
1019
+ NUM_SET_SLOT_STEPS: 0,
1020
+ MAX_DEPTH_OF_IF_CONSTRUCT: 0,
1021
+ NUM_LINK_STEPS: 0,
1022
+ NUM_CALL_STEPS: 0,
1023
+ NUM_SHARED_SLOTS_BETWEEN_FLOWS: 0,
1024
+ }
1025
+
1026
+ slots_used_in_different_flows = defaultdict(set)
1027
+
1028
+ for flow in flows:
1029
+ if flow.guard_condition:
1030
+ data[NUM_FLOWS_WITH_FLOW_GUARDS] += 1
1031
+ if flow.guard_condition.lower() == "false":
1032
+ data[NUM_FLOWS_WITH_NOT_STARTABLE_FLOW_GUARDS] += 1
1033
+
1034
+ if flow.always_include_in_prompt:
1035
+ data[NUM_FLOWS_ALWAYS_INCLUDED_IN_PROMPT] += 1
1036
+
1037
+ if flow.nlu_triggers:
1038
+ data[NUM_FLOWS_WITH_NLU_TRIGGER] += 1
1039
+
1040
+ for step in flow.steps_with_calls_resolved:
1041
+ if isinstance(step, CollectInformationFlowStep):
1042
+ slots_used_in_different_flows[step.collect].add(flow.id)
1043
+ data[NUM_COLLECT_STEPS] += 1
1044
+ if len(step.rejections) > 0:
1045
+ data[NUM_COLLECT_STEPS_WITH_REJECTIONS] += 1
1046
+ if not step.reset_after_flow_ends:
1047
+ data[NUM_COLLECT_STEPS_WITH_NOT_RESET_AFTER_FLOW_ENDS] += 1
1048
+ if step.utter != f"{UTTER_ASK_PREFIX}{step.collect}":
1049
+ data[NUM_COLLECT_STEPS_WITH_SEPARATE_UTTER] += 1
1050
+
1051
+ if isinstance(step, SetSlotsFlowStep):
1052
+ for slot in step.slots:
1053
+ slots_used_in_different_flows[slot["key"]].add(flow.id)
1054
+ data[NUM_SET_SLOT_STEPS] += 1
1055
+
1056
+ if isinstance(step, LinkFlowStep):
1057
+ data[NUM_LINK_STEPS] += 1
1058
+
1059
+ if isinstance(step, CallFlowStep):
1060
+ data[NUM_CALL_STEPS] += 1
1061
+
1062
+ if step.next:
1063
+ depth = step.next.depth_in_tree()
1064
+ if depth > data[MAX_DEPTH_OF_IF_CONSTRUCT]:
1065
+ data[MAX_DEPTH_OF_IF_CONSTRUCT] = depth
1066
+
1067
+ for flows_with_slot in slots_used_in_different_flows.values():
1068
+ if len(flows_with_slot) > 1:
1069
+ data[NUM_SHARED_SLOTS_BETWEEN_FLOWS] += 1
1070
+
1071
+ return data
1072
+
1073
+
1074
+ def _get_llm_command_generator_config(config: Dict[str, Any]) -> Optional[Dict]:
1075
+ """Returns the configuration for the LLMCommandGenerator.
1076
+
1077
+ Includes the model name, whether a custom prompt is used, whether flow
1078
+ retrieval is enabled, and flow retrieval embedding model.
1079
+ """
1080
+ from rasa.shared.constants import (
1081
+ MODEL_CONFIG_KEY,
1082
+ MODEL_NAME_CONFIG_KEY,
1083
+ )
1084
+ from rasa.dialogue_understanding.generator import (
1085
+ LLMCommandGenerator,
1086
+ SingleStepLLMCommandGenerator,
1087
+ MultiStepLLMCommandGenerator,
1088
+ )
1089
+ from rasa.dialogue_understanding.generator.multi_step.multi_step_llm_command_generator import ( # noqa: E501
1090
+ HANDLE_FLOWS_KEY,
1091
+ FILL_SLOTS_KEY,
1092
+ )
1093
+ from rasa.dialogue_understanding.generator.constants import (
1094
+ LLM_CONFIG_KEY,
1095
+ DEFAULT_LLM_CONFIG,
1096
+ FLOW_RETRIEVAL_KEY,
1097
+ )
1098
+ from rasa.dialogue_understanding.generator.flow_retrieval import (
1099
+ DEFAULT_EMBEDDINGS_CONFIG,
1100
+ )
1101
+
1102
+ def find_command_generator_component(pipeline: List) -> Optional[Dict]:
1103
+ """Finds the LLMCommandGenerator component in the pipeline."""
1104
+ for component in pipeline:
1105
+ if component["name"] in [
1106
+ LLMCommandGenerator.__name__,
1107
+ SingleStepLLMCommandGenerator.__name__,
1108
+ MultiStepLLMCommandGenerator.__name__,
1109
+ ]:
1110
+ return component
1111
+ return None
1112
+
1113
+ def extract_settings(component: Dict) -> Dict:
1114
+ """Extracts the settings from the command generator component."""
1115
+ llm_config = component.get(LLM_CONFIG_KEY, {})
1116
+ llm_model_name = (
1117
+ llm_config.get(MODEL_CONFIG_KEY)
1118
+ or llm_config.get(MODEL_NAME_CONFIG_KEY)
1119
+ or DEFAULT_LLM_CONFIG[MODEL_NAME_CONFIG_KEY]
1120
+ )
1121
+ flow_retrieval_config = component.get(FLOW_RETRIEVAL_KEY, {})
1122
+ flow_retrieval_enabled = flow_retrieval_config.get("active", True)
1123
+ flow_retrieval_embedding_model_name = (
1124
+ flow_retrieval_config.get("embeddings", DEFAULT_EMBEDDINGS_CONFIG).get(
1125
+ "model"
1126
+ )
1127
+ if flow_retrieval_enabled
1128
+ else None
1129
+ )
1130
+ return {
1131
+ LLM_COMMAND_GENERATOR_MODEL_NAME: llm_model_name,
1132
+ LLM_COMMAND_GENERATOR_CUSTOM_PROMPT_USED: PROMPT_CONFIG_KEY in component
1133
+ or PROMPT_TEMPLATE_CONFIG_KEY in component,
1134
+ MULTI_STEP_LLM_COMMAND_GENERATOR_HANDLE_FLOWS_PROMPT_USED: HANDLE_FLOWS_KEY
1135
+ in component.get("prompt_templates", {}),
1136
+ MULTI_STEP_LLM_COMMAND_GENERATOR_FILL_SLOTS_PROMPT_USED: FILL_SLOTS_KEY
1137
+ in component.get("prompt_templates", {}),
1138
+ FLOW_RETRIEVAL_ENABLED: flow_retrieval_enabled,
1139
+ FLOW_RETRIEVAL_EMBEDDING_MODEL_NAME: flow_retrieval_embedding_model_name,
1140
+ }
1141
+
1142
+ command_generator_config = {
1143
+ LLM_COMMAND_GENERATOR_MODEL_NAME: None,
1144
+ LLM_COMMAND_GENERATOR_CUSTOM_PROMPT_USED: None,
1145
+ MULTI_STEP_LLM_COMMAND_GENERATOR_HANDLE_FLOWS_PROMPT_USED: None,
1146
+ MULTI_STEP_LLM_COMMAND_GENERATOR_FILL_SLOTS_PROMPT_USED: None,
1147
+ FLOW_RETRIEVAL_ENABLED: None,
1148
+ FLOW_RETRIEVAL_EMBEDDING_MODEL_NAME: None,
1149
+ }
1150
+
1151
+ pipeline = config.get("pipeline", [])
1152
+ if not isinstance(pipeline, list):
1153
+ return command_generator_config
1154
+
1155
+ command_generator_component = find_command_generator_component(pipeline)
1156
+ if command_generator_component is not None:
1157
+ extracted_settings = extract_settings(command_generator_component)
1158
+ command_generator_config.update(extracted_settings)
1159
+
1160
+ return command_generator_config
1161
+
1162
+
1163
+ @ensure_telemetry_enabled
1164
+ def track_telemetry_disabled() -> None:
1165
+ """Track when a user disables telemetry."""
1166
+ _track(TELEMETRY_DISABLED_EVENT)
1167
+
1168
+
1169
+ @ensure_telemetry_enabled
1170
+ def track_data_split(fraction: float, data_type: Text) -> None:
1171
+ """Track when a user splits data.
1172
+
1173
+ Args:
1174
+ fraction: How much data goes into train and how much goes into test
1175
+ data_type: Is this core, nlu or nlg data
1176
+ """
1177
+ _track(TELEMETRY_DATA_SPLIT_EVENT, {"fraction": fraction, "type": data_type})
1178
+
1179
+
1180
+ @ensure_telemetry_enabled
1181
+ def track_validate_files(validation_success: bool) -> None:
1182
+ """Track when a user validates data files.
1183
+
1184
+ Args:
1185
+ validation_success: Whether the validation was successful
1186
+ """
1187
+ _track(TELEMETRY_DATA_VALIDATED_EVENT, {"validation_success": validation_success})
1188
+
1189
+
1190
+ @ensure_telemetry_enabled
1191
+ def track_data_convert(output_format: Text, data_type: Text) -> None:
1192
+ """Track when a user converts data.
1193
+
1194
+ Args:
1195
+ output_format: Target format for the converter
1196
+ data_type: Is this core, nlu or nlg data
1197
+ """
1198
+ _track(
1199
+ TELEMETRY_DATA_CONVERTED_EVENT,
1200
+ {"output_format": output_format, "type": data_type},
1201
+ )
1202
+
1203
+
1204
+ @ensure_telemetry_enabled
1205
+ def track_tracker_export(
1206
+ number_of_exported_events: int,
1207
+ tracker_store: "TrackerStore",
1208
+ event_broker: "EventBroker",
1209
+ ) -> None:
1210
+ """Track when a user exports trackers.
1211
+
1212
+ Args:
1213
+ number_of_exported_events: Number of events that got exported
1214
+ tracker_store: Store used to retrieve the events from
1215
+ event_broker: Broker the events are getting published towards
1216
+ """
1217
+ _track(
1218
+ TELEMETRY_TRACKER_EXPORTED_EVENT,
1219
+ {
1220
+ "number_of_exported_events": number_of_exported_events,
1221
+ "tracker_store": type(tracker_store).__name__,
1222
+ "event_broker": type(event_broker).__name__,
1223
+ },
1224
+ )
1225
+
1226
+
1227
+ @ensure_telemetry_enabled
1228
+ def track_interactive_learning_start(
1229
+ skip_visualization: bool, save_in_e2e: bool
1230
+ ) -> None:
1231
+ """Track when a user starts an interactive learning session.
1232
+
1233
+ Args:
1234
+ skip_visualization: Is visualization skipped in this session
1235
+ save_in_e2e: Is e2e used in this session
1236
+ """
1237
+ _track(
1238
+ TELEMETRY_INTERACTIVE_LEARNING_STARTED_EVENT,
1239
+ {"skip_visualization": skip_visualization, "save_in_e2e": save_in_e2e},
1240
+ )
1241
+
1242
+
1243
+ @ensure_telemetry_enabled
1244
+ def track_server_start(
1245
+ input_channels: List["InputChannel"],
1246
+ endpoints: Optional["AvailableEndpoints"],
1247
+ model_directory: Optional[Text],
1248
+ number_of_workers: int,
1249
+ is_api_enabled: bool,
1250
+ ) -> None:
1251
+ """Tracks when a user starts a rasa server.
1252
+
1253
+ Args:
1254
+ input_channels: Used input channels
1255
+ endpoints: Endpoint configuration for the server
1256
+ model_directory: directory of the running model
1257
+ number_of_workers: number of used Sanic workers
1258
+ is_api_enabled: whether the rasa API server is enabled
1259
+ """
1260
+ from rasa.core.utils import AvailableEndpoints
1261
+
1262
+ def project_fingerprint_from_model(
1263
+ _model_directory: Optional[Text],
1264
+ ) -> Optional[Text]:
1265
+ """Gets project fingerprint from an app's loaded model."""
1266
+ if not model_directory:
1267
+ return None
1268
+
1269
+ try:
1270
+ model_archive = model.get_local_model(_model_directory)
1271
+ metadata = LocalModelStorage.metadata_from_archive(model_archive)
1272
+
1273
+ return metadata.project_fingerprint
1274
+ except Exception:
1275
+ return None
1276
+
1277
+ if not endpoints:
1278
+ endpoints = AvailableEndpoints()
1279
+
1280
+ _track(
1281
+ TELEMETRY_SERVER_STARTED_EVENT,
1282
+ {
1283
+ "input_channels": [i.name() for i in input_channels],
1284
+ "api_enabled": is_api_enabled,
1285
+ "number_of_workers": number_of_workers,
1286
+ "endpoints_nlg": endpoints.nlg.type if endpoints.nlg else None,
1287
+ "endpoints_nlu": endpoints.nlu.type if endpoints.nlu else None,
1288
+ "endpoints_action_server": endpoints.action.type
1289
+ if endpoints.action
1290
+ else None,
1291
+ "endpoints_model_server": endpoints.model.type if endpoints.model else None,
1292
+ "endpoints_tracker_store": endpoints.tracker_store.type
1293
+ if endpoints.tracker_store
1294
+ else None,
1295
+ "endpoints_lock_store": endpoints.lock_store.type
1296
+ if endpoints.lock_store
1297
+ else None,
1298
+ "endpoints_event_broker": endpoints.event_broker.type
1299
+ if endpoints.event_broker
1300
+ else None,
1301
+ "project": project_fingerprint_from_model(model_directory),
1302
+ },
1303
+ )
1304
+
1305
+
1306
+ @ensure_telemetry_enabled
1307
+ def track_project_init(path: Text) -> None:
1308
+ """Track when a user creates a project using rasa init.
1309
+
1310
+ Args:
1311
+ path: Location of the project
1312
+ """
1313
+ _track(
1314
+ TELEMETRY_PROJECT_CREATED_EVENT, {"init_directory": _hash_directory_path(path)}
1315
+ )
1316
+
1317
+
1318
+ @ensure_telemetry_enabled
1319
+ def track_shell_started(model_type: Text) -> None:
1320
+ """Track when a user starts a bot using rasa shell.
1321
+
1322
+ Args:
1323
+ model_type: Type of the model, core / nlu or rasa.
1324
+ """
1325
+ _track(TELEMETRY_SHELL_STARTED_EVENT, {"type": model_type})
1326
+
1327
+
1328
+ @ensure_telemetry_enabled
1329
+ def track_visualization() -> None:
1330
+ """Track when a user runs the visualization."""
1331
+ _track(TELEMETRY_VISUALIZATION_STARTED_EVENT)
1332
+
1333
+
1334
+ @ensure_telemetry_enabled
1335
+ def track_core_model_test(num_story_steps: int, e2e: bool, agent: "Agent") -> None:
1336
+ """Track when a user tests a core model.
1337
+
1338
+ Args:
1339
+ num_story_steps: Number of test stories used for the comparison
1340
+ e2e: indicator if tests running in end to end mode
1341
+ agent: Agent of the model getting tested
1342
+ """
1343
+ if agent.processor is None:
1344
+ project_fingerprint = ""
1345
+ else:
1346
+ project_fingerprint = agent.processor.model_metadata.project_fingerprint
1347
+
1348
+ _track(
1349
+ TELEMETRY_TEST_CORE_EVENT,
1350
+ {
1351
+ "project": project_fingerprint,
1352
+ "end_to_end": e2e,
1353
+ "num_story_steps": num_story_steps,
1354
+ },
1355
+ )
1356
+
1357
+
1358
+ @ensure_telemetry_enabled
1359
+ def track_nlu_model_test(test_data: "TrainingData") -> None:
1360
+ """Track when a user tests an nlu model.
1361
+
1362
+ Args:
1363
+ test_data: Data used for testing
1364
+ """
1365
+ _track(
1366
+ TELEMETRY_TEST_NLU_EVENT,
1367
+ {
1368
+ "num_intent_examples": len(test_data.intent_examples),
1369
+ "num_entity_examples": len(test_data.entity_examples),
1370
+ "num_lookup_tables": len(test_data.lookup_tables),
1371
+ "num_synonyms": len(test_data.entity_synonyms),
1372
+ "num_regexes": len(test_data.regex_features),
1373
+ },
1374
+ )
1375
+
1376
+
1377
+ @ensure_telemetry_enabled
1378
+ def track_markers_extraction_initiated(
1379
+ strategy: Text, only_extract: bool, seed: bool, count: Optional[int]
1380
+ ) -> None:
1381
+ """Track when a user tries to extract success markers.
1382
+
1383
+ Args:
1384
+ strategy: The strategy the user is using for tracker selection
1385
+ only_extract: Indicates if the user is only extracting markers or also
1386
+ producing stats
1387
+ seed: Indicates if the user used a seed for this attempt
1388
+ count: (Optional) The number of trackers the user is trying to select.
1389
+ """
1390
+ _track(
1391
+ TELEMETRY_MARKERS_EXTRACTION_INITIATED_EVENT,
1392
+ {
1393
+ "strategy": strategy,
1394
+ "only_extract": only_extract,
1395
+ "seed": seed,
1396
+ "count": count,
1397
+ },
1398
+ )
1399
+
1400
+
1401
+ @ensure_telemetry_enabled
1402
+ def track_markers_extracted(trackers_count: int) -> None:
1403
+ """Track when markers have been extracted by a user.
1404
+
1405
+ Args:
1406
+ trackers_count: The actual number of trackers processed
1407
+ """
1408
+ _track(TELEMETRY_MARKERS_EXTRACTED_EVENT, {"trackers_count": trackers_count})
1409
+
1410
+
1411
+ @ensure_telemetry_enabled
1412
+ def track_markers_stats_computed(trackers_count: int) -> None:
1413
+ """Track when stats over markers have been computed by a user.
1414
+
1415
+ Args:
1416
+ trackers_count: The actual number of trackers processed
1417
+ """
1418
+ _track(TELEMETRY_MARKERS_STATS_COMPUTED_EVENT, {"trackers_count": trackers_count})
1419
+
1420
+
1421
+ @ensure_telemetry_enabled
1422
+ def track_markers_parsed_count(
1423
+ marker_count: int, max_depth: int, branching_factor: int
1424
+ ) -> None:
1425
+ """Track when markers have been successfully parsed from config.
1426
+
1427
+ Args:
1428
+ marker_count: The number of markers found in the config
1429
+ max_depth: The maximum depth of any marker in the config
1430
+ branching_factor: The maximum number of children of any marker in the config.
1431
+ """
1432
+ _track(
1433
+ TELEMETRY_MARKERS_PARSED_COUNT,
1434
+ {
1435
+ "marker_count": marker_count,
1436
+ "max_depth": max_depth,
1437
+ "branching_factor": branching_factor,
1438
+ },
1439
+ )
1440
+
1441
+
1442
+ @ensure_telemetry_enabled
1443
+ def track_e2e_test_run(
1444
+ input_test_cases: List["TestCase"],
1445
+ input_fixtures: List["Fixture"],
1446
+ input_metadata: List["Metadata"],
1447
+ ) -> None:
1448
+ """Track an end-to-end test run."""
1449
+ _track(
1450
+ TELEMETRY_E2E_TEST_RUN_STARTED_EVENT,
1451
+ {
1452
+ "number_of_test_cases": len(input_test_cases),
1453
+ "number_of_fixtures": len(input_fixtures),
1454
+ "uses_fixtures": len(input_fixtures) > 0,
1455
+ "uses_metadata": len(input_metadata) > 0,
1456
+ "number_of_metadata": len(input_metadata),
1457
+ },
1458
+ )
1459
+
1460
+
1461
+ @ensure_telemetry_enabled
1462
+ def track_response_rephrase(
1463
+ rephrase_all: bool,
1464
+ custom_prompt_template: Optional[str],
1465
+ llm_type: Optional[str],
1466
+ llm_model: Optional[str],
1467
+ ) -> None:
1468
+ """Track when a user rephrases a response."""
1469
+ _track(
1470
+ TELEMETRY_RESPONSE_REPHRASED_EVENT,
1471
+ {
1472
+ "rephrase_all": rephrase_all,
1473
+ "custom_prompt_template": custom_prompt_template,
1474
+ "llm_type": llm_type,
1475
+ "llm_model": llm_model,
1476
+ },
1477
+ )
1478
+
1479
+
1480
+ @ensure_telemetry_enabled
1481
+ def track_intentless_policy_train() -> None:
1482
+ """Track when a user trains a policy."""
1483
+ _track(TELEMETRY_INTENTLESS_POLICY_TRAINING_STARTED_EVENT)
1484
+
1485
+
1486
+ @ensure_telemetry_enabled
1487
+ def track_intentless_policy_train_completed(
1488
+ embeddings_type: Optional[str],
1489
+ embeddings_model: Optional[str],
1490
+ llm_type: Optional[str],
1491
+ llm_model: Optional[str],
1492
+ ) -> None:
1493
+ """Track when a user trains a policy."""
1494
+ _track(
1495
+ TELEMETRY_INTENTLESS_POLICY_TRAINING_COMPLETED_EVENT,
1496
+ {
1497
+ "embeddings_type": embeddings_type,
1498
+ "embeddings_model": embeddings_model,
1499
+ "llm_type": llm_type,
1500
+ "llm_model": llm_model,
1501
+ },
1502
+ )
1503
+
1504
+
1505
+ @ensure_telemetry_enabled
1506
+ def track_intentless_policy_predict(
1507
+ embeddings_type: Optional[str],
1508
+ embeddings_model: Optional[str],
1509
+ llm_type: Optional[str],
1510
+ llm_model: Optional[str],
1511
+ score: float,
1512
+ ) -> None:
1513
+ """Track when a user trains a policy."""
1514
+ _track(
1515
+ TELEMETRY_INTENTLESS_POLICY_PREDICT_EVENT,
1516
+ {
1517
+ "embeddings_type": embeddings_type,
1518
+ "embeddings_model": embeddings_model,
1519
+ "llm_type": llm_type,
1520
+ "llm_model": llm_model,
1521
+ "score": score,
1522
+ },
1523
+ )
1524
+
1525
+
1526
+ @ensure_telemetry_enabled
1527
+ def track_llm_intent_predict(
1528
+ embeddings_type: Optional[str],
1529
+ embeddings_model: Optional[str],
1530
+ llm_type: Optional[str],
1531
+ llm_model: Optional[str],
1532
+ ) -> None:
1533
+ """Track when a user predicts an intent using the llm intent classifier."""
1534
+ _track(
1535
+ TELEMETRY_LLM_INTENT_PREDICT_EVENT,
1536
+ {
1537
+ "embeddings_type": embeddings_type,
1538
+ "embeddings_model": embeddings_model,
1539
+ "llm_type": llm_type,
1540
+ "llm_model": llm_model,
1541
+ },
1542
+ )
1543
+
1544
+
1545
+ @ensure_telemetry_enabled
1546
+ def track_llm_intent_train_completed(
1547
+ embeddings_type: Optional[str],
1548
+ embeddings_model: Optional[str],
1549
+ llm_type: Optional[str],
1550
+ llm_model: Optional[str],
1551
+ fallback_intent: Optional[str],
1552
+ custom_prompt_template: Optional[str],
1553
+ number_of_examples: int,
1554
+ number_of_available_intents: int,
1555
+ ) -> None:
1556
+ """Track when a user trains the llm intent classifier."""
1557
+ _track(
1558
+ TELEMETRY_LLM_INTENT_TRAIN_COMPLETED_EVENT,
1559
+ {
1560
+ "embeddings_type": embeddings_type,
1561
+ "embeddings_model": embeddings_model,
1562
+ "llm_type": llm_type,
1563
+ "llm_model": llm_model,
1564
+ "fallback_intent": fallback_intent,
1565
+ "custom_prompt_template": custom_prompt_template,
1566
+ "number_of_examples": number_of_examples,
1567
+ "number_of_available_intents": number_of_available_intents,
1568
+ },
1569
+ )
1570
+
1571
+
1572
+ @ensure_telemetry_enabled
1573
+ def identify_endpoint_config_traits(
1574
+ endpoints_file: Optional[Text],
1575
+ context: Optional[Dict[Text, Any]] = None,
1576
+ ) -> None:
1577
+ """Collect traits if enabled.
1578
+
1579
+ Otherwise, sets traits to None.
1580
+ """
1581
+ traits: Dict[str, Any] = {}
1582
+
1583
+ traits = append_tracing_trait(traits, endpoints_file)
1584
+ traits = append_metrics_trait(traits, endpoints_file)
1585
+ traits = append_anonymization_trait(traits, endpoints_file)
1586
+
1587
+ _identify(traits, context)
1588
+
1589
+
1590
+ def append_tracing_trait(
1591
+ traits: Dict[str, Any], endpoints_file: Optional[str]
1592
+ ) -> Dict[str, Any]:
1593
+ """Append the tracing trait to the traits dictionary."""
1594
+ import rasa.utils.endpoints
1595
+ from rasa.tracing.constants import ENDPOINTS_TRACING_KEY
1596
+
1597
+ tracing_config = rasa.utils.endpoints.read_endpoint_config(
1598
+ endpoints_file, ENDPOINTS_TRACING_KEY
1599
+ )
1600
+ traits[TRACING_BACKEND] = (
1601
+ tracing_config.type if tracing_config is not None else None
1602
+ )
1603
+
1604
+ return traits
1605
+
1606
+
1607
+ def append_metrics_trait(
1608
+ traits: Dict[str, Any], endpoints_file: Optional[str]
1609
+ ) -> Dict[str, Any]:
1610
+ """Append the metrics trait to the traits dictionary."""
1611
+ import rasa.utils.endpoints
1612
+ from rasa.tracing.constants import ENDPOINTS_METRICS_KEY
1613
+
1614
+ metrics_config = rasa.utils.endpoints.read_endpoint_config(
1615
+ endpoints_file, ENDPOINTS_METRICS_KEY
1616
+ )
1617
+ traits[METRICS_BACKEND] = (
1618
+ metrics_config.type if metrics_config is not None else None
1619
+ )
1620
+
1621
+ return traits
1622
+
1623
+
1624
+ def append_anonymization_trait(
1625
+ traits: Dict[str, Any], endpoints_file: Optional[str]
1626
+ ) -> Dict[str, Any]:
1627
+ """Append the anonymization trait to the traits dictionary."""
1628
+ from rasa.anonymization.anonymisation_rule_yaml_reader import (
1629
+ KEY_ANONYMIZATION_RULES,
1630
+ )
1631
+
1632
+ anonymization_config = rasa.anonymization.utils.read_endpoint_config(
1633
+ endpoints_file, KEY_ANONYMIZATION_RULES
1634
+ )
1635
+
1636
+ traits[KEY_ANONYMIZATION_RULES] = (
1637
+ rasa.anonymization.utils.extract_anonymization_traits(
1638
+ anonymization_config, KEY_ANONYMIZATION_RULES
1639
+ )
1640
+ )
1641
+
1642
+ return traits
1643
+
1644
+
1645
+ @ensure_telemetry_enabled
1646
+ def track_enterprise_search_policy_train_started() -> None:
1647
+ """Track when a user starts training Enterprise Search policy."""
1648
+ _track(TELEMETRY_ENTERPRISE_SEARCH_POLICY_TRAINING_STARTED_EVENT)
1649
+
1650
+
1651
+ @ensure_telemetry_enabled
1652
+ def track_enterprise_search_policy_train_completed(
1653
+ vector_store_type: Optional[str],
1654
+ embeddings_type: Optional[str],
1655
+ embeddings_model: Optional[str],
1656
+ llm_type: Optional[str],
1657
+ llm_model: Optional[str],
1658
+ citation_enabled: Optional[bool],
1659
+ ) -> None:
1660
+ """Track when a user completes training Enterprise Search policy."""
1661
+ _track(
1662
+ TELEMETRY_ENTERPRISE_SEARCH_POLICY_TRAINING_COMPLETED_EVENT,
1663
+ {
1664
+ "vector_store_type": vector_store_type,
1665
+ "embeddings_type": embeddings_type,
1666
+ "embeddings_model": embeddings_model,
1667
+ "llm_type": llm_type,
1668
+ "llm_model": llm_model,
1669
+ "citation_enabled": citation_enabled,
1670
+ },
1671
+ )
1672
+
1673
+
1674
+ @ensure_telemetry_enabled
1675
+ def track_enterprise_search_policy_predict(
1676
+ vector_store_type: Optional[str],
1677
+ embeddings_type: Optional[str],
1678
+ embeddings_model: Optional[str],
1679
+ llm_type: Optional[str],
1680
+ llm_model: Optional[str],
1681
+ citation_enabled: Optional[bool],
1682
+ ) -> None:
1683
+ """Track when a user predicts the next action using Enterprise Search policy."""
1684
+ _track(
1685
+ TELEMETRY_ENTERPRISE_SEARCH_POLICY_PREDICT_EVENT,
1686
+ {
1687
+ "vector_store_type": vector_store_type,
1688
+ "embeddings_type": embeddings_type,
1689
+ "embeddings_model": embeddings_model,
1690
+ "llm_type": llm_type,
1691
+ "llm_model": llm_model,
1692
+ "citation_enabled": citation_enabled,
1693
+ },
1694
+ )
1695
+
1696
+
1697
+ @ensure_telemetry_enabled
1698
+ def track_conversation_count_hard_limit(
1699
+ conversation_count: int, tracked_month: datetime
1700
+ ) -> None:
1701
+ """Track when the number of conversations reaches the hard limit."""
1702
+ _track(
1703
+ TELEMETRY_CONVERSATION_HARD_LIMIT_REACHED,
1704
+ {
1705
+ "conversation_count": conversation_count,
1706
+ "year": tracked_month.year,
1707
+ "month": tracked_month.month,
1708
+ },
1709
+ )
1710
+
1711
+
1712
+ @ensure_telemetry_enabled
1713
+ def track_conversation_count_soft_limit(
1714
+ conversation_count: int, tracked_month: datetime
1715
+ ) -> None:
1716
+ """Track when the number of conversations reaches the soft limit."""
1717
+ _track(
1718
+ TELEMETRY_CONVERSATION_SOFT_LIMIT_REACHED,
1719
+ {
1720
+ "conversation_count": conversation_count,
1721
+ "year": tracked_month.year,
1722
+ "month": tracked_month.month,
1723
+ },
1724
+ )
1725
+
1726
+
1727
+ @ensure_telemetry_enabled
1728
+ def track_conversation_count(conversation_count: int, tracked_month: datetime) -> None:
1729
+ """Track the number of conversations."""
1730
+ _track(
1731
+ TELEMETRY_CONVERSATION_COUNT,
1732
+ {
1733
+ "conversation_count": conversation_count,
1734
+ "year": tracked_month.year,
1735
+ "month": tracked_month.month,
1736
+ },
1737
+ )