mito-ai 0.1.50__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.
Files changed (205) hide show
  1. mito_ai/__init__.py +114 -0
  2. mito_ai/_version.py +4 -0
  3. mito_ai/anthropic_client.py +334 -0
  4. mito_ai/app_deploy/__init__.py +6 -0
  5. mito_ai/app_deploy/app_deploy_utils.py +44 -0
  6. mito_ai/app_deploy/handlers.py +345 -0
  7. mito_ai/app_deploy/models.py +98 -0
  8. mito_ai/app_manager/__init__.py +4 -0
  9. mito_ai/app_manager/handlers.py +167 -0
  10. mito_ai/app_manager/models.py +71 -0
  11. mito_ai/app_manager/utils.py +24 -0
  12. mito_ai/auth/README.md +18 -0
  13. mito_ai/auth/__init__.py +6 -0
  14. mito_ai/auth/handlers.py +96 -0
  15. mito_ai/auth/urls.py +13 -0
  16. mito_ai/chat_history/handlers.py +63 -0
  17. mito_ai/chat_history/urls.py +32 -0
  18. mito_ai/completions/completion_handlers/__init__.py +3 -0
  19. mito_ai/completions/completion_handlers/agent_auto_error_fixup_handler.py +59 -0
  20. mito_ai/completions/completion_handlers/agent_execution_handler.py +66 -0
  21. mito_ai/completions/completion_handlers/chat_completion_handler.py +141 -0
  22. mito_ai/completions/completion_handlers/code_explain_handler.py +113 -0
  23. mito_ai/completions/completion_handlers/completion_handler.py +42 -0
  24. mito_ai/completions/completion_handlers/inline_completer_handler.py +48 -0
  25. mito_ai/completions/completion_handlers/smart_debug_handler.py +160 -0
  26. mito_ai/completions/completion_handlers/utils.py +147 -0
  27. mito_ai/completions/handlers.py +415 -0
  28. mito_ai/completions/message_history.py +401 -0
  29. mito_ai/completions/models.py +404 -0
  30. mito_ai/completions/prompt_builders/__init__.py +3 -0
  31. mito_ai/completions/prompt_builders/agent_execution_prompt.py +57 -0
  32. mito_ai/completions/prompt_builders/agent_smart_debug_prompt.py +160 -0
  33. mito_ai/completions/prompt_builders/agent_system_message.py +472 -0
  34. mito_ai/completions/prompt_builders/chat_name_prompt.py +15 -0
  35. mito_ai/completions/prompt_builders/chat_prompt.py +116 -0
  36. mito_ai/completions/prompt_builders/chat_system_message.py +92 -0
  37. mito_ai/completions/prompt_builders/explain_code_prompt.py +32 -0
  38. mito_ai/completions/prompt_builders/inline_completer_prompt.py +197 -0
  39. mito_ai/completions/prompt_builders/prompt_constants.py +170 -0
  40. mito_ai/completions/prompt_builders/smart_debug_prompt.py +199 -0
  41. mito_ai/completions/prompt_builders/utils.py +84 -0
  42. mito_ai/completions/providers.py +284 -0
  43. mito_ai/constants.py +63 -0
  44. mito_ai/db/__init__.py +3 -0
  45. mito_ai/db/crawlers/__init__.py +6 -0
  46. mito_ai/db/crawlers/base_crawler.py +61 -0
  47. mito_ai/db/crawlers/constants.py +43 -0
  48. mito_ai/db/crawlers/snowflake.py +71 -0
  49. mito_ai/db/handlers.py +168 -0
  50. mito_ai/db/models.py +31 -0
  51. mito_ai/db/urls.py +34 -0
  52. mito_ai/db/utils.py +185 -0
  53. mito_ai/docker/mssql/compose.yml +37 -0
  54. mito_ai/docker/mssql/init/setup.sql +21 -0
  55. mito_ai/docker/mysql/compose.yml +18 -0
  56. mito_ai/docker/mysql/init/setup.sql +13 -0
  57. mito_ai/docker/oracle/compose.yml +17 -0
  58. mito_ai/docker/oracle/init/setup.sql +20 -0
  59. mito_ai/docker/postgres/compose.yml +17 -0
  60. mito_ai/docker/postgres/init/setup.sql +13 -0
  61. mito_ai/enterprise/__init__.py +3 -0
  62. mito_ai/enterprise/utils.py +15 -0
  63. mito_ai/file_uploads/__init__.py +3 -0
  64. mito_ai/file_uploads/handlers.py +248 -0
  65. mito_ai/file_uploads/urls.py +21 -0
  66. mito_ai/gemini_client.py +232 -0
  67. mito_ai/log/handlers.py +38 -0
  68. mito_ai/log/urls.py +21 -0
  69. mito_ai/logger.py +37 -0
  70. mito_ai/openai_client.py +382 -0
  71. mito_ai/path_utils.py +70 -0
  72. mito_ai/rules/handlers.py +44 -0
  73. mito_ai/rules/urls.py +22 -0
  74. mito_ai/rules/utils.py +56 -0
  75. mito_ai/settings/handlers.py +41 -0
  76. mito_ai/settings/urls.py +20 -0
  77. mito_ai/settings/utils.py +42 -0
  78. mito_ai/streamlit_conversion/agent_utils.py +37 -0
  79. mito_ai/streamlit_conversion/prompts/prompt_constants.py +172 -0
  80. mito_ai/streamlit_conversion/prompts/prompt_utils.py +10 -0
  81. mito_ai/streamlit_conversion/prompts/streamlit_app_creation_prompt.py +46 -0
  82. mito_ai/streamlit_conversion/prompts/streamlit_error_correction_prompt.py +28 -0
  83. mito_ai/streamlit_conversion/prompts/streamlit_finish_todo_prompt.py +45 -0
  84. mito_ai/streamlit_conversion/prompts/streamlit_system_prompt.py +56 -0
  85. mito_ai/streamlit_conversion/prompts/update_existing_app_prompt.py +50 -0
  86. mito_ai/streamlit_conversion/search_replace_utils.py +94 -0
  87. mito_ai/streamlit_conversion/streamlit_agent_handler.py +144 -0
  88. mito_ai/streamlit_conversion/streamlit_utils.py +85 -0
  89. mito_ai/streamlit_conversion/validate_streamlit_app.py +105 -0
  90. mito_ai/streamlit_preview/__init__.py +6 -0
  91. mito_ai/streamlit_preview/handlers.py +111 -0
  92. mito_ai/streamlit_preview/manager.py +152 -0
  93. mito_ai/streamlit_preview/urls.py +22 -0
  94. mito_ai/streamlit_preview/utils.py +29 -0
  95. mito_ai/tests/__init__.py +3 -0
  96. mito_ai/tests/chat_history/test_chat_history.py +211 -0
  97. mito_ai/tests/completions/completion_handlers_utils_test.py +190 -0
  98. mito_ai/tests/conftest.py +53 -0
  99. mito_ai/tests/create_agent_system_message_prompt_test.py +22 -0
  100. mito_ai/tests/data/prompt_lg.py +69 -0
  101. mito_ai/tests/data/prompt_sm.py +6 -0
  102. mito_ai/tests/data/prompt_xl.py +13 -0
  103. mito_ai/tests/data/stock_data.sqlite3 +0 -0
  104. mito_ai/tests/db/conftest.py +39 -0
  105. mito_ai/tests/db/connections_test.py +102 -0
  106. mito_ai/tests/db/mssql_test.py +29 -0
  107. mito_ai/tests/db/mysql_test.py +29 -0
  108. mito_ai/tests/db/oracle_test.py +29 -0
  109. mito_ai/tests/db/postgres_test.py +29 -0
  110. mito_ai/tests/db/schema_test.py +93 -0
  111. mito_ai/tests/db/sqlite_test.py +31 -0
  112. mito_ai/tests/db/test_db_constants.py +61 -0
  113. mito_ai/tests/deploy_app/test_app_deploy_utils.py +89 -0
  114. mito_ai/tests/file_uploads/__init__.py +2 -0
  115. mito_ai/tests/file_uploads/test_handlers.py +282 -0
  116. mito_ai/tests/message_history/test_generate_short_chat_name.py +120 -0
  117. mito_ai/tests/message_history/test_message_history_utils.py +469 -0
  118. mito_ai/tests/open_ai_utils_test.py +152 -0
  119. mito_ai/tests/performance_test.py +329 -0
  120. mito_ai/tests/providers/test_anthropic_client.py +447 -0
  121. mito_ai/tests/providers/test_azure.py +631 -0
  122. mito_ai/tests/providers/test_capabilities.py +120 -0
  123. mito_ai/tests/providers/test_gemini_client.py +195 -0
  124. mito_ai/tests/providers/test_mito_server_utils.py +448 -0
  125. mito_ai/tests/providers/test_model_resolution.py +130 -0
  126. mito_ai/tests/providers/test_openai_client.py +57 -0
  127. mito_ai/tests/providers/test_provider_completion_exception.py +66 -0
  128. mito_ai/tests/providers/test_provider_limits.py +42 -0
  129. mito_ai/tests/providers/test_providers.py +382 -0
  130. mito_ai/tests/providers/test_retry_logic.py +389 -0
  131. mito_ai/tests/providers/test_stream_mito_server_utils.py +140 -0
  132. mito_ai/tests/providers/utils.py +85 -0
  133. mito_ai/tests/rules/conftest.py +26 -0
  134. mito_ai/tests/rules/rules_test.py +117 -0
  135. mito_ai/tests/server_limits_test.py +406 -0
  136. mito_ai/tests/settings/conftest.py +26 -0
  137. mito_ai/tests/settings/settings_test.py +70 -0
  138. mito_ai/tests/settings/test_settings_constants.py +9 -0
  139. mito_ai/tests/streamlit_conversion/__init__.py +3 -0
  140. mito_ai/tests/streamlit_conversion/test_apply_search_replace.py +240 -0
  141. mito_ai/tests/streamlit_conversion/test_streamlit_agent_handler.py +246 -0
  142. mito_ai/tests/streamlit_conversion/test_streamlit_utils.py +193 -0
  143. mito_ai/tests/streamlit_conversion/test_validate_streamlit_app.py +112 -0
  144. mito_ai/tests/streamlit_preview/test_streamlit_preview_handler.py +118 -0
  145. mito_ai/tests/streamlit_preview/test_streamlit_preview_manager.py +292 -0
  146. mito_ai/tests/test_constants.py +47 -0
  147. mito_ai/tests/test_telemetry.py +12 -0
  148. mito_ai/tests/user/__init__.py +2 -0
  149. mito_ai/tests/user/test_user.py +120 -0
  150. mito_ai/tests/utils/__init__.py +3 -0
  151. mito_ai/tests/utils/test_anthropic_utils.py +162 -0
  152. mito_ai/tests/utils/test_gemini_utils.py +98 -0
  153. mito_ai/tests/version_check_test.py +169 -0
  154. mito_ai/user/handlers.py +45 -0
  155. mito_ai/user/urls.py +21 -0
  156. mito_ai/utils/__init__.py +3 -0
  157. mito_ai/utils/anthropic_utils.py +168 -0
  158. mito_ai/utils/create.py +94 -0
  159. mito_ai/utils/db.py +74 -0
  160. mito_ai/utils/error_classes.py +42 -0
  161. mito_ai/utils/gemini_utils.py +133 -0
  162. mito_ai/utils/message_history_utils.py +87 -0
  163. mito_ai/utils/mito_server_utils.py +242 -0
  164. mito_ai/utils/open_ai_utils.py +200 -0
  165. mito_ai/utils/provider_utils.py +49 -0
  166. mito_ai/utils/schema.py +86 -0
  167. mito_ai/utils/server_limits.py +152 -0
  168. mito_ai/utils/telemetry_utils.py +480 -0
  169. mito_ai/utils/utils.py +89 -0
  170. mito_ai/utils/version_utils.py +94 -0
  171. mito_ai/utils/websocket_base.py +88 -0
  172. mito_ai/version_check.py +60 -0
  173. mito_ai-0.1.50.data/data/etc/jupyter/jupyter_server_config.d/mito_ai.json +7 -0
  174. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/build_log.json +728 -0
  175. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/package.json +243 -0
  176. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/schemas/mito_ai/package.json.orig +238 -0
  177. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/schemas/mito_ai/toolbar-buttons.json +37 -0
  178. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/lib_index_js.8f1845da6bf2b128c049.js +21602 -0
  179. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/lib_index_js.8f1845da6bf2b128c049.js.map +1 -0
  180. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/node_modules_process_browser_js.4b128e94d31a81ebd209.js +198 -0
  181. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/node_modules_process_browser_js.4b128e94d31a81ebd209.js.map +1 -0
  182. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/remoteEntry.78d3ccb73e7ca1da3aae.js +619 -0
  183. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/remoteEntry.78d3ccb73e7ca1da3aae.js.map +1 -0
  184. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/style.js +4 -0
  185. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/style_index_js.5876024bb17dbd6a3ee6.js +712 -0
  186. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/style_index_js.5876024bb17dbd6a3ee6.js.map +1 -0
  187. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_aws-amplify_auth_dist_esm_providers_cognito_apis_signOut_mjs-node_module-75790d.688c25857e7b81b1740f.js +533 -0
  188. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_aws-amplify_auth_dist_esm_providers_cognito_apis_signOut_mjs-node_module-75790d.688c25857e7b81b1740f.js.map +1 -0
  189. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_aws-amplify_auth_dist_esm_providers_cognito_tokenProvider_tokenProvider_-72f1c8.a917210f057fcfe224ad.js +6941 -0
  190. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_aws-amplify_auth_dist_esm_providers_cognito_tokenProvider_tokenProvider_-72f1c8.a917210f057fcfe224ad.js.map +1 -0
  191. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_aws-amplify_dist_esm_index_mjs.6bac1a8c4cc93f15f6b7.js +1021 -0
  192. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_aws-amplify_dist_esm_index_mjs.6bac1a8c4cc93f15f6b7.js.map +1 -0
  193. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_aws-amplify_ui-react_dist_esm_index_mjs.4fcecd65bef9e9847609.js +59698 -0
  194. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_aws-amplify_ui-react_dist_esm_index_mjs.4fcecd65bef9e9847609.js.map +1 -0
  195. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_react-dom_client_js-node_modules_aws-amplify_ui-react_dist_styles_css.b43d4249e4d3dac9ad7b.js +7440 -0
  196. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_react-dom_client_js-node_modules_aws-amplify_ui-react_dist_styles_css.b43d4249e4d3dac9ad7b.js.map +1 -0
  197. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_semver_index_js.3f6754ac5116d47de76b.js +2792 -0
  198. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_semver_index_js.3f6754ac5116d47de76b.js.map +1 -0
  199. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_vscode-diff_dist_index_js.ea55f1f9346638aafbcf.js +4859 -0
  200. mito_ai-0.1.50.data/data/share/jupyter/labextensions/mito_ai/static/vendors-node_modules_vscode-diff_dist_index_js.ea55f1f9346638aafbcf.js.map +1 -0
  201. mito_ai-0.1.50.dist-info/METADATA +221 -0
  202. mito_ai-0.1.50.dist-info/RECORD +205 -0
  203. mito_ai-0.1.50.dist-info/WHEEL +4 -0
  204. mito_ai-0.1.50.dist-info/entry_points.txt +2 -0
  205. mito_ai-0.1.50.dist-info/licenses/LICENSE +3 -0
mito_ai/__init__.py ADDED
@@ -0,0 +1,114 @@
1
+ # Copyright (c) Saga Inc.
2
+ # Distributed under the terms of the GNU Affero General Public License v3.0 License.
3
+
4
+ from typing import List, Dict
5
+ from jupyter_server.utils import url_path_join
6
+ from mito_ai.completions.handlers import CompletionHandler
7
+ from mito_ai.completions.providers import OpenAIProvider
8
+ from mito_ai.completions.message_history import GlobalMessageHistory
9
+ from mito_ai.app_deploy.handlers import AppDeployHandler
10
+ from mito_ai.streamlit_preview.handlers import StreamlitPreviewHandler
11
+ from mito_ai.log.urls import get_log_urls
12
+ from mito_ai.version_check import VersionCheckHandler
13
+ from mito_ai.db.urls import get_db_urls
14
+ from mito_ai.settings.urls import get_settings_urls
15
+ from mito_ai.rules.urls import get_rules_urls
16
+ from mito_ai.auth.urls import get_auth_urls
17
+ from mito_ai.streamlit_preview.urls import get_streamlit_preview_urls
18
+ from mito_ai.app_manager.handlers import AppManagerHandler
19
+ from mito_ai.file_uploads.urls import get_file_uploads_urls
20
+ from mito_ai.user.urls import get_user_urls
21
+ from mito_ai.chat_history.urls import get_chat_history_urls
22
+
23
+ # Force Matplotlib to use the Jupyter inline backend.
24
+ # Background: importing Streamlit sets os.environ["MPLBACKEND"] = "Agg" very early.
25
+ # In a Jupyter kernel, that selects a non‑interactive canvas and can trigger:
26
+ # "UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown"
27
+ # which prevents figures from rendering in notebook outputs.
28
+ # We preempt this by selecting the canonical Jupyter inline backend BEFORE any
29
+ # Matplotlib import, so figures render inline reliably. This must run very early.
30
+ # See: https://github.com/streamlit/streamlit/issues/9640
31
+
32
+ import os
33
+ os.environ["MPLBACKEND"] = "module://matplotlib_inline.backend_inline"
34
+
35
+ try:
36
+ from _version import __version__
37
+ except ImportError:
38
+ # Fallback when using the package in dev mode without installing in editable mode with pip. It is highly recommended to install
39
+ # the package from a stable release or in editable mode: https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs
40
+ import warnings
41
+
42
+ warnings.warn("Importing 'mito_ai' outside a proper installation.")
43
+ __version__ = "dev"
44
+
45
+ def _jupyter_labextension_paths() -> List[Dict[str, str]]:
46
+ return [{"src": "labextension", "dest": "mito_ai"}]
47
+
48
+
49
+ def _jupyter_server_extension_points() -> List[Dict[str, str]]:
50
+ """
51
+ Returns a list of dictionaries with metadata describing
52
+ where to find the `_load_jupyter_server_extension` function.
53
+ """
54
+ return [{"module": "mito_ai"}]
55
+
56
+
57
+ # Jupyter Server is the backend used by JupyterLab. A sever extension lets
58
+ # us add new API's to the backend, so we can do some processing that we don't
59
+ # want to exist in the users's javascript.
60
+ # For a further explanation of the Jupyter architecture watch the first 35 minutes
61
+ # of this video: https://www.youtube.com/watch?v=9_-siU-_XoI
62
+ def _load_jupyter_server_extension(server_app) -> None: # type: ignore
63
+ host_pattern = ".*$"
64
+ web_app = server_app.web_app
65
+ base_url = web_app.settings["base_url"]
66
+
67
+ open_ai_provider = OpenAIProvider(config=server_app.config)
68
+
69
+ # Create a single GlobalMessageHistory instance for the entire server
70
+ # This ensures thread-safe access to the .mito/ai-chats directory
71
+ global_message_history = GlobalMessageHistory()
72
+
73
+ # WebSocket handlers
74
+ handlers = [
75
+ (
76
+ url_path_join(base_url, "mito-ai", "completions"),
77
+ CompletionHandler,
78
+ {"llm": open_ai_provider, "message_history": global_message_history},
79
+ ),
80
+ (
81
+ url_path_join(base_url, "mito-ai", "app-deploy"),
82
+ AppDeployHandler,
83
+ {}
84
+ ),
85
+ (
86
+ url_path_join(base_url, "mito-ai", "streamlit-preview"),
87
+ StreamlitPreviewHandler,
88
+ {}
89
+ ),
90
+ (
91
+ url_path_join(base_url, "mito-ai", "version-check"),
92
+ VersionCheckHandler,
93
+ {},
94
+ ),
95
+ (
96
+ url_path_join(base_url, "mito-ai", "app-manager"),
97
+ AppManagerHandler,
98
+ {}
99
+ )
100
+ ]
101
+
102
+ # REST API endpoints
103
+ handlers.extend(get_db_urls(base_url)) # type: ignore
104
+ handlers.extend(get_settings_urls(base_url)) # type: ignore
105
+ handlers.extend(get_rules_urls(base_url)) # type: ignore
106
+ handlers.extend(get_log_urls(base_url, open_ai_provider.key_type)) # type: ignore
107
+ handlers.extend(get_auth_urls(base_url)) # type: ignore
108
+ handlers.extend(get_streamlit_preview_urls(base_url)) # type: ignore
109
+ handlers.extend(get_file_uploads_urls(base_url)) # type: ignore
110
+ handlers.extend(get_user_urls(base_url)) # type: ignore
111
+ handlers.extend(get_chat_history_urls(base_url, global_message_history)) # type: ignore
112
+
113
+ web_app.add_handlers(host_pattern, handlers)
114
+ server_app.log.info("Loaded the mito_ai server extension")
mito_ai/_version.py ADDED
@@ -0,0 +1,4 @@
1
+ # This file is auto-generated by Hatchling. As such, do not:
2
+ # - modify
3
+ # - track in version control e.g. be sure to add to .gitignore
4
+ __version__ = VERSION = '0.1.50'
@@ -0,0 +1,334 @@
1
+ # Copyright (c) Saga Inc.
2
+ # Distributed under the terms of the GNU Affero General Public License v3.0 License.
3
+
4
+ import json
5
+ import anthropic
6
+ from typing import Dict, Any, Optional, Tuple, Union, Callable, List, cast
7
+
8
+ from anthropic.types import Message, MessageParam, TextBlockParam
9
+ from mito_ai.completions.models import ResponseFormatInfo, CompletionReply, CompletionStreamChunk, CompletionItem, MessageType
10
+ from mito_ai.constants import MESSAGE_HISTORY_TRIM_THRESHOLD
11
+ from openai.types.chat import ChatCompletionMessageParam
12
+ from mito_ai.utils.anthropic_utils import get_anthropic_completion_from_mito_server, stream_anthropic_completion_from_mito_server, get_anthropic_completion_function_params
13
+
14
+ # Max tokens is a required parameter for the Anthropic API.
15
+ # We set it to a high number so that we can edit large code cells
16
+ # 8192 is the maximum allowed number of output tokens for claude-3-5-haiku-20241022
17
+ MAX_TOKENS = 8_000
18
+
19
+ def extract_and_parse_anthropic_json_response(response: Message) -> Union[object, Any]:
20
+ """
21
+ Extracts and parses the JSON response from the Claude API.
22
+ """
23
+ try:
24
+ # Check for tool use in the response
25
+ for content_block in response.content:
26
+ if content_block.type == "tool_use" and content_block.name == "agent_response":
27
+ result = content_block.input
28
+ return result
29
+
30
+ # If no tool use was found, try to parse the text response
31
+ text_response = None
32
+ for content_block in response.content:
33
+ if content_block.type == "text":
34
+ text_response = content_block.text
35
+ break
36
+
37
+ if text_response:
38
+ # Try to extract JSON from the text response
39
+ import re
40
+ json_pattern = r'(\{.*\})'
41
+ match = re.search(json_pattern, text_response, re.DOTALL)
42
+ if match:
43
+ try:
44
+ json_response = json.loads(match.group(0))
45
+ return json_response
46
+ except json.JSONDecodeError:
47
+ pass
48
+
49
+ raise Exception("No valid AgentResponse format found in the response")
50
+ except Exception as e:
51
+ raise Exception(f"Failed to parse response: {e}")
52
+
53
+
54
+ def get_anthropic_system_prompt_and_messages(messages: List[ChatCompletionMessageParam]) -> Tuple[
55
+ Union[str, anthropic.Omit], List[MessageParam]]:
56
+ """
57
+ Convert a list of OpenAI messages to a list of Anthropic messages.
58
+ """
59
+
60
+ system_prompt: Union[str, anthropic.Omit] = anthropic.Omit()
61
+ anthropic_messages: List[MessageParam] = []
62
+
63
+ for message in messages:
64
+ if 'content' not in message:
65
+ continue
66
+
67
+ # We assume that the conversation only has one system message.
68
+ # Or if there are multiple, we take the last one.
69
+ if message['role'] == 'system':
70
+ system_prompt = str(message['content'])
71
+
72
+ # Construct the messages for the user and assistant in Anthropic format.
73
+ if message['role'] == 'user':
74
+ content = message['content']
75
+
76
+ # Handle mixed content (text + images)
77
+ if isinstance(content, list):
78
+ anthropic_content = []
79
+
80
+ for item in content:
81
+ if isinstance(item, dict):
82
+ item_dict = cast(Dict[str, Any], item)
83
+ if item_dict.get('type') == 'text':
84
+ # Add text content
85
+ text_content = item_dict.get('text', '')
86
+ anthropic_content.append({
87
+ "type": "text",
88
+ "text": text_content
89
+ })
90
+ elif item_dict.get('type') == 'image_url':
91
+ # Convert OpenAI image format to Anthropic format
92
+ image_url_obj = item_dict.get('image_url', {})
93
+ if isinstance(image_url_obj, dict):
94
+ image_url = image_url_obj.get('url', '')
95
+ else:
96
+ image_url = str(image_url_obj)
97
+
98
+ # Extract media type and base64 data
99
+ if image_url.startswith('data:'):
100
+ # Format: data:image/png;base64,<base64_data>
101
+ header, base64_data = image_url.split(',', 1)
102
+ media_type = header.split(';')[0].split(':')[1] # Extract image/png or image/jpeg
103
+ else:
104
+ # If it's not a data URL, assume it's direct base64 and default to image/png
105
+ media_type = "image/png"
106
+ base64_data = image_url
107
+
108
+ anthropic_content.append({
109
+ "type": "image",
110
+ "source": {
111
+ "type": "base64",
112
+ "media_type": media_type,
113
+ "data": base64_data
114
+ }
115
+ })
116
+
117
+ anthropic_messages.append(MessageParam(role='user', content=cast(Any, anthropic_content)))
118
+ else:
119
+ # Handle simple text content
120
+ anthropic_messages.append(MessageParam(role='user', content=str(content)))
121
+
122
+ elif message['role'] == 'assistant':
123
+ anthropic_messages.append(MessageParam(role='assistant', content=str(message['content'])))
124
+
125
+ return system_prompt, anthropic_messages
126
+
127
+
128
+ def add_cache_control_to_message(message: MessageParam) -> MessageParam:
129
+ """
130
+ Adds cache_control to a message's content.
131
+ Handles both string content and list of content blocks.
132
+ """
133
+ content = message.get("content")
134
+
135
+ if isinstance(content, str):
136
+ # Simple string content - convert to list format with cache_control
137
+ return {
138
+ "role": message["role"],
139
+ "content": [
140
+ {
141
+ "type": "text",
142
+ "text": content,
143
+ "cache_control": {"type": "ephemeral"}
144
+ }
145
+ ]
146
+ }
147
+
148
+ elif isinstance(content, list) and len(content) > 0:
149
+ # List of content blocks - add cache_control to last block
150
+ content_blocks = content.copy()
151
+ last_block = content_blocks[-1].copy()
152
+ last_block["cache_control"] = {"type": "ephemeral"}
153
+ content_blocks[-1] = last_block
154
+
155
+ return {
156
+ "role": message["role"],
157
+ "content": content_blocks
158
+ }
159
+
160
+ else:
161
+ # Edge case: empty or malformed content
162
+ return message
163
+
164
+
165
+ def get_anthropic_system_prompt_and_messages_with_caching(messages: List[ChatCompletionMessageParam]) -> Tuple[
166
+ Union[str, List[TextBlockParam], anthropic.Omit], List[MessageParam]]:
167
+ """
168
+ Convert a list of OpenAI messages to a list of Anthropic messages with caching applied.
169
+
170
+ Caching Strategy:
171
+ 1. System prompt (static) → Always cached
172
+ 2. Stable conversation history → Cache at keep_recent boundary
173
+ 3. Recent messages → Never cached (always fresh)
174
+
175
+ The keep_recent parameter determines which messages are stable and won't be trimmed.
176
+ We cache at the keep_recent boundary because those messages are guaranteed to be stable.
177
+ """
178
+
179
+ # Get the base system prompt and messages
180
+ system_prompt, anthropic_messages = get_anthropic_system_prompt_and_messages(messages)
181
+
182
+ # 1. Cache the system prompt always
183
+ # If the system prompt is something like anthropic.Omit, we don't need to cache it
184
+ cached_system_prompt: Union[str, List[TextBlockParam], anthropic.Omit] = system_prompt
185
+ if isinstance(system_prompt, str):
186
+ cached_system_prompt = [{
187
+ "type": "text",
188
+ "text": system_prompt,
189
+ "cache_control": {"type": "ephemeral"}
190
+ }]
191
+
192
+ # 2. Cache conversation history at the boundary where the messages are stable.
193
+ # Messages are stable after they are more than MESSAGE_HISTORY_TRIM_THRESHOLD old.
194
+ # At this point, the messages are not edited anymore, so they will not invalidate the cache.
195
+ # If we included the messages before the boundary in the cache, then every time we send a new
196
+ # message, we would invalidate the cache and we would never get a cache hit except for the system prompt.
197
+ messages_with_cache = []
198
+
199
+ if len(anthropic_messages) > 0:
200
+ cache_boundary = len(anthropic_messages) - MESSAGE_HISTORY_TRIM_THRESHOLD - 1
201
+
202
+ # Add all messages, but only add cache_control to the message at the boundary
203
+ for i, msg in enumerate(anthropic_messages):
204
+ if i == cache_boundary:
205
+ messages_with_cache.append(add_cache_control_to_message(msg))
206
+ else:
207
+ messages_with_cache.append(msg)
208
+
209
+ return cached_system_prompt, messages_with_cache
210
+
211
+
212
+ class AnthropicClient:
213
+ """
214
+ A client for interacting with the Anthropic API or the Mito server fallback.
215
+ """
216
+
217
+ def __init__(self, api_key: Optional[str], timeout: int = 30, max_retries: int = 1):
218
+ self.api_key = api_key
219
+ self.timeout = timeout
220
+ self.max_retries = max_retries
221
+ self.client: Optional[anthropic.Anthropic]
222
+ if api_key:
223
+ self.client = anthropic.Anthropic(api_key=api_key)
224
+ else:
225
+ self.client = None
226
+
227
+ async def request_completions(
228
+ self, messages: List[ChatCompletionMessageParam],
229
+ model: str,
230
+ response_format_info: Optional[ResponseFormatInfo] = None,
231
+ message_type: MessageType = MessageType.CHAT
232
+ ) -> Any:
233
+ """
234
+ Get a response from Claude or the Mito server that adheres to the AgentResponse format.
235
+ """
236
+ anthropic_system_prompt, anthropic_messages = get_anthropic_system_prompt_and_messages_with_caching(messages)
237
+
238
+ provider_data = get_anthropic_completion_function_params(
239
+ message_type=message_type,
240
+ model=model,
241
+ messages=anthropic_messages,
242
+ max_tokens=MAX_TOKENS,
243
+ temperature=0,
244
+ system=anthropic_system_prompt,
245
+ stream=None,
246
+ response_format_info=response_format_info
247
+ )
248
+
249
+ if self.api_key:
250
+ # Unpack provider_data for direct API call
251
+ assert self.client is not None
252
+ response = self.client.messages.create(**provider_data)
253
+
254
+ if provider_data.get("tool_choice") is not None:
255
+ result = extract_and_parse_anthropic_json_response(response)
256
+ return json.dumps(result) if not isinstance(result, str) else result
257
+ else:
258
+ content = response.content
259
+ if content[0].type == "text":
260
+ return content[0].text
261
+ else:
262
+ return ""
263
+ else:
264
+ # Only pass provider_data to the server
265
+ response = await get_anthropic_completion_from_mito_server(
266
+ model=provider_data["model"],
267
+ max_tokens=provider_data["max_tokens"],
268
+ temperature=provider_data["temperature"],
269
+ system=provider_data["system"],
270
+ messages=provider_data["messages"],
271
+ tools=provider_data.get("tools"),
272
+ tool_choice=provider_data.get("tool_choice"),
273
+ message_type=message_type
274
+ )
275
+ return response
276
+
277
+ async def stream_completions(self, messages: List[ChatCompletionMessageParam], model: str, message_id: str, message_type: MessageType,
278
+ reply_fn: Callable[[Union[CompletionReply, CompletionStreamChunk]], None]) -> str:
279
+ try:
280
+ anthropic_system_prompt, anthropic_messages = get_anthropic_system_prompt_and_messages_with_caching(messages)
281
+ accumulated_response = ""
282
+
283
+ if self.api_key:
284
+ assert self.client is not None
285
+ stream = self.client.messages.create(
286
+ model=model,
287
+ max_tokens=MAX_TOKENS,
288
+ temperature=0,
289
+ system=anthropic_system_prompt,
290
+ messages=anthropic_messages,
291
+ stream=True
292
+ )
293
+
294
+ for chunk in stream:
295
+ if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta":
296
+ content = chunk.delta.text
297
+ accumulated_response += content
298
+
299
+ is_finished = chunk.type == "message_stop"
300
+
301
+ reply_fn(CompletionStreamChunk(
302
+ parent_id=message_id,
303
+ chunk=CompletionItem(
304
+ content=content,
305
+ isIncomplete=not is_finished,
306
+ token=message_id,
307
+ ),
308
+ done=is_finished,
309
+ ))
310
+
311
+ else:
312
+ async for stram_chunk in stream_anthropic_completion_from_mito_server(
313
+ model=model,
314
+ max_tokens=MAX_TOKENS,
315
+ temperature=0,
316
+ system=anthropic_system_prompt,
317
+ messages=anthropic_messages,
318
+ stream=True,
319
+ message_type=message_type,
320
+ reply_fn=reply_fn,
321
+ message_id=message_id
322
+ ):
323
+ accumulated_response += stram_chunk
324
+
325
+ return accumulated_response
326
+
327
+ except anthropic.RateLimitError:
328
+ raise Exception("Rate limit exceeded. Please try again later or reduce your request frequency.")
329
+
330
+ except Exception as e:
331
+ print(f"Error streaming content: {str(e)}")
332
+ raise e
333
+
334
+
@@ -0,0 +1,6 @@
1
+ # Copyright (c) Saga Inc.
2
+ # Distributed under the terms of the GNU Affero General Public License v3.0 License.
3
+
4
+ """App builder module for Mito AI."""
5
+
6
+ from .handlers import AppDeployHandler
@@ -0,0 +1,44 @@
1
+ # Copyright (c) Saga Inc.
2
+ # Distributed under the terms of the GNU Affero General Public License v3.0 License.
3
+
4
+ import os
5
+ import zipfile
6
+ import logging
7
+ from typing import List, Optional
8
+
9
+ from mito_ai.path_utils import AbsoluteNotebookDirPath
10
+
11
+ def add_files_to_zip(
12
+ zip_path: str,
13
+ notebook_dir_path: AbsoluteNotebookDirPath,
14
+ files_to_add: List[str],
15
+ app_file_name: str,
16
+ logger: Optional[logging.Logger] = None
17
+ ) -> None:
18
+ """Create a zip file at zip_path and add the selected files/folders."""
19
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
20
+ for file_to_add_rel_path in files_to_add:
21
+
22
+ file_to_add_abs_path = os.path.join(notebook_dir_path, file_to_add_rel_path)
23
+
24
+ if os.path.isfile(file_to_add_abs_path):
25
+ basename = os.path.basename(file_to_add_abs_path)
26
+
27
+ if basename == app_file_name:
28
+ # For the actual app file, we want to write it just as app.py
29
+ # so our infra can always deploy using `streamlit run app.py`
30
+ # without having to account for different app names
31
+ zipf.write(file_to_add_abs_path, arcname='app.py')
32
+ else:
33
+ # otherwise we want to keep the name as is so all references
34
+ # to it from the app are correct
35
+ zipf.write(file_to_add_abs_path, arcname=file_to_add_rel_path)
36
+ elif os.path.isdir(file_to_add_abs_path):
37
+ for root, _, files in os.walk(file_to_add_abs_path):
38
+ for file in files:
39
+ file_abs = os.path.join(root, file)
40
+ arcname = os.path.relpath(file_abs, notebook_dir_path)
41
+ zipf.write(file_abs, arcname=arcname)
42
+ else:
43
+ if logger:
44
+ logger.warning(f"Skipping missing file: {file_to_add_abs_path}")