asksql 2.1.0__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 (291) hide show
  1. asksql-2.1.0.dist-info/METADATA +517 -0
  2. asksql-2.1.0.dist-info/RECORD +291 -0
  3. asksql-2.1.0.dist-info/WHEEL +4 -0
  4. asksql-2.1.0.dist-info/entry_points.txt +4 -0
  5. asksql-2.1.0.dist-info/licenses/LICENSE +21 -0
  6. vanna/__init__.py +172 -0
  7. vanna/agents/__init__.py +7 -0
  8. vanna/capabilities/__init__.py +17 -0
  9. vanna/capabilities/agent_memory/__init__.py +21 -0
  10. vanna/capabilities/agent_memory/base.py +103 -0
  11. vanna/capabilities/agent_memory/models.py +53 -0
  12. vanna/capabilities/file_system/__init__.py +14 -0
  13. vanna/capabilities/file_system/base.py +71 -0
  14. vanna/capabilities/file_system/models.py +25 -0
  15. vanna/capabilities/sql_runner/__init__.py +13 -0
  16. vanna/capabilities/sql_runner/base.py +37 -0
  17. vanna/capabilities/sql_runner/models.py +13 -0
  18. vanna/components/__init__.py +92 -0
  19. vanna/components/base.py +11 -0
  20. vanna/components/rich/__init__.py +83 -0
  21. vanna/components/rich/containers/__init__.py +7 -0
  22. vanna/components/rich/containers/card.py +20 -0
  23. vanna/components/rich/data/__init__.py +9 -0
  24. vanna/components/rich/data/chart.py +17 -0
  25. vanna/components/rich/data/dataframe.py +93 -0
  26. vanna/components/rich/feedback/__init__.py +21 -0
  27. vanna/components/rich/feedback/badge.py +16 -0
  28. vanna/components/rich/feedback/icon_text.py +14 -0
  29. vanna/components/rich/feedback/log_viewer.py +41 -0
  30. vanna/components/rich/feedback/notification.py +19 -0
  31. vanna/components/rich/feedback/progress.py +37 -0
  32. vanna/components/rich/feedback/status_card.py +28 -0
  33. vanna/components/rich/feedback/status_indicator.py +14 -0
  34. vanna/components/rich/interactive/__init__.py +21 -0
  35. vanna/components/rich/interactive/button.py +95 -0
  36. vanna/components/rich/interactive/task_list.py +58 -0
  37. vanna/components/rich/interactive/ui_state.py +93 -0
  38. vanna/components/rich/specialized/__init__.py +7 -0
  39. vanna/components/rich/specialized/artifact.py +20 -0
  40. vanna/components/rich/text.py +16 -0
  41. vanna/components/simple/__init__.py +15 -0
  42. vanna/components/simple/image.py +15 -0
  43. vanna/components/simple/link.py +15 -0
  44. vanna/components/simple/text.py +11 -0
  45. vanna/core/__init__.py +193 -0
  46. vanna/core/_compat.py +19 -0
  47. vanna/core/agent/__init__.py +10 -0
  48. vanna/core/agent/agent.py +1407 -0
  49. vanna/core/agent/config.py +123 -0
  50. vanna/core/audit/__init__.py +28 -0
  51. vanna/core/audit/base.py +299 -0
  52. vanna/core/audit/models.py +131 -0
  53. vanna/core/component_manager.py +329 -0
  54. vanna/core/components.py +53 -0
  55. vanna/core/enhancer/__init__.py +11 -0
  56. vanna/core/enhancer/base.py +94 -0
  57. vanna/core/enhancer/default.py +118 -0
  58. vanna/core/enricher/__init__.py +10 -0
  59. vanna/core/enricher/base.py +59 -0
  60. vanna/core/errors.py +47 -0
  61. vanna/core/evaluation/__init__.py +81 -0
  62. vanna/core/evaluation/base.py +186 -0
  63. vanna/core/evaluation/dataset.py +254 -0
  64. vanna/core/evaluation/evaluators.py +376 -0
  65. vanna/core/evaluation/report.py +289 -0
  66. vanna/core/evaluation/runner.py +313 -0
  67. vanna/core/filter/__init__.py +10 -0
  68. vanna/core/filter/base.py +67 -0
  69. vanna/core/lifecycle/__init__.py +10 -0
  70. vanna/core/lifecycle/base.py +83 -0
  71. vanna/core/llm/__init__.py +16 -0
  72. vanna/core/llm/base.py +40 -0
  73. vanna/core/llm/models.py +61 -0
  74. vanna/core/middleware/__init__.py +10 -0
  75. vanna/core/middleware/base.py +69 -0
  76. vanna/core/observability/__init__.py +11 -0
  77. vanna/core/observability/base.py +88 -0
  78. vanna/core/observability/models.py +47 -0
  79. vanna/core/recovery/__init__.py +11 -0
  80. vanna/core/recovery/base.py +84 -0
  81. vanna/core/recovery/models.py +32 -0
  82. vanna/core/registry.py +278 -0
  83. vanna/core/rich_component.py +156 -0
  84. vanna/core/simple_component.py +27 -0
  85. vanna/core/storage/__init__.py +14 -0
  86. vanna/core/storage/base.py +46 -0
  87. vanna/core/storage/models.py +46 -0
  88. vanna/core/system_prompt/__init__.py +13 -0
  89. vanna/core/system_prompt/base.py +36 -0
  90. vanna/core/system_prompt/default.py +157 -0
  91. vanna/core/tool/__init__.py +18 -0
  92. vanna/core/tool/base.py +70 -0
  93. vanna/core/tool/models.py +84 -0
  94. vanna/core/user/__init__.py +17 -0
  95. vanna/core/user/base.py +29 -0
  96. vanna/core/user/models.py +25 -0
  97. vanna/core/user/request_context.py +70 -0
  98. vanna/core/user/resolver.py +42 -0
  99. vanna/core/validation.py +164 -0
  100. vanna/core/workflow/__init__.py +12 -0
  101. vanna/core/workflow/base.py +254 -0
  102. vanna/core/workflow/default.py +789 -0
  103. vanna/examples/__init__.py +1 -0
  104. vanna/examples/__main__.py +44 -0
  105. vanna/examples/anthropic_quickstart.py +80 -0
  106. vanna/examples/artifact_example.py +293 -0
  107. vanna/examples/claude_sqlite_example.py +236 -0
  108. vanna/examples/coding_agent_example.py +300 -0
  109. vanna/examples/custom_system_prompt_example.py +174 -0
  110. vanna/examples/default_workflow_handler_example.py +208 -0
  111. vanna/examples/email_auth_example.py +340 -0
  112. vanna/examples/evaluation_example.py +269 -0
  113. vanna/examples/extensibility_example.py +262 -0
  114. vanna/examples/minimal_example.py +67 -0
  115. vanna/examples/mock_auth_example.py +227 -0
  116. vanna/examples/mock_custom_tool.py +311 -0
  117. vanna/examples/mock_quickstart.py +79 -0
  118. vanna/examples/mock_quota_example.py +145 -0
  119. vanna/examples/mock_rich_components_demo.py +396 -0
  120. vanna/examples/mock_sqlite_example.py +223 -0
  121. vanna/examples/openai_quickstart.py +83 -0
  122. vanna/examples/primitive_components_demo.py +305 -0
  123. vanna/examples/quota_lifecycle_example.py +139 -0
  124. vanna/examples/visualization_example.py +251 -0
  125. vanna/integrations/__init__.py +17 -0
  126. vanna/integrations/anthropic/__init__.py +9 -0
  127. vanna/integrations/anthropic/llm.py +270 -0
  128. vanna/integrations/azureopenai/__init__.py +9 -0
  129. vanna/integrations/azureopenai/llm.py +329 -0
  130. vanna/integrations/azuresearch/__init__.py +7 -0
  131. vanna/integrations/azuresearch/agent_memory.py +413 -0
  132. vanna/integrations/bigquery/__init__.py +5 -0
  133. vanna/integrations/bigquery/sql_runner.py +81 -0
  134. vanna/integrations/chromadb/__init__.py +104 -0
  135. vanna/integrations/chromadb/agent_memory.py +488 -0
  136. vanna/integrations/clickhouse/__init__.py +5 -0
  137. vanna/integrations/clickhouse/sql_runner.py +82 -0
  138. vanna/integrations/duckdb/__init__.py +5 -0
  139. vanna/integrations/duckdb/sql_runner.py +65 -0
  140. vanna/integrations/faiss/__init__.py +7 -0
  141. vanna/integrations/faiss/agent_memory.py +435 -0
  142. vanna/integrations/google/__init__.py +9 -0
  143. vanna/integrations/google/gemini.py +370 -0
  144. vanna/integrations/hive/__init__.py +5 -0
  145. vanna/integrations/hive/sql_runner.py +87 -0
  146. vanna/integrations/local/__init__.py +17 -0
  147. vanna/integrations/local/agent_memory/__init__.py +7 -0
  148. vanna/integrations/local/agent_memory/in_memory.py +285 -0
  149. vanna/integrations/local/audit.py +59 -0
  150. vanna/integrations/local/file_system.py +242 -0
  151. vanna/integrations/local/file_system_conversation_store.py +255 -0
  152. vanna/integrations/local/storage.py +62 -0
  153. vanna/integrations/marqo/__init__.py +7 -0
  154. vanna/integrations/marqo/agent_memory.py +354 -0
  155. vanna/integrations/milvus/__init__.py +7 -0
  156. vanna/integrations/milvus/agent_memory.py +458 -0
  157. vanna/integrations/mock/__init__.py +9 -0
  158. vanna/integrations/mock/llm.py +65 -0
  159. vanna/integrations/mssql/__init__.py +5 -0
  160. vanna/integrations/mssql/sql_runner.py +66 -0
  161. vanna/integrations/mysql/__init__.py +5 -0
  162. vanna/integrations/mysql/sql_runner.py +92 -0
  163. vanna/integrations/ollama/__init__.py +7 -0
  164. vanna/integrations/ollama/llm.py +252 -0
  165. vanna/integrations/openai/__init__.py +10 -0
  166. vanna/integrations/openai/llm.py +267 -0
  167. vanna/integrations/openai/responses.py +163 -0
  168. vanna/integrations/opensearch/__init__.py +7 -0
  169. vanna/integrations/opensearch/agent_memory.py +411 -0
  170. vanna/integrations/oracle/__init__.py +5 -0
  171. vanna/integrations/oracle/sql_runner.py +75 -0
  172. vanna/integrations/pinecone/__init__.py +7 -0
  173. vanna/integrations/pinecone/agent_memory.py +329 -0
  174. vanna/integrations/plotly/__init__.py +5 -0
  175. vanna/integrations/plotly/chart_generator.py +313 -0
  176. vanna/integrations/postgres/__init__.py +9 -0
  177. vanna/integrations/postgres/sql_runner.py +112 -0
  178. vanna/integrations/premium/agent_memory/__init__.py +7 -0
  179. vanna/integrations/premium/agent_memory/premium.py +186 -0
  180. vanna/integrations/presto/__init__.py +5 -0
  181. vanna/integrations/presto/sql_runner.py +107 -0
  182. vanna/integrations/qdrant/__init__.py +7 -0
  183. vanna/integrations/qdrant/agent_memory.py +466 -0
  184. vanna/integrations/snowflake/__init__.py +5 -0
  185. vanna/integrations/snowflake/sql_runner.py +147 -0
  186. vanna/integrations/sqlite/__init__.py +9 -0
  187. vanna/integrations/sqlite/sql_runner.py +65 -0
  188. vanna/integrations/weaviate/__init__.py +7 -0
  189. vanna/integrations/weaviate/agent_memory.py +428 -0
  190. vanna/legacy/ZhipuAI/ZhipuAI_Chat.py +233 -0
  191. vanna/legacy/ZhipuAI/ZhipuAI_embeddings.py +79 -0
  192. vanna/legacy/ZhipuAI/__init__.py +2 -0
  193. vanna/legacy/__init__.py +403 -0
  194. vanna/legacy/adapter.py +468 -0
  195. vanna/legacy/advanced/__init__.py +28 -0
  196. vanna/legacy/anthropic/__init__.py +1 -0
  197. vanna/legacy/anthropic/anthropic_chat.py +80 -0
  198. vanna/legacy/azuresearch/__init__.py +1 -0
  199. vanna/legacy/azuresearch/azuresearch_vector.py +274 -0
  200. vanna/legacy/base/__init__.py +1 -0
  201. vanna/legacy/base/base.py +2133 -0
  202. vanna/legacy/base/safe_exec.py +190 -0
  203. vanna/legacy/bedrock/__init__.py +1 -0
  204. vanna/legacy/bedrock/bedrock_converse.py +86 -0
  205. vanna/legacy/chromadb/__init__.py +1 -0
  206. vanna/legacy/chromadb/chromadb_vector.py +259 -0
  207. vanna/legacy/cohere/__init__.py +2 -0
  208. vanna/legacy/cohere/cohere_chat.py +99 -0
  209. vanna/legacy/cohere/cohere_embeddings.py +77 -0
  210. vanna/legacy/deepseek/__init__.py +1 -0
  211. vanna/legacy/deepseek/deepseek_chat.py +59 -0
  212. vanna/legacy/exceptions/__init__.py +46 -0
  213. vanna/legacy/faiss/__init__.py +1 -0
  214. vanna/legacy/faiss/faiss.py +230 -0
  215. vanna/legacy/flask/__init__.py +1355 -0
  216. vanna/legacy/flask/assets.py +58 -0
  217. vanna/legacy/flask/auth.py +56 -0
  218. vanna/legacy/google/__init__.py +2 -0
  219. vanna/legacy/google/bigquery_vector.py +293 -0
  220. vanna/legacy/google/gemini_chat.py +78 -0
  221. vanna/legacy/hf/__init__.py +1 -0
  222. vanna/legacy/hf/hf.py +80 -0
  223. vanna/legacy/local.py +8 -0
  224. vanna/legacy/marqo/__init__.py +1 -0
  225. vanna/legacy/marqo/marqo.py +168 -0
  226. vanna/legacy/milvus/__init__.py +1 -0
  227. vanna/legacy/milvus/milvus_vector.py +328 -0
  228. vanna/legacy/mistral/__init__.py +1 -0
  229. vanna/legacy/mistral/mistral.py +51 -0
  230. vanna/legacy/mock/__init__.py +3 -0
  231. vanna/legacy/mock/embedding.py +11 -0
  232. vanna/legacy/mock/llm.py +18 -0
  233. vanna/legacy/mock/vectordb.py +67 -0
  234. vanna/legacy/ollama/__init__.py +1 -0
  235. vanna/legacy/ollama/ollama.py +110 -0
  236. vanna/legacy/openai/__init__.py +2 -0
  237. vanna/legacy/openai/openai_chat.py +124 -0
  238. vanna/legacy/openai/openai_embeddings.py +46 -0
  239. vanna/legacy/opensearch/__init__.py +2 -0
  240. vanna/legacy/opensearch/opensearch_vector.py +369 -0
  241. vanna/legacy/opensearch/opensearch_vector_semantic.py +200 -0
  242. vanna/legacy/oracle/__init__.py +1 -0
  243. vanna/legacy/oracle/oracle_vector.py +584 -0
  244. vanna/legacy/pgvector/__init__.py +1 -0
  245. vanna/legacy/pgvector/pgvector.py +282 -0
  246. vanna/legacy/pinecone/__init__.py +3 -0
  247. vanna/legacy/pinecone/pinecone_vector.py +275 -0
  248. vanna/legacy/qdrant/__init__.py +3 -0
  249. vanna/legacy/qdrant/qdrant.py +329 -0
  250. vanna/legacy/qianfan/Qianfan_Chat.py +170 -0
  251. vanna/legacy/qianfan/Qianfan_embeddings.py +36 -0
  252. vanna/legacy/qianfan/__init__.py +2 -0
  253. vanna/legacy/qianwen/QianwenAI_chat.py +132 -0
  254. vanna/legacy/qianwen/QianwenAI_embeddings.py +46 -0
  255. vanna/legacy/qianwen/__init__.py +2 -0
  256. vanna/legacy/remote.py +79 -0
  257. vanna/legacy/types/__init__.py +292 -0
  258. vanna/legacy/utils.py +72 -0
  259. vanna/legacy/vannadb/__init__.py +1 -0
  260. vanna/legacy/vannadb/vannadb_vector.py +468 -0
  261. vanna/legacy/vllm/__init__.py +1 -0
  262. vanna/legacy/vllm/vllm.py +97 -0
  263. vanna/legacy/weaviate/__init__.py +1 -0
  264. vanna/legacy/weaviate/weaviate_vector.py +194 -0
  265. vanna/legacy/xinference/__init__.py +1 -0
  266. vanna/legacy/xinference/xinference.py +53 -0
  267. vanna/py.typed +0 -0
  268. vanna/servers/__init__.py +16 -0
  269. vanna/servers/__main__.py +8 -0
  270. vanna/servers/base/__init__.py +18 -0
  271. vanna/servers/base/chat_handler.py +65 -0
  272. vanna/servers/base/models.py +111 -0
  273. vanna/servers/base/rich_chat_handler.py +141 -0
  274. vanna/servers/base/templates.py +331 -0
  275. vanna/servers/cli/__init__.py +7 -0
  276. vanna/servers/cli/server_runner.py +204 -0
  277. vanna/servers/fastapi/__init__.py +7 -0
  278. vanna/servers/fastapi/app.py +163 -0
  279. vanna/servers/fastapi/routes.py +183 -0
  280. vanna/servers/flask/__init__.py +7 -0
  281. vanna/servers/flask/app.py +132 -0
  282. vanna/servers/flask/routes.py +137 -0
  283. vanna/tools/__init__.py +41 -0
  284. vanna/tools/agent_memory.py +322 -0
  285. vanna/tools/file_system.py +879 -0
  286. vanna/tools/python.py +222 -0
  287. vanna/tools/run_sql.py +173 -0
  288. vanna/tools/visualize_data.py +195 -0
  289. vanna/utils/__init__.py +0 -0
  290. vanna/utils/sql_safety.py +84 -0
  291. vanna/web_components/__init__.py +44 -0
@@ -0,0 +1,2133 @@
1
+ r"""
2
+
3
+ # Nomenclature
4
+
5
+ | Prefix | Definition | Examples |
6
+ | --- | --- | --- |
7
+ | `vn.get_` | Fetch some data | [`vn.get_related_ddl(...)`][vanna.base.base.VannaBase.get_related_ddl] |
8
+ | `vn.add_` | Adds something to the retrieval layer | [`vn.add_question_sql(...)`][vanna.base.base.VannaBase.add_question_sql] <br> [`vn.add_ddl(...)`][vanna.base.base.VannaBase.add_ddl] |
9
+ | `vn.generate_` | Generates something using AI based on the information in the model | [`vn.generate_sql(...)`][vanna.base.base.VannaBase.generate_sql] <br> [`vn.generate_explanation()`][vanna.base.base.VannaBase.generate_explanation] |
10
+ | `vn.run_` | Runs code (SQL) | [`vn.run_sql`][vanna.base.base.VannaBase.run_sql] |
11
+ | `vn.remove_` | Removes something from the retrieval layer | [`vn.remove_training_data`][vanna.base.base.VannaBase.remove_training_data] |
12
+ | `vn.connect_` | Connects to a database | [`vn.connect_to_snowflake(...)`][vanna.base.base.VannaBase.connect_to_snowflake] |
13
+ | `vn.update_` | Updates something | N/A -- unused |
14
+ | `vn.set_` | Sets something | N/A -- unused |
15
+
16
+ # Open-Source and Extending
17
+
18
+ Vanna.AI is open-source and extensible. If you'd like to use Vanna without the servers, see an example [here](https://vanna.ai/docs/postgres-ollama-chromadb/).
19
+
20
+ The following is an example of where various functions are implemented in the codebase when using the default "local" version of Vanna. `vanna.base.VannaBase` is the base class which provides a `vanna.base.VannaBase.ask` and `vanna.base.VannaBase.train` function. Those rely on abstract methods which are implemented in the subclasses `vanna.openai_chat.OpenAI_Chat` and `vanna.chromadb_vector.ChromaDB_VectorStore`. `vanna.openai_chat.OpenAI_Chat` uses the OpenAI API to generate SQL and Plotly code. `vanna.chromadb_vector.ChromaDB_VectorStore` uses ChromaDB to store training data and generate embeddings.
21
+
22
+ If you want to use Vanna with other LLMs or databases, you can create your own subclass of `vanna.base.VannaBase` and implement the abstract methods.
23
+
24
+ ```mermaid
25
+ flowchart
26
+ subgraph VannaBase
27
+ ask
28
+ train
29
+ end
30
+
31
+ subgraph OpenAI_Chat
32
+ get_sql_prompt
33
+ submit_prompt
34
+ generate_question
35
+ generate_plotly_code
36
+ end
37
+
38
+ subgraph ChromaDB_VectorStore
39
+ generate_embedding
40
+ add_question_sql
41
+ add_ddl
42
+ add_documentation
43
+ get_similar_question_sql
44
+ get_related_ddl
45
+ get_related_documentation
46
+ end
47
+ ```
48
+
49
+ """
50
+
51
+ import json
52
+ import os
53
+ import re
54
+ import sqlite3
55
+ import traceback
56
+ from abc import ABC, abstractmethod
57
+ from typing import List, Tuple, Union
58
+ from urllib.parse import urlparse
59
+
60
+ import pandas as pd
61
+ import plotly
62
+ import plotly.express as px
63
+ import plotly.graph_objects as go
64
+ import requests
65
+ import sqlparse
66
+
67
+ from ..exceptions import DependencyError, ImproperlyConfigured, ValidationError
68
+ from ..types import TrainingPlan, TrainingPlanItem
69
+ from ..utils import validate_config_path
70
+ from ...utils.sql_safety import ensure_read_only_sql
71
+ from .safe_exec import exec_plotly_code
72
+
73
+
74
+ class VannaBase(ABC):
75
+ def __init__(self, config=None):
76
+ if config is None:
77
+ config = {}
78
+
79
+ self.config = config
80
+ self.run_sql_is_set = False
81
+ self.static_documentation = ""
82
+ self.dialect = self.config.get("dialect", "SQL")
83
+ self.language = self.config.get("language", None)
84
+ self.max_tokens = self.config.get("max_tokens", 14000)
85
+
86
+ def log(self, message: str, title: str = "Info"):
87
+ print(f"{title}: {message}")
88
+
89
+ def _ensure_llm_sql_allowed(self, sql: str) -> None:
90
+ """Block non-read-only LLM-generated SQL unless config allow_write_sql=True (vanna-ai/vanna#1078)."""
91
+ config = getattr(self, "config", None) or {}
92
+ if not config.get("allow_write_sql", False):
93
+ ensure_read_only_sql(sql)
94
+
95
+ def _response_language(self) -> str:
96
+ if self.language is None:
97
+ return ""
98
+
99
+ return f"Respond in the {self.language} language."
100
+
101
+ def generate_sql(self, question: str, allow_llm_to_see_data=False, **kwargs) -> str:
102
+ """
103
+ Example:
104
+ ```python
105
+ vn.generate_sql("What are the top 10 customers by sales?")
106
+ ```
107
+
108
+ Uses the LLM to generate a SQL query that answers a question. It runs the following methods:
109
+
110
+ - [`get_similar_question_sql`][vanna.base.base.VannaBase.get_similar_question_sql]
111
+
112
+ - [`get_related_ddl`][vanna.base.base.VannaBase.get_related_ddl]
113
+
114
+ - [`get_related_documentation`][vanna.base.base.VannaBase.get_related_documentation]
115
+
116
+ - [`get_sql_prompt`][vanna.base.base.VannaBase.get_sql_prompt]
117
+
118
+ - [`submit_prompt`][vanna.base.base.VannaBase.submit_prompt]
119
+
120
+
121
+ Args:
122
+ question (str): The question to generate a SQL query for.
123
+ allow_llm_to_see_data (bool): Whether to allow the LLM to see the data (for the purposes of introspecting the data to generate the final SQL).
124
+
125
+ Returns:
126
+ str: The SQL query that answers the question.
127
+ """
128
+ if self.config is not None:
129
+ initial_prompt = self.config.get("initial_prompt", None)
130
+ else:
131
+ initial_prompt = None
132
+ question_sql_list = self.get_similar_question_sql(question, **kwargs)
133
+ ddl_list = self.get_related_ddl(question, **kwargs)
134
+ doc_list = self.get_related_documentation(question, **kwargs)
135
+ prompt = self.get_sql_prompt(
136
+ initial_prompt=initial_prompt,
137
+ question=question,
138
+ question_sql_list=question_sql_list,
139
+ ddl_list=ddl_list,
140
+ doc_list=doc_list,
141
+ **kwargs,
142
+ )
143
+ self.log(title="SQL Prompt", message=prompt)
144
+ llm_response = self.submit_prompt(prompt, **kwargs)
145
+ self.log(title="LLM Response", message=llm_response)
146
+
147
+ if "intermediate_sql" in llm_response:
148
+ if not allow_llm_to_see_data:
149
+ return "The LLM is not allowed to see the data in your database. Your question requires database introspection to generate the necessary SQL. Please set allow_llm_to_see_data=True to enable this."
150
+
151
+ if allow_llm_to_see_data:
152
+ intermediate_sql = self.extract_sql(llm_response)
153
+
154
+ try:
155
+ self.log(title="Running Intermediate SQL", message=intermediate_sql)
156
+ self._ensure_llm_sql_allowed(intermediate_sql)
157
+ df = self.run_sql(intermediate_sql)
158
+
159
+ prompt = self.get_sql_prompt(
160
+ initial_prompt=initial_prompt,
161
+ question=question,
162
+ question_sql_list=question_sql_list,
163
+ ddl_list=ddl_list,
164
+ doc_list=doc_list
165
+ + [
166
+ f"The following is a pandas DataFrame with the results of the intermediate SQL query {intermediate_sql}: \n"
167
+ + df.to_markdown()
168
+ ],
169
+ **kwargs,
170
+ )
171
+ self.log(title="Final SQL Prompt", message=prompt)
172
+ llm_response = self.submit_prompt(prompt, **kwargs)
173
+ self.log(title="LLM Response", message=llm_response)
174
+ except Exception as e:
175
+ return f"Error running intermediate SQL: {e}"
176
+
177
+ return self.extract_sql(llm_response)
178
+
179
+ def extract_sql(self, llm_response: str) -> str:
180
+ """
181
+ Example:
182
+ ```python
183
+ vn.extract_sql("Here's the SQL query in a code block: ```sql\nSELECT * FROM customers\n```")
184
+ ```
185
+
186
+ Extracts the SQL query from the LLM response. This is useful in case the LLM response contains other information besides the SQL query.
187
+ Override this function if your LLM responses need custom extraction logic.
188
+
189
+ Args:
190
+ llm_response (str): The LLM response.
191
+
192
+ Returns:
193
+ str: The extracted SQL query.
194
+ """
195
+
196
+ import re
197
+
198
+ """
199
+ Extracts the SQL query from the LLM response, handling various formats including:
200
+ - WITH clause
201
+ - SELECT statement
202
+ - CREATE TABLE AS SELECT
203
+ - Markdown code blocks
204
+ """
205
+
206
+ # Match CREATE TABLE ... AS SELECT
207
+ sqls = re.findall(
208
+ r"\bCREATE\s+TABLE\b.*?\bAS\b.*?;", llm_response, re.DOTALL | re.IGNORECASE
209
+ )
210
+ if sqls:
211
+ sql = sqls[-1]
212
+ self.log(title="Extracted SQL", message=f"{sql}")
213
+ return sql
214
+
215
+ # Match WITH clause (CTEs)
216
+ sqls = re.findall(r"\bWITH\b .*?;", llm_response, re.DOTALL | re.IGNORECASE)
217
+ if sqls:
218
+ sql = sqls[-1]
219
+ self.log(title="Extracted SQL", message=f"{sql}")
220
+ return sql
221
+
222
+ # Match SELECT ... ;
223
+ sqls = re.findall(r"\bSELECT\b .*?;", llm_response, re.DOTALL | re.IGNORECASE)
224
+ if sqls:
225
+ sql = sqls[-1]
226
+ self.log(title="Extracted SQL", message=f"{sql}")
227
+ return sql
228
+
229
+ # Match ```sql ... ``` blocks
230
+ sqls = re.findall(
231
+ r"```sql\s*\n(.*?)```", llm_response, re.DOTALL | re.IGNORECASE
232
+ )
233
+ if sqls:
234
+ sql = sqls[-1].strip()
235
+ self.log(title="Extracted SQL", message=f"{sql}")
236
+ return sql
237
+
238
+ # Match any ``` ... ``` code blocks
239
+ sqls = re.findall(r"```(.*?)```", llm_response, re.DOTALL | re.IGNORECASE)
240
+ if sqls:
241
+ sql = sqls[-1].strip()
242
+ self.log(title="Extracted SQL", message=f"{sql}")
243
+ return sql
244
+
245
+ return llm_response
246
+
247
+ def is_sql_valid(self, sql: str) -> bool:
248
+ """
249
+ Example:
250
+ ```python
251
+ vn.is_sql_valid("SELECT * FROM customers")
252
+ ```
253
+ Checks if the SQL query is valid. This is usually used to check if we should run the SQL query or not.
254
+ By default it checks if the SQL query is a SELECT statement. You can override this method to enable running other types of SQL queries.
255
+
256
+ Args:
257
+ sql (str): The SQL query to check.
258
+
259
+ Returns:
260
+ bool: True if the SQL query is valid, False otherwise.
261
+ """
262
+
263
+ parsed = sqlparse.parse(sql)
264
+
265
+ for statement in parsed:
266
+ if statement.get_type() == "SELECT":
267
+ return True
268
+
269
+ return False
270
+
271
+ def should_generate_chart(self, df: pd.DataFrame) -> bool:
272
+ """
273
+ Example:
274
+ ```python
275
+ vn.should_generate_chart(df)
276
+ ```
277
+
278
+ Checks if a chart should be generated for the given DataFrame. By default, it checks if the DataFrame has more than one row and has numerical columns.
279
+ You can override this method to customize the logic for generating charts.
280
+
281
+ Args:
282
+ df (pd.DataFrame): The DataFrame to check.
283
+
284
+ Returns:
285
+ bool: True if a chart should be generated, False otherwise.
286
+ """
287
+
288
+ if len(df) > 1 and df.select_dtypes(include=["number"]).shape[1] > 0:
289
+ return True
290
+
291
+ return False
292
+
293
+ def generate_rewritten_question(
294
+ self, last_question: str, new_question: str, **kwargs
295
+ ) -> str:
296
+ """
297
+ **Example:**
298
+ ```python
299
+ rewritten_question = vn.generate_rewritten_question("Who are the top 5 customers by sales?", "Show me their email addresses")
300
+ ```
301
+
302
+ Generate a rewritten question by combining the last question and the new question if they are related. If the new question is self-contained and not related to the last question, return the new question.
303
+
304
+ Args:
305
+ last_question (str): The previous question that was asked.
306
+ new_question (str): The new question to be combined with the last question.
307
+ **kwargs: Additional keyword arguments.
308
+
309
+ Returns:
310
+ str: The combined question if related, otherwise the new question.
311
+ """
312
+ if last_question is None:
313
+ return new_question
314
+
315
+ prompt = [
316
+ self.system_message(
317
+ "Your goal is to combine a sequence of questions into a singular question if they are related. If the second question does not relate to the first question and is fully self-contained, return the second question. Return just the new combined question with no additional explanations. The question should theoretically be answerable with a single SQL statement."
318
+ ),
319
+ self.user_message(
320
+ "First question: "
321
+ + last_question
322
+ + "\nSecond question: "
323
+ + new_question
324
+ ),
325
+ ]
326
+
327
+ return self.submit_prompt(prompt=prompt, **kwargs)
328
+
329
+ def generate_followup_questions(
330
+ self, question: str, sql: str, df: pd.DataFrame, n_questions: int = 5, **kwargs
331
+ ) -> list:
332
+ """
333
+ **Example:**
334
+ ```python
335
+ vn.generate_followup_questions("What are the top 10 customers by sales?", sql, df)
336
+ ```
337
+
338
+ Generate a list of followup questions that you can ask Vanna.AI.
339
+
340
+ Args:
341
+ question (str): The question that was asked.
342
+ sql (str): The LLM-generated SQL query.
343
+ df (pd.DataFrame): The results of the SQL query.
344
+ n_questions (int): Number of follow-up questions to generate.
345
+
346
+ Returns:
347
+ list: A list of followup questions that you can ask Vanna.AI.
348
+ """
349
+
350
+ message_log = [
351
+ self.system_message(
352
+ f"You are a helpful data assistant. The user asked the question: '{question}'\n\nThe SQL query for this question was: {sql}\n\nThe following is a pandas DataFrame with the results of the query: \n{df.head(25).to_markdown()}\n\n"
353
+ ),
354
+ self.user_message(
355
+ f"Generate a list of {n_questions} followup questions that the user might ask about this data. Respond with a list of questions, one per line. Do not answer with any explanations -- just the questions. Remember that there should be an unambiguous SQL query that can be generated from the question. Prefer questions that are answerable outside of the context of this conversation. Prefer questions that are slight modifications of the SQL query that was generated that allow digging deeper into the data. Each question will be turned into a button that the user can click to generate a new SQL query so don't use 'example' type questions. Each question must have a one-to-one correspondence with an instantiated SQL query."
356
+ + self._response_language()
357
+ ),
358
+ ]
359
+
360
+ llm_response = self.submit_prompt(message_log, **kwargs)
361
+
362
+ numbers_removed = re.sub(r"^\d+\.\s*", "", llm_response, flags=re.MULTILINE)
363
+ return numbers_removed.split("\n")
364
+
365
+ def generate_questions(self, **kwargs) -> List[str]:
366
+ """
367
+ **Example:**
368
+ ```python
369
+ vn.generate_questions()
370
+ ```
371
+
372
+ Generate a list of questions that you can ask Vanna.AI.
373
+ """
374
+ question_sql = self.get_similar_question_sql(question="", **kwargs)
375
+
376
+ return [q["question"] for q in question_sql]
377
+
378
+ def generate_summary(self, question: str, df: pd.DataFrame, **kwargs) -> str:
379
+ """
380
+ **Example:**
381
+ ```python
382
+ vn.generate_summary("What are the top 10 customers by sales?", df)
383
+ ```
384
+
385
+ Generate a summary of the results of a SQL query.
386
+
387
+ Args:
388
+ question (str): The question that was asked.
389
+ df (pd.DataFrame): The results of the SQL query.
390
+
391
+ Returns:
392
+ str: The summary of the results of the SQL query.
393
+ """
394
+
395
+ message_log = [
396
+ self.system_message(
397
+ f"You are a helpful data assistant. The user asked the question: '{question}'\n\nThe following is a pandas DataFrame with the results of the query: \n{df.to_markdown()}\n\n"
398
+ ),
399
+ self.user_message(
400
+ "Briefly summarize the data based on the question that was asked. Do not respond with any additional explanation beyond the summary."
401
+ + self._response_language()
402
+ ),
403
+ ]
404
+
405
+ summary = self.submit_prompt(message_log, **kwargs)
406
+
407
+ return summary
408
+
409
+ # ----------------- Use Any Embeddings API ----------------- #
410
+ @abstractmethod
411
+ def generate_embedding(self, data: str, **kwargs) -> List[float]:
412
+ pass
413
+
414
+ # ----------------- Use Any Database to Store and Retrieve Context ----------------- #
415
+ @abstractmethod
416
+ def get_similar_question_sql(self, question: str, **kwargs) -> list:
417
+ """
418
+ This method is used to get similar questions and their corresponding SQL statements.
419
+
420
+ Args:
421
+ question (str): The question to get similar questions and their corresponding SQL statements for.
422
+
423
+ Returns:
424
+ list: A list of similar questions and their corresponding SQL statements.
425
+ """
426
+ pass
427
+
428
+ @abstractmethod
429
+ def get_related_ddl(self, question: str, **kwargs) -> list:
430
+ """
431
+ This method is used to get related DDL statements to a question.
432
+
433
+ Args:
434
+ question (str): The question to get related DDL statements for.
435
+
436
+ Returns:
437
+ list: A list of related DDL statements.
438
+ """
439
+ pass
440
+
441
+ @abstractmethod
442
+ def get_related_documentation(self, question: str, **kwargs) -> list:
443
+ """
444
+ This method is used to get related documentation to a question.
445
+
446
+ Args:
447
+ question (str): The question to get related documentation for.
448
+
449
+ Returns:
450
+ list: A list of related documentation.
451
+ """
452
+ pass
453
+
454
+ @abstractmethod
455
+ def add_question_sql(self, question: str, sql: str, **kwargs) -> str:
456
+ """
457
+ This method is used to add a question and its corresponding SQL query to the training data.
458
+
459
+ Args:
460
+ question (str): The question to add.
461
+ sql (str): The SQL query to add.
462
+
463
+ Returns:
464
+ str: The ID of the training data that was added.
465
+ """
466
+ pass
467
+
468
+ @abstractmethod
469
+ def add_ddl(self, ddl: str, **kwargs) -> str:
470
+ """
471
+ This method is used to add a DDL statement to the training data.
472
+
473
+ Args:
474
+ ddl (str): The DDL statement to add.
475
+
476
+ Returns:
477
+ str: The ID of the training data that was added.
478
+ """
479
+ pass
480
+
481
+ @abstractmethod
482
+ def add_documentation(self, documentation: str, **kwargs) -> str:
483
+ """
484
+ This method is used to add documentation to the training data.
485
+
486
+ Args:
487
+ documentation (str): The documentation to add.
488
+
489
+ Returns:
490
+ str: The ID of the training data that was added.
491
+ """
492
+ pass
493
+
494
+ @abstractmethod
495
+ def get_training_data(self, **kwargs) -> pd.DataFrame:
496
+ """
497
+ Example:
498
+ ```python
499
+ vn.get_training_data()
500
+ ```
501
+
502
+ This method is used to get all the training data from the retrieval layer.
503
+
504
+ Returns:
505
+ pd.DataFrame: The training data.
506
+ """
507
+ pass
508
+
509
+ @abstractmethod
510
+ def remove_training_data(self, id: str, **kwargs) -> bool:
511
+ """
512
+ Example:
513
+ ```python
514
+ vn.remove_training_data(id="123-ddl")
515
+ ```
516
+
517
+ This method is used to remove training data from the retrieval layer.
518
+
519
+ Args:
520
+ id (str): The ID of the training data to remove.
521
+
522
+ Returns:
523
+ bool: True if the training data was removed, False otherwise.
524
+ """
525
+ pass
526
+
527
+ # ----------------- Use Any Language Model API ----------------- #
528
+
529
+ @abstractmethod
530
+ def system_message(self, message: str) -> any:
531
+ pass
532
+
533
+ @abstractmethod
534
+ def user_message(self, message: str) -> any:
535
+ pass
536
+
537
+ @abstractmethod
538
+ def assistant_message(self, message: str) -> any:
539
+ pass
540
+
541
+ def str_to_approx_token_count(self, string: str) -> int:
542
+ return len(string) / 4
543
+
544
+ def add_ddl_to_prompt(
545
+ self, initial_prompt: str, ddl_list: list[str], max_tokens: int = 14000
546
+ ) -> str:
547
+ if len(ddl_list) > 0:
548
+ initial_prompt += "\n===Tables \n"
549
+
550
+ for ddl in ddl_list:
551
+ if (
552
+ self.str_to_approx_token_count(initial_prompt)
553
+ + self.str_to_approx_token_count(ddl)
554
+ < max_tokens
555
+ ):
556
+ initial_prompt += f"{ddl}\n\n"
557
+
558
+ return initial_prompt
559
+
560
+ def add_documentation_to_prompt(
561
+ self,
562
+ initial_prompt: str,
563
+ documentation_list: list[str],
564
+ max_tokens: int = 14000,
565
+ ) -> str:
566
+ if len(documentation_list) > 0:
567
+ initial_prompt += "\n===Additional Context \n\n"
568
+
569
+ for documentation in documentation_list:
570
+ if (
571
+ self.str_to_approx_token_count(initial_prompt)
572
+ + self.str_to_approx_token_count(documentation)
573
+ < max_tokens
574
+ ):
575
+ initial_prompt += f"{documentation}\n\n"
576
+
577
+ return initial_prompt
578
+
579
+ def add_sql_to_prompt(
580
+ self, initial_prompt: str, sql_list: list[str], max_tokens: int = 14000
581
+ ) -> str:
582
+ if len(sql_list) > 0:
583
+ initial_prompt += "\n===Question-SQL Pairs\n\n"
584
+
585
+ for question in sql_list:
586
+ if (
587
+ self.str_to_approx_token_count(initial_prompt)
588
+ + self.str_to_approx_token_count(question["sql"])
589
+ < max_tokens
590
+ ):
591
+ initial_prompt += f"{question['question']}\n{question['sql']}\n\n"
592
+
593
+ return initial_prompt
594
+
595
+ def get_sql_prompt(
596
+ self,
597
+ initial_prompt: str,
598
+ question: str,
599
+ question_sql_list: list,
600
+ ddl_list: list,
601
+ doc_list: list,
602
+ **kwargs,
603
+ ):
604
+ """
605
+ Example:
606
+ ```python
607
+ vn.get_sql_prompt(
608
+ question="What are the top 10 customers by sales?",
609
+ question_sql_list=[{"question": "What are the top 10 customers by sales?", "sql": "SELECT * FROM customers ORDER BY sales DESC LIMIT 10"}],
610
+ ddl_list=["CREATE TABLE customers (id INT, name TEXT, sales DECIMAL)"],
611
+ doc_list=["The customers table contains information about customers and their sales."],
612
+ )
613
+
614
+ ```
615
+
616
+ This method is used to generate a prompt for the LLM to generate SQL.
617
+
618
+ Args:
619
+ question (str): The question to generate SQL for.
620
+ question_sql_list (list): A list of questions and their corresponding SQL statements.
621
+ ddl_list (list): A list of DDL statements.
622
+ doc_list (list): A list of documentation.
623
+
624
+ Returns:
625
+ any: The prompt for the LLM to generate SQL.
626
+ """
627
+
628
+ if initial_prompt is None:
629
+ initial_prompt = (
630
+ f"You are a {self.dialect} expert. "
631
+ + "Please help to generate a SQL query to answer the question. Your response should ONLY be based on the given context and follow the response guidelines and format instructions. "
632
+ )
633
+
634
+ initial_prompt = self.add_ddl_to_prompt(
635
+ initial_prompt, ddl_list, max_tokens=self.max_tokens
636
+ )
637
+
638
+ if self.static_documentation != "":
639
+ doc_list.append(self.static_documentation)
640
+
641
+ initial_prompt = self.add_documentation_to_prompt(
642
+ initial_prompt, doc_list, max_tokens=self.max_tokens
643
+ )
644
+
645
+ initial_prompt += (
646
+ "===Response Guidelines \n"
647
+ "1. If the provided context is sufficient, please generate a valid SQL query without any explanations for the question. \n"
648
+ "2. If the provided context is almost sufficient but requires knowledge of a specific string in a particular column, please generate an intermediate SQL query to find the distinct strings in that column. Prepend the query with a comment saying intermediate_sql \n"
649
+ "3. If the provided context is insufficient, please explain why it can't be generated. \n"
650
+ "4. Please use the most relevant table(s). \n"
651
+ "5. If the question has been asked and answered before, please repeat the answer exactly as it was given before. \n"
652
+ f"6. Ensure that the output SQL is {self.dialect}-compliant and executable, and free of syntax errors. \n"
653
+ )
654
+
655
+ message_log = [self.system_message(initial_prompt)]
656
+
657
+ for example in question_sql_list:
658
+ if example is None:
659
+ print("example is None")
660
+ else:
661
+ if example is not None and "question" in example and "sql" in example:
662
+ message_log.append(self.user_message(example["question"]))
663
+ message_log.append(self.assistant_message(example["sql"]))
664
+
665
+ message_log.append(self.user_message(question))
666
+
667
+ return message_log
668
+
669
+ def get_followup_questions_prompt(
670
+ self,
671
+ question: str,
672
+ question_sql_list: list,
673
+ ddl_list: list,
674
+ doc_list: list,
675
+ **kwargs,
676
+ ) -> list:
677
+ initial_prompt = f"The user initially asked the question: '{question}': \n\n"
678
+
679
+ initial_prompt = self.add_ddl_to_prompt(
680
+ initial_prompt, ddl_list, max_tokens=self.max_tokens
681
+ )
682
+
683
+ initial_prompt = self.add_documentation_to_prompt(
684
+ initial_prompt, doc_list, max_tokens=self.max_tokens
685
+ )
686
+
687
+ initial_prompt = self.add_sql_to_prompt(
688
+ initial_prompt, question_sql_list, max_tokens=self.max_tokens
689
+ )
690
+
691
+ message_log = [self.system_message(initial_prompt)]
692
+ message_log.append(
693
+ self.user_message(
694
+ "Generate a list of followup questions that the user might ask about this data. Respond with a list of questions, one per line. Do not answer with any explanations -- just the questions."
695
+ )
696
+ )
697
+
698
+ return message_log
699
+
700
+ @abstractmethod
701
+ def submit_prompt(self, prompt, **kwargs) -> str:
702
+ """
703
+ Example:
704
+ ```python
705
+ vn.submit_prompt(
706
+ [
707
+ vn.system_message("The user will give you SQL and you will try to guess what the business question this query is answering. Return just the question without any additional explanation. Do not reference the table name in the question."),
708
+ vn.user_message("What are the top 10 customers by sales?"),
709
+ ]
710
+ )
711
+ ```
712
+
713
+ This method is used to submit a prompt to the LLM.
714
+
715
+ Args:
716
+ prompt (any): The prompt to submit to the LLM.
717
+
718
+ Returns:
719
+ str: The response from the LLM.
720
+ """
721
+ pass
722
+
723
+ def generate_question(self, sql: str, **kwargs) -> str:
724
+ response = self.submit_prompt(
725
+ [
726
+ self.system_message(
727
+ "The user will give you SQL and you will try to guess what the business question this query is answering. Return just the question without any additional explanation. Do not reference the table name in the question."
728
+ ),
729
+ self.user_message(sql),
730
+ ],
731
+ **kwargs,
732
+ )
733
+
734
+ return response
735
+
736
+ def _extract_python_code(self, markdown_string: str) -> str:
737
+ # Strip whitespace to avoid indentation errors in LLM-generated code
738
+ markdown_string = markdown_string.strip()
739
+
740
+ # Regex pattern to match Python code blocks
741
+ pattern = r"```[\w\s]*python\n([\s\S]*?)```|```([\s\S]*?)```"
742
+
743
+ # Find all matches in the markdown string
744
+ matches = re.findall(pattern, markdown_string, re.IGNORECASE)
745
+
746
+ # Extract the Python code from the matches
747
+ python_code = []
748
+ for match in matches:
749
+ python = match[0] if match[0] else match[1]
750
+ python_code.append(python.strip())
751
+
752
+ if len(python_code) == 0:
753
+ return markdown_string
754
+
755
+ return python_code[0]
756
+
757
+ def _sanitize_plotly_code(self, raw_plotly_code: str) -> str:
758
+ # Remove the fig.show() statement from the plotly code
759
+ plotly_code = raw_plotly_code.replace("fig.show()", "")
760
+
761
+ return plotly_code
762
+
763
+ def generate_plotly_code(
764
+ self, question: str = None, sql: str = None, df_metadata: str = None, **kwargs
765
+ ) -> str:
766
+ if question is not None:
767
+ system_msg = f"The following is a pandas DataFrame that contains the results of the query that answers the question the user asked: '{question}'"
768
+ else:
769
+ system_msg = "The following is a pandas DataFrame "
770
+
771
+ if sql is not None:
772
+ system_msg += f"\n\nThe DataFrame was produced using this query: {sql}\n\n"
773
+
774
+ system_msg += f"The following is information about the resulting pandas DataFrame 'df': \n{df_metadata}"
775
+
776
+ message_log = [
777
+ self.system_message(system_msg),
778
+ self.user_message(
779
+ "Can you generate the Python plotly code to chart the results of the dataframe? Assume the data is in a pandas dataframe called 'df'. If there is only one value in the dataframe, use an Indicator. Respond with only Python code. Do not answer with any explanations -- just the code."
780
+ ),
781
+ ]
782
+
783
+ plotly_code = self.submit_prompt(message_log, kwargs=kwargs)
784
+
785
+ return self._sanitize_plotly_code(self._extract_python_code(plotly_code))
786
+
787
+ # ----------------- Connect to Any Database to run the Generated SQL ----------------- #
788
+
789
+ def connect_to_snowflake(
790
+ self,
791
+ account: str,
792
+ username: str,
793
+ password: str,
794
+ database: str,
795
+ role: Union[str, None] = None,
796
+ warehouse: Union[str, None] = None,
797
+ **kwargs,
798
+ ):
799
+ try:
800
+ snowflake = __import__("snowflake.connector")
801
+ except ImportError:
802
+ raise DependencyError(
803
+ "You need to install required dependencies to execute this method, run command:"
804
+ " \npip install asksql[snowflake]"
805
+ )
806
+
807
+ if username == "my-username":
808
+ username_env = os.getenv("SNOWFLAKE_USERNAME")
809
+
810
+ if username_env is not None:
811
+ username = username_env
812
+ else:
813
+ raise ImproperlyConfigured("Please set your Snowflake username.")
814
+
815
+ if password == "mypassword":
816
+ password_env = os.getenv("SNOWFLAKE_PASSWORD")
817
+
818
+ if password_env is not None:
819
+ password = password_env
820
+ else:
821
+ raise ImproperlyConfigured("Please set your Snowflake password.")
822
+
823
+ if account == "my-account":
824
+ account_env = os.getenv("SNOWFLAKE_ACCOUNT")
825
+
826
+ if account_env is not None:
827
+ account = account_env
828
+ else:
829
+ raise ImproperlyConfigured("Please set your Snowflake account.")
830
+
831
+ if database == "my-database":
832
+ database_env = os.getenv("SNOWFLAKE_DATABASE")
833
+
834
+ if database_env is not None:
835
+ database = database_env
836
+ else:
837
+ raise ImproperlyConfigured("Please set your Snowflake database.")
838
+
839
+ conn = snowflake.connector.connect(
840
+ user=username,
841
+ password=password,
842
+ account=account,
843
+ database=database,
844
+ client_session_keep_alive=True,
845
+ **kwargs,
846
+ )
847
+
848
+ def run_sql_snowflake(sql: str) -> pd.DataFrame:
849
+ cs = conn.cursor()
850
+
851
+ if role is not None:
852
+ cs.execute(f"USE ROLE {role}")
853
+
854
+ if warehouse is not None:
855
+ cs.execute(f"USE WAREHOUSE {warehouse}")
856
+ cs.execute(f"USE DATABASE {database}")
857
+
858
+ cur = cs.execute(sql)
859
+
860
+ results = cur.fetchall()
861
+
862
+ # Create a pandas dataframe from the results
863
+ df = pd.DataFrame(results, columns=[desc[0] for desc in cur.description])
864
+
865
+ return df
866
+
867
+ self.dialect = "Snowflake SQL"
868
+ self.run_sql = run_sql_snowflake
869
+ self.run_sql_is_set = True
870
+
871
+ def connect_to_sqlite(self, url: str, check_same_thread: bool = False, **kwargs):
872
+ """
873
+ Connect to a SQLite database. This is just a helper function to set [`vn.run_sql`][vanna.base.base.VannaBase.run_sql]
874
+
875
+ Args:
876
+ url (str): The URL of the database to connect to.
877
+ check_same_thread (str): Allow the connection may be accessed in multiple threads.
878
+ Returns:
879
+ None
880
+ """
881
+
882
+ # URL of the database to download
883
+
884
+ # Path to save the downloaded database
885
+ path = os.path.basename(urlparse(url).path)
886
+
887
+ # Download the database if it doesn't exist
888
+ if not os.path.exists(url):
889
+ response = requests.get(url)
890
+ response.raise_for_status() # Check that the request was successful
891
+ with open(path, "wb") as f:
892
+ f.write(response.content)
893
+ url = path
894
+
895
+ # Connect to the database
896
+ conn = sqlite3.connect(url, check_same_thread=check_same_thread, **kwargs)
897
+
898
+ def run_sql_sqlite(sql: str):
899
+ return pd.read_sql_query(sql, conn)
900
+
901
+ self.dialect = "SQLite"
902
+ self.run_sql = run_sql_sqlite
903
+ self.run_sql_is_set = True
904
+
905
+ def connect_to_postgres(
906
+ self,
907
+ host: str = None,
908
+ dbname: str = None,
909
+ user: str = None,
910
+ password: str = None,
911
+ port: int = None,
912
+ **kwargs,
913
+ ):
914
+ """
915
+ Connect to postgres using the psycopg2 connector. This is just a helper function to set [`vn.run_sql`][vanna.base.base.VannaBase.run_sql]
916
+ **Example:**
917
+ ```python
918
+ vn.connect_to_postgres(
919
+ host="myhost",
920
+ dbname="mydatabase",
921
+ user="myuser",
922
+ password="mypassword",
923
+ port=5432
924
+ )
925
+ ```
926
+ Args:
927
+ host (str): The postgres host.
928
+ dbname (str): The postgres database name.
929
+ user (str): The postgres user.
930
+ password (str): The postgres password.
931
+ port (int): The postgres Port.
932
+ """
933
+
934
+ try:
935
+ import psycopg2
936
+ import psycopg2.extras
937
+ except ImportError:
938
+ raise DependencyError(
939
+ "You need to install required dependencies to execute this method,"
940
+ " run command: \npip install asksql[postgres]"
941
+ )
942
+
943
+ if not host:
944
+ host = os.getenv("HOST")
945
+
946
+ if not host:
947
+ raise ImproperlyConfigured("Please set your postgres host")
948
+
949
+ if not dbname:
950
+ dbname = os.getenv("DATABASE")
951
+
952
+ if not dbname:
953
+ raise ImproperlyConfigured("Please set your postgres database")
954
+
955
+ if not user:
956
+ user = os.getenv("PG_USER")
957
+
958
+ if not user:
959
+ raise ImproperlyConfigured("Please set your postgres user")
960
+
961
+ if not password:
962
+ password = os.getenv("PASSWORD")
963
+
964
+ if not password:
965
+ raise ImproperlyConfigured("Please set your postgres password")
966
+
967
+ if not port:
968
+ port = os.getenv("PORT")
969
+
970
+ if not port:
971
+ raise ImproperlyConfigured("Please set your postgres port")
972
+
973
+ conn = None
974
+
975
+ try:
976
+ conn = psycopg2.connect(
977
+ host=host,
978
+ dbname=dbname,
979
+ user=user,
980
+ password=password,
981
+ port=port,
982
+ **kwargs,
983
+ )
984
+ except psycopg2.Error as e:
985
+ raise ValidationError(e)
986
+
987
+ def connect_to_db():
988
+ return psycopg2.connect(
989
+ host=host,
990
+ dbname=dbname,
991
+ user=user,
992
+ password=password,
993
+ port=port,
994
+ **kwargs,
995
+ )
996
+
997
+ def run_sql_postgres(sql: str) -> Union[pd.DataFrame, None]:
998
+ conn = None
999
+ try:
1000
+ conn = connect_to_db() # Initial connection attempt
1001
+ cs = conn.cursor()
1002
+ cs.execute(sql)
1003
+ results = cs.fetchall()
1004
+
1005
+ # Create a pandas dataframe from the results
1006
+ df = pd.DataFrame(results, columns=[desc[0] for desc in cs.description])
1007
+ return df
1008
+
1009
+ except psycopg2.InterfaceError as e:
1010
+ # Attempt to reconnect and retry the operation
1011
+ if conn:
1012
+ conn.close() # Ensure any existing connection is closed
1013
+ conn = connect_to_db()
1014
+ cs = conn.cursor()
1015
+ cs.execute(sql)
1016
+ results = cs.fetchall()
1017
+
1018
+ # Create a pandas dataframe from the results
1019
+ df = pd.DataFrame(results, columns=[desc[0] for desc in cs.description])
1020
+ return df
1021
+
1022
+ except psycopg2.Error as e:
1023
+ if conn:
1024
+ conn.rollback()
1025
+ raise ValidationError(e)
1026
+
1027
+ except Exception as e:
1028
+ conn.rollback()
1029
+ raise e
1030
+
1031
+ self.dialect = "PostgreSQL"
1032
+ self.run_sql_is_set = True
1033
+ self.run_sql = run_sql_postgres
1034
+
1035
+ def connect_to_mysql(
1036
+ self,
1037
+ host: str = None,
1038
+ dbname: str = None,
1039
+ user: str = None,
1040
+ password: str = None,
1041
+ port: int = None,
1042
+ **kwargs,
1043
+ ):
1044
+ try:
1045
+ import pymysql.cursors
1046
+ except ImportError:
1047
+ raise DependencyError(
1048
+ "You need to install required dependencies to execute this method,"
1049
+ " run command: \npip install PyMySQL"
1050
+ )
1051
+
1052
+ if not host:
1053
+ host = os.getenv("HOST")
1054
+
1055
+ if not host:
1056
+ raise ImproperlyConfigured("Please set your MySQL host")
1057
+
1058
+ if not dbname:
1059
+ dbname = os.getenv("DATABASE")
1060
+
1061
+ if not dbname:
1062
+ raise ImproperlyConfigured("Please set your MySQL database")
1063
+
1064
+ if not user:
1065
+ user = os.getenv("USER")
1066
+
1067
+ if not user:
1068
+ raise ImproperlyConfigured("Please set your MySQL user")
1069
+
1070
+ if not password:
1071
+ password = os.getenv("PASSWORD")
1072
+
1073
+ if not password:
1074
+ raise ImproperlyConfigured("Please set your MySQL password")
1075
+
1076
+ if not port:
1077
+ port = os.getenv("PORT")
1078
+
1079
+ if not port:
1080
+ raise ImproperlyConfigured("Please set your MySQL port")
1081
+
1082
+ conn = None
1083
+
1084
+ try:
1085
+ conn = pymysql.connect(
1086
+ host=host,
1087
+ user=user,
1088
+ password=password,
1089
+ database=dbname,
1090
+ port=port,
1091
+ cursorclass=pymysql.cursors.DictCursor,
1092
+ **kwargs,
1093
+ )
1094
+ except pymysql.Error as e:
1095
+ raise ValidationError(e)
1096
+
1097
+ def run_sql_mysql(sql: str) -> Union[pd.DataFrame, None]:
1098
+ if conn:
1099
+ try:
1100
+ conn.ping(reconnect=True)
1101
+ cs = conn.cursor()
1102
+ cs.execute(sql)
1103
+ results = cs.fetchall()
1104
+
1105
+ # Create a pandas dataframe from the results
1106
+ df = pd.DataFrame(
1107
+ results, columns=[desc[0] for desc in cs.description]
1108
+ )
1109
+ return df
1110
+
1111
+ except pymysql.Error as e:
1112
+ conn.rollback()
1113
+ raise ValidationError(e)
1114
+
1115
+ except Exception as e:
1116
+ conn.rollback()
1117
+ raise e
1118
+
1119
+ self.run_sql_is_set = True
1120
+ self.run_sql = run_sql_mysql
1121
+
1122
+ def connect_to_clickhouse(
1123
+ self,
1124
+ host: str = None,
1125
+ dbname: str = None,
1126
+ user: str = None,
1127
+ password: str = None,
1128
+ port: int = None,
1129
+ **kwargs,
1130
+ ):
1131
+ try:
1132
+ import clickhouse_connect
1133
+ except ImportError:
1134
+ raise DependencyError(
1135
+ "You need to install required dependencies to execute this method,"
1136
+ " run command: \npip install clickhouse_connect"
1137
+ )
1138
+
1139
+ if not host:
1140
+ host = os.getenv("HOST")
1141
+
1142
+ if not host:
1143
+ raise ImproperlyConfigured("Please set your ClickHouse host")
1144
+
1145
+ if not dbname:
1146
+ dbname = os.getenv("DATABASE")
1147
+
1148
+ if not dbname:
1149
+ raise ImproperlyConfigured("Please set your ClickHouse database")
1150
+
1151
+ if not user:
1152
+ user = os.getenv("USER")
1153
+
1154
+ if not user:
1155
+ raise ImproperlyConfigured("Please set your ClickHouse user")
1156
+
1157
+ if not password:
1158
+ password = os.getenv("PASSWORD")
1159
+
1160
+ if not password:
1161
+ raise ImproperlyConfigured("Please set your ClickHouse password")
1162
+
1163
+ if not port:
1164
+ port = os.getenv("PORT")
1165
+
1166
+ if not port:
1167
+ raise ImproperlyConfigured("Please set your ClickHouse port")
1168
+
1169
+ conn = None
1170
+
1171
+ try:
1172
+ conn = clickhouse_connect.get_client(
1173
+ host=host,
1174
+ port=port,
1175
+ username=user,
1176
+ password=password,
1177
+ database=dbname,
1178
+ **kwargs,
1179
+ )
1180
+ print(conn)
1181
+ except Exception as e:
1182
+ raise ValidationError(e)
1183
+
1184
+ def run_sql_clickhouse(sql: str) -> Union[pd.DataFrame, None]:
1185
+ if conn:
1186
+ try:
1187
+ result = conn.query(sql)
1188
+ results = result.result_rows
1189
+
1190
+ # Create a pandas dataframe from the results
1191
+ df = pd.DataFrame(results, columns=result.column_names)
1192
+ return df
1193
+
1194
+ except Exception as e:
1195
+ raise e
1196
+
1197
+ self.run_sql_is_set = True
1198
+ self.run_sql = run_sql_clickhouse
1199
+
1200
+ def connect_to_oracle(
1201
+ self, user: str = None, password: str = None, dsn: str = None, **kwargs
1202
+ ):
1203
+ """
1204
+ Connect to an Oracle db using oracledb package. This is just a helper function to set [`vn.run_sql`][vanna.base.base.VannaBase.run_sql]
1205
+ **Example:**
1206
+ ```python
1207
+ vn.connect_to_oracle(
1208
+ user="username",
1209
+ password="password",
1210
+ dsn="host:port/sid",
1211
+ )
1212
+ ```
1213
+ Args:
1214
+ USER (str): Oracle db user name.
1215
+ PASSWORD (str): Oracle db user password.
1216
+ DSN (str): Oracle db host ip - host:port/sid.
1217
+ """
1218
+
1219
+ try:
1220
+ import oracledb
1221
+ except ImportError:
1222
+ raise DependencyError(
1223
+ "You need to install required dependencies to execute this method,"
1224
+ " run command: \npip install oracledb"
1225
+ )
1226
+
1227
+ if not dsn:
1228
+ dsn = os.getenv("DSN")
1229
+
1230
+ if not dsn:
1231
+ raise ImproperlyConfigured(
1232
+ "Please set your Oracle dsn which should include host:port/sid"
1233
+ )
1234
+
1235
+ if not user:
1236
+ user = os.getenv("USER")
1237
+
1238
+ if not user:
1239
+ raise ImproperlyConfigured("Please set your Oracle db user")
1240
+
1241
+ if not password:
1242
+ password = os.getenv("PASSWORD")
1243
+
1244
+ if not password:
1245
+ raise ImproperlyConfigured("Please set your Oracle db password")
1246
+
1247
+ conn = None
1248
+
1249
+ try:
1250
+ conn = oracledb.connect(user=user, password=password, dsn=dsn, **kwargs)
1251
+ except oracledb.Error as e:
1252
+ raise ValidationError(e)
1253
+
1254
+ def run_sql_oracle(sql: str) -> Union[pd.DataFrame, None]:
1255
+ if conn:
1256
+ try:
1257
+ sql = sql.rstrip()
1258
+ if sql.endswith(
1259
+ ";"
1260
+ ): # fix for a known problem with Oracle db where an extra ; will cause an error.
1261
+ sql = sql[:-1]
1262
+
1263
+ cs = conn.cursor()
1264
+ cs.execute(sql)
1265
+ results = cs.fetchall()
1266
+
1267
+ # Create a pandas dataframe from the results
1268
+ df = pd.DataFrame(
1269
+ results, columns=[desc[0] for desc in cs.description]
1270
+ )
1271
+ return df
1272
+
1273
+ except oracledb.Error as e:
1274
+ conn.rollback()
1275
+ raise ValidationError(e)
1276
+
1277
+ except Exception as e:
1278
+ conn.rollback()
1279
+ raise e
1280
+
1281
+ self.run_sql_is_set = True
1282
+ self.run_sql = run_sql_oracle
1283
+
1284
+ def connect_to_bigquery(
1285
+ self, cred_file_path: str = None, project_id: str = None, **kwargs
1286
+ ):
1287
+ """
1288
+ Connect to gcs using the bigquery connector. This is just a helper function to set [`vn.run_sql`][vanna.base.base.VannaBase.run_sql]
1289
+ **Example:**
1290
+ ```python
1291
+ vn.connect_to_bigquery(
1292
+ project_id="myprojectid",
1293
+ cred_file_path="path/to/credentials.json",
1294
+ )
1295
+ ```
1296
+ Args:
1297
+ project_id (str): The gcs project id.
1298
+ cred_file_path (str): The gcs credential file path
1299
+ """
1300
+
1301
+ try:
1302
+ from google.api_core.exceptions import GoogleAPIError
1303
+ from google.cloud import bigquery
1304
+ from google.oauth2 import service_account
1305
+ except ImportError:
1306
+ raise DependencyError(
1307
+ "You need to install required dependencies to execute this method, run command:"
1308
+ " \npip install asksql[bigquery]"
1309
+ )
1310
+
1311
+ if not project_id:
1312
+ project_id = os.getenv("PROJECT_ID")
1313
+
1314
+ if not project_id:
1315
+ raise ImproperlyConfigured("Please set your Google Cloud Project ID.")
1316
+
1317
+ import sys
1318
+
1319
+ if "google.colab" in sys.modules:
1320
+ try:
1321
+ from google.colab import auth
1322
+
1323
+ auth.authenticate_user()
1324
+ except Exception as e:
1325
+ raise ImproperlyConfigured(e)
1326
+ else:
1327
+ print("Not using Google Colab.")
1328
+
1329
+ conn = None
1330
+
1331
+ if not cred_file_path:
1332
+ try:
1333
+ conn = bigquery.Client(project=project_id)
1334
+ except Exception:
1335
+ print("Could not found any google cloud implicit credentials")
1336
+ else:
1337
+ # Validate file path and pemissions
1338
+ validate_config_path(cred_file_path)
1339
+
1340
+ if not conn:
1341
+ with open(cred_file_path, "r") as f:
1342
+ credentials = service_account.Credentials.from_service_account_info(
1343
+ json.loads(f.read()),
1344
+ scopes=["https://www.googleapis.com/auth/cloud-platform"],
1345
+ )
1346
+
1347
+ try:
1348
+ conn = bigquery.Client(
1349
+ project=project_id, credentials=credentials, **kwargs
1350
+ )
1351
+ except Exception:
1352
+ raise ImproperlyConfigured(
1353
+ "Could not connect to bigquery please correct credentials"
1354
+ )
1355
+
1356
+ def run_sql_bigquery(sql: str) -> Union[pd.DataFrame, None]:
1357
+ if conn:
1358
+ job = conn.query(sql)
1359
+ df = job.result().to_dataframe()
1360
+ return df
1361
+ return None
1362
+
1363
+ self.dialect = "BigQuery SQL"
1364
+ self.run_sql_is_set = True
1365
+ self.run_sql = run_sql_bigquery
1366
+
1367
+ def connect_to_duckdb(self, url: str, init_sql: str = None, **kwargs):
1368
+ """
1369
+ Connect to a DuckDB database. This is just a helper function to set [`vn.run_sql`][vanna.base.base.VannaBase.run_sql]
1370
+
1371
+ Args:
1372
+ url (str): The URL of the database to connect to. Use :memory: to create an in-memory database. Use md: or motherduck: to use the MotherDuck database.
1373
+ init_sql (str, optional): SQL to run when connecting to the database. Defaults to None.
1374
+
1375
+ Returns:
1376
+ None
1377
+ """
1378
+ try:
1379
+ import duckdb
1380
+ except ImportError:
1381
+ raise DependencyError(
1382
+ "You need to install required dependencies to execute this method,"
1383
+ " run command: \npip install asksql[duckdb]"
1384
+ )
1385
+ # URL of the database to download
1386
+ if url == ":memory:" or url == "":
1387
+ path = ":memory:"
1388
+ else:
1389
+ # Path to save the downloaded database
1390
+ print(os.path.exists(url))
1391
+ if os.path.exists(url):
1392
+ path = url
1393
+ elif url.startswith("md") or url.startswith("motherduck"):
1394
+ path = url
1395
+ else:
1396
+ path = os.path.basename(urlparse(url).path)
1397
+ # Download the database if it doesn't exist
1398
+ if not os.path.exists(path):
1399
+ response = requests.get(url)
1400
+ response.raise_for_status() # Check that the request was successful
1401
+ with open(path, "wb") as f:
1402
+ f.write(response.content)
1403
+
1404
+ # Connect to the database
1405
+ conn = duckdb.connect(path, **kwargs)
1406
+ if init_sql:
1407
+ conn.query(init_sql)
1408
+
1409
+ def run_sql_duckdb(sql: str):
1410
+ return conn.query(sql).to_df()
1411
+
1412
+ self.dialect = "DuckDB SQL"
1413
+ self.run_sql = run_sql_duckdb
1414
+ self.run_sql_is_set = True
1415
+
1416
+ def connect_to_mssql(self, odbc_conn_str: str, **kwargs):
1417
+ """
1418
+ Connect to a Microsoft SQL Server database. This is just a helper function to set [`vn.run_sql`][vanna.base.base.VannaBase.run_sql]
1419
+
1420
+ Args:
1421
+ odbc_conn_str (str): The ODBC connection string.
1422
+
1423
+ Returns:
1424
+ None
1425
+ """
1426
+ try:
1427
+ import pyodbc
1428
+ except ImportError:
1429
+ raise DependencyError(
1430
+ "You need to install required dependencies to execute this method,"
1431
+ " run command: pip install pyodbc"
1432
+ )
1433
+
1434
+ try:
1435
+ import sqlalchemy as sa
1436
+ from sqlalchemy.engine import URL
1437
+ except ImportError:
1438
+ raise DependencyError(
1439
+ "You need to install required dependencies to execute this method,"
1440
+ " run command: pip install sqlalchemy"
1441
+ )
1442
+
1443
+ connection_url = URL.create(
1444
+ "mssql+pyodbc", query={"odbc_connect": odbc_conn_str}
1445
+ )
1446
+
1447
+ from sqlalchemy import create_engine
1448
+
1449
+ engine = create_engine(connection_url, **kwargs)
1450
+
1451
+ def run_sql_mssql(sql: str):
1452
+ # Execute the SQL statement and return the result as a pandas DataFrame
1453
+ with engine.begin() as conn:
1454
+ df = pd.read_sql_query(sa.text(sql), conn)
1455
+ conn.close()
1456
+ return df
1457
+
1458
+ raise Exception("Couldn't run sql")
1459
+
1460
+ self.dialect = "T-SQL / Microsoft SQL Server"
1461
+ self.run_sql = run_sql_mssql
1462
+ self.run_sql_is_set = True
1463
+
1464
+ def connect_to_presto(
1465
+ self,
1466
+ host: str,
1467
+ catalog: str = "hive",
1468
+ schema: str = "default",
1469
+ user: str = None,
1470
+ password: str = None,
1471
+ port: int = None,
1472
+ combined_pem_path: str = None,
1473
+ protocol: str = "https",
1474
+ requests_kwargs: dict = None,
1475
+ **kwargs,
1476
+ ):
1477
+ """
1478
+ Connect to a Presto database using the specified parameters.
1479
+
1480
+ Args:
1481
+ host (str): The host address of the Presto database.
1482
+ catalog (str): The catalog to use in the Presto environment.
1483
+ schema (str): The schema to use in the Presto environment.
1484
+ user (str): The username for authentication.
1485
+ password (str): The password for authentication.
1486
+ port (int): The port number for the Presto connection.
1487
+ combined_pem_path (str): The path to the combined pem file for SSL connection.
1488
+ protocol (str): The protocol to use for the connection (default is 'https').
1489
+ requests_kwargs (dict): Additional keyword arguments for requests.
1490
+
1491
+ Raises:
1492
+ DependencyError: If required dependencies are not installed.
1493
+ ImproperlyConfigured: If essential configuration settings are missing.
1494
+
1495
+ Returns:
1496
+ None
1497
+ """
1498
+ try:
1499
+ from pyhive import presto
1500
+ except ImportError:
1501
+ raise DependencyError(
1502
+ "You need to install required dependencies to execute this method,"
1503
+ " run command: \npip install pyhive"
1504
+ )
1505
+
1506
+ if not host:
1507
+ host = os.getenv("PRESTO_HOST")
1508
+
1509
+ if not host:
1510
+ raise ImproperlyConfigured("Please set your presto host")
1511
+
1512
+ if not catalog:
1513
+ catalog = os.getenv("PRESTO_CATALOG")
1514
+
1515
+ if not catalog:
1516
+ raise ImproperlyConfigured("Please set your presto catalog")
1517
+
1518
+ if not user:
1519
+ user = os.getenv("PRESTO_USER")
1520
+
1521
+ if not user:
1522
+ raise ImproperlyConfigured("Please set your presto user")
1523
+
1524
+ if not password:
1525
+ password = os.getenv("PRESTO_PASSWORD")
1526
+
1527
+ if not port:
1528
+ port = os.getenv("PRESTO_PORT")
1529
+
1530
+ if not port:
1531
+ raise ImproperlyConfigured("Please set your presto port")
1532
+
1533
+ conn = None
1534
+
1535
+ try:
1536
+ if requests_kwargs is None and combined_pem_path is not None:
1537
+ # use the combined pem file to verify the SSL connection
1538
+ requests_kwargs = {
1539
+ "verify": combined_pem_path, # 使用转换后得到的 PEM 文件进行 SSL 验证
1540
+ }
1541
+ conn = presto.Connection(
1542
+ host=host,
1543
+ username=user,
1544
+ password=password,
1545
+ catalog=catalog,
1546
+ schema=schema,
1547
+ port=port,
1548
+ protocol=protocol,
1549
+ requests_kwargs=requests_kwargs,
1550
+ **kwargs,
1551
+ )
1552
+ except presto.Error as e:
1553
+ raise ValidationError(e)
1554
+
1555
+ def run_sql_presto(sql: str) -> Union[pd.DataFrame, None]:
1556
+ if conn:
1557
+ try:
1558
+ sql = sql.rstrip()
1559
+ # fix for a known problem with presto db where an extra ; will cause an error.
1560
+ if sql.endswith(";"):
1561
+ sql = sql[:-1]
1562
+ cs = conn.cursor()
1563
+ cs.execute(sql)
1564
+ results = cs.fetchall()
1565
+
1566
+ # Create a pandas dataframe from the results
1567
+ df = pd.DataFrame(
1568
+ results, columns=[desc[0] for desc in cs.description]
1569
+ )
1570
+ return df
1571
+
1572
+ except presto.Error as e:
1573
+ print(e)
1574
+ raise ValidationError(e)
1575
+
1576
+ except Exception as e:
1577
+ print(e)
1578
+ raise e
1579
+
1580
+ self.run_sql_is_set = True
1581
+ self.run_sql = run_sql_presto
1582
+
1583
+ def connect_to_hive(
1584
+ self,
1585
+ host: str = None,
1586
+ dbname: str = "default",
1587
+ user: str = None,
1588
+ password: str = None,
1589
+ port: int = None,
1590
+ auth: str = "CUSTOM",
1591
+ **kwargs,
1592
+ ):
1593
+ """
1594
+ Connect to a Hive database. This is just a helper function to set [`vn.run_sql`][vanna.base.base.VannaBase.run_sql]
1595
+ Connect to a Hive database. This is just a helper function to set [`vn.run_sql`][vanna.base.base.VannaBase.run_sql]
1596
+
1597
+ Args:
1598
+ host (str): The host of the Hive database.
1599
+ dbname (str): The name of the database to connect to.
1600
+ user (str): The username to use for authentication.
1601
+ password (str): The password to use for authentication.
1602
+ port (int): The port to use for the connection.
1603
+ auth (str): The authentication method to use.
1604
+
1605
+ Returns:
1606
+ None
1607
+ """
1608
+
1609
+ try:
1610
+ from pyhive import hive
1611
+ except ImportError:
1612
+ raise DependencyError(
1613
+ "You need to install required dependencies to execute this method,"
1614
+ " run command: \npip install pyhive"
1615
+ )
1616
+
1617
+ if not host:
1618
+ host = os.getenv("HIVE_HOST")
1619
+
1620
+ if not host:
1621
+ raise ImproperlyConfigured("Please set your hive host")
1622
+
1623
+ if not dbname:
1624
+ dbname = os.getenv("HIVE_DATABASE")
1625
+
1626
+ if not dbname:
1627
+ raise ImproperlyConfigured("Please set your hive database")
1628
+
1629
+ if not user:
1630
+ user = os.getenv("HIVE_USER")
1631
+
1632
+ if not user:
1633
+ raise ImproperlyConfigured("Please set your hive user")
1634
+
1635
+ if not password:
1636
+ password = os.getenv("HIVE_PASSWORD")
1637
+
1638
+ if not port:
1639
+ port = os.getenv("HIVE_PORT")
1640
+
1641
+ if not port:
1642
+ raise ImproperlyConfigured("Please set your hive port")
1643
+
1644
+ conn = None
1645
+
1646
+ try:
1647
+ conn = hive.Connection(
1648
+ host=host,
1649
+ username=user,
1650
+ password=password,
1651
+ database=dbname,
1652
+ port=port,
1653
+ auth=auth,
1654
+ )
1655
+ except hive.Error as e:
1656
+ raise ValidationError(e)
1657
+
1658
+ def run_sql_hive(sql: str) -> Union[pd.DataFrame, None]:
1659
+ if conn:
1660
+ try:
1661
+ cs = conn.cursor()
1662
+ cs.execute(sql)
1663
+ results = cs.fetchall()
1664
+
1665
+ # Create a pandas dataframe from the results
1666
+ df = pd.DataFrame(
1667
+ results, columns=[desc[0] for desc in cs.description]
1668
+ )
1669
+ return df
1670
+
1671
+ except hive.Error as e:
1672
+ print(e)
1673
+ raise ValidationError(e)
1674
+
1675
+ except Exception as e:
1676
+ print(e)
1677
+ raise e
1678
+
1679
+ self.run_sql_is_set = True
1680
+ self.run_sql = run_sql_hive
1681
+
1682
+ def run_sql(self, sql: str, **kwargs) -> pd.DataFrame:
1683
+ """
1684
+ Example:
1685
+ ```python
1686
+ vn.run_sql("SELECT * FROM my_table")
1687
+ ```
1688
+
1689
+ Run a SQL query on the connected database.
1690
+
1691
+ Args:
1692
+ sql (str): The SQL query to run.
1693
+
1694
+ Returns:
1695
+ pd.DataFrame: The results of the SQL query.
1696
+ """
1697
+ raise Exception(
1698
+ "You need to connect to a database first by running vn.connect_to_snowflake(), vn.connect_to_postgres(), similar function, or manually set vn.run_sql"
1699
+ )
1700
+
1701
+ def ask(
1702
+ self,
1703
+ question: Union[str, None] = None,
1704
+ print_results: bool = True,
1705
+ auto_train: bool = True,
1706
+ visualize: bool = True, # if False, will not generate plotly code
1707
+ allow_llm_to_see_data: bool = False,
1708
+ ) -> Union[
1709
+ Tuple[
1710
+ Union[str, None],
1711
+ Union[pd.DataFrame, None],
1712
+ Union[plotly.graph_objs.Figure, None],
1713
+ ],
1714
+ None,
1715
+ ]:
1716
+ """
1717
+ **Example:**
1718
+ ```python
1719
+ vn.ask("What are the top 10 customers by sales?")
1720
+ ```
1721
+
1722
+ Ask Vanna.AI a question and get the SQL query that answers it.
1723
+
1724
+ Args:
1725
+ question (str): The question to ask.
1726
+ print_results (bool): Whether to print the results of the SQL query.
1727
+ auto_train (bool): Whether to automatically train Vanna.AI on the question and SQL query.
1728
+ visualize (bool): Whether to generate plotly code and display the plotly figure.
1729
+
1730
+ Returns:
1731
+ Tuple[str, pd.DataFrame, plotly.graph_objs.Figure]: The SQL query, the results of the SQL query, and the plotly figure.
1732
+ """
1733
+
1734
+ if question is None:
1735
+ question = input("Enter a question: ")
1736
+
1737
+ try:
1738
+ sql = self.generate_sql(
1739
+ question=question, allow_llm_to_see_data=allow_llm_to_see_data
1740
+ )
1741
+ except Exception as e:
1742
+ print(e)
1743
+ return None, None, None
1744
+
1745
+ if print_results:
1746
+ try:
1747
+ from IPython.display import Code, display
1748
+
1749
+ display(Code(sql))
1750
+ except Exception as e:
1751
+ print(sql)
1752
+
1753
+ if self.run_sql_is_set is False:
1754
+ print("If you want to run the SQL query, connect to a database first.")
1755
+
1756
+ if print_results:
1757
+ return None
1758
+ else:
1759
+ return sql, None, None
1760
+
1761
+ try:
1762
+ self._ensure_llm_sql_allowed(sql)
1763
+ df = self.run_sql(sql)
1764
+
1765
+ if print_results:
1766
+ try:
1767
+ display = __import__(
1768
+ "IPython.display", fromList=["display"]
1769
+ ).display
1770
+ display(df)
1771
+ except Exception as e:
1772
+ print(df)
1773
+
1774
+ if len(df) > 0 and auto_train:
1775
+ self.add_question_sql(question=question, sql=sql)
1776
+ # Only generate plotly code if visualize is True
1777
+ if visualize:
1778
+ try:
1779
+ plotly_code = self.generate_plotly_code(
1780
+ question=question,
1781
+ sql=sql,
1782
+ df_metadata=f"Running df.dtypes gives:\n {df.dtypes}",
1783
+ )
1784
+ fig = self.get_plotly_figure(plotly_code=plotly_code, df=df)
1785
+ if print_results:
1786
+ try:
1787
+ display = __import__(
1788
+ "IPython.display", fromlist=["display"]
1789
+ ).display
1790
+ Image = __import__(
1791
+ "IPython.display", fromlist=["Image"]
1792
+ ).Image
1793
+ img_bytes = fig.to_image(format="png", scale=2)
1794
+ display(Image(img_bytes))
1795
+ except Exception as e:
1796
+ fig.show()
1797
+ except Exception as e:
1798
+ # Print stack trace
1799
+ traceback.print_stack()
1800
+ traceback.print_exc()
1801
+ print("Couldn't run plotly code: ", e)
1802
+ if print_results:
1803
+ return None
1804
+ else:
1805
+ return sql, df, None
1806
+ else:
1807
+ return sql, df, None
1808
+
1809
+ except Exception as e:
1810
+ print("Couldn't run sql: ", e)
1811
+ if print_results:
1812
+ return None
1813
+ else:
1814
+ return sql, None, None
1815
+ return sql, df, fig
1816
+
1817
+ def train(
1818
+ self,
1819
+ question: str = None,
1820
+ sql: str = None,
1821
+ ddl: str = None,
1822
+ documentation: str = None,
1823
+ plan: TrainingPlan = None,
1824
+ ) -> str:
1825
+ """
1826
+ **Example:**
1827
+ ```python
1828
+ vn.train()
1829
+ ```
1830
+
1831
+ Train Vanna.AI on a question and its corresponding SQL query.
1832
+ If you call it with no arguments, it will check if you connected to a database and it will attempt to train on the metadata of that database.
1833
+ If you call it with the sql argument, it's equivalent to [`vn.add_question_sql()`][vanna.base.base.VannaBase.add_question_sql].
1834
+ If you call it with the ddl argument, it's equivalent to [`vn.add_ddl()`][vanna.base.base.VannaBase.add_ddl].
1835
+ If you call it with the documentation argument, it's equivalent to [`vn.add_documentation()`][vanna.base.base.VannaBase.add_documentation].
1836
+ Additionally, you can pass a [`TrainingPlan`][vanna.types.TrainingPlan] object. Get a training plan with [`vn.get_training_plan_generic()`][vanna.base.base.VannaBase.get_training_plan_generic].
1837
+
1838
+ Args:
1839
+ question (str): The question to train on.
1840
+ sql (str): The SQL query to train on.
1841
+ ddl (str): The DDL statement.
1842
+ documentation (str): The documentation to train on.
1843
+ plan (TrainingPlan): The training plan to train on.
1844
+ """
1845
+
1846
+ if question and not sql:
1847
+ raise ValidationError("Please also provide a SQL query")
1848
+
1849
+ if documentation:
1850
+ print("Adding documentation....")
1851
+ return self.add_documentation(documentation)
1852
+
1853
+ if sql:
1854
+ if question is None:
1855
+ question = self.generate_question(sql)
1856
+ print("Question generated with sql:", question, "\nAdding SQL...")
1857
+ return self.add_question_sql(question=question, sql=sql)
1858
+
1859
+ if ddl:
1860
+ print("Adding ddl:", ddl)
1861
+ return self.add_ddl(ddl)
1862
+
1863
+ if plan:
1864
+ for item in plan._plan:
1865
+ if item.item_type == TrainingPlanItem.ITEM_TYPE_DDL:
1866
+ self.add_ddl(item.item_value)
1867
+ elif item.item_type == TrainingPlanItem.ITEM_TYPE_IS:
1868
+ self.add_documentation(item.item_value)
1869
+ elif item.item_type == TrainingPlanItem.ITEM_TYPE_SQL:
1870
+ self.add_question_sql(question=item.item_name, sql=item.item_value)
1871
+
1872
+ def _get_databases(self) -> List[str]:
1873
+ try:
1874
+ print("Trying INFORMATION_SCHEMA.DATABASES")
1875
+ df_databases = self.run_sql("SELECT * FROM INFORMATION_SCHEMA.DATABASES")
1876
+ except Exception as e:
1877
+ print(e)
1878
+ try:
1879
+ print("Trying SHOW DATABASES")
1880
+ df_databases = self.run_sql("SHOW DATABASES")
1881
+ except Exception as e:
1882
+ print(e)
1883
+ return []
1884
+
1885
+ return df_databases["DATABASE_NAME"].unique().tolist()
1886
+
1887
+ def _get_information_schema_tables(self, database: str) -> pd.DataFrame:
1888
+ df_tables = self.run_sql(f"SELECT * FROM {database}.INFORMATION_SCHEMA.TABLES")
1889
+
1890
+ return df_tables
1891
+
1892
+ def get_training_plan_generic(self, df) -> TrainingPlan:
1893
+ """
1894
+ This method is used to generate a training plan from an information schema dataframe.
1895
+
1896
+ Basically what it does is breaks up INFORMATION_SCHEMA.COLUMNS into groups of table/column descriptions that can be used to pass to the LLM.
1897
+
1898
+ Args:
1899
+ df (pd.DataFrame): The dataframe to generate the training plan from.
1900
+
1901
+ Returns:
1902
+ TrainingPlan: The training plan.
1903
+ """
1904
+ # For each of the following, we look at the df columns to see if there's a match:
1905
+ database_column = df.columns[
1906
+ df.columns.str.lower().str.contains("database")
1907
+ | df.columns.str.lower().str.contains("table_catalog")
1908
+ ].to_list()[0]
1909
+ schema_column = df.columns[
1910
+ df.columns.str.lower().str.contains("table_schema")
1911
+ ].to_list()[0]
1912
+ table_column = df.columns[
1913
+ df.columns.str.lower().str.contains("table_name")
1914
+ ].to_list()[0]
1915
+ columns = [database_column, schema_column, table_column]
1916
+ candidates = ["column_name", "data_type", "comment"]
1917
+ matches = df.columns.str.lower().str.contains("|".join(candidates), regex=True)
1918
+ columns += df.columns[matches].to_list()
1919
+
1920
+ plan = TrainingPlan([])
1921
+
1922
+ for database in df[database_column].unique().tolist():
1923
+ for schema in (
1924
+ df.query(f'{database_column} == "{database}"')[schema_column]
1925
+ .unique()
1926
+ .tolist()
1927
+ ):
1928
+ for table in (
1929
+ df.query(
1930
+ f'{database_column} == "{database}" and {schema_column} == "{schema}"'
1931
+ )[table_column]
1932
+ .unique()
1933
+ .tolist()
1934
+ ):
1935
+ df_columns_filtered_to_table = df.query(
1936
+ f'{database_column} == "{database}" and {schema_column} == "{schema}" and {table_column} == "{table}"'
1937
+ )
1938
+ doc = f"The following columns are in the {table} table in the {database} database:\n\n"
1939
+ doc += df_columns_filtered_to_table[columns].to_markdown()
1940
+
1941
+ plan._plan.append(
1942
+ TrainingPlanItem(
1943
+ item_type=TrainingPlanItem.ITEM_TYPE_IS,
1944
+ item_group=f"{database}.{schema}",
1945
+ item_name=table,
1946
+ item_value=doc,
1947
+ )
1948
+ )
1949
+
1950
+ return plan
1951
+
1952
+ def get_training_plan_snowflake(
1953
+ self,
1954
+ filter_databases: Union[List[str], None] = None,
1955
+ filter_schemas: Union[List[str], None] = None,
1956
+ include_information_schema: bool = False,
1957
+ use_historical_queries: bool = True,
1958
+ ) -> TrainingPlan:
1959
+ plan = TrainingPlan([])
1960
+
1961
+ if self.run_sql_is_set is False:
1962
+ raise ImproperlyConfigured("Please connect to a database first.")
1963
+
1964
+ if use_historical_queries:
1965
+ try:
1966
+ print("Trying query history")
1967
+ df_history = self.run_sql(
1968
+ """ select * from table(information_schema.query_history(result_limit => 5000)) order by start_time"""
1969
+ )
1970
+
1971
+ df_history_filtered = df_history.query("ROWS_PRODUCED > 1")
1972
+ if filter_databases is not None:
1973
+ mask = (
1974
+ df_history_filtered["QUERY_TEXT"]
1975
+ .str.lower()
1976
+ .apply(
1977
+ lambda x: any(
1978
+ s in x for s in [s.lower() for s in filter_databases]
1979
+ )
1980
+ )
1981
+ )
1982
+ df_history_filtered = df_history_filtered[mask]
1983
+
1984
+ if filter_schemas is not None:
1985
+ mask = (
1986
+ df_history_filtered["QUERY_TEXT"]
1987
+ .str.lower()
1988
+ .apply(
1989
+ lambda x: any(
1990
+ s in x for s in [s.lower() for s in filter_schemas]
1991
+ )
1992
+ )
1993
+ )
1994
+ df_history_filtered = df_history_filtered[mask]
1995
+
1996
+ if len(df_history_filtered) > 10:
1997
+ df_history_filtered = df_history_filtered.sample(10)
1998
+
1999
+ for query in df_history_filtered["QUERY_TEXT"].unique().tolist():
2000
+ plan._plan.append(
2001
+ TrainingPlanItem(
2002
+ item_type=TrainingPlanItem.ITEM_TYPE_SQL,
2003
+ item_group="",
2004
+ item_name=self.generate_question(query),
2005
+ item_value=query,
2006
+ )
2007
+ )
2008
+
2009
+ except Exception as e:
2010
+ print(e)
2011
+
2012
+ databases = self._get_databases()
2013
+
2014
+ for database in databases:
2015
+ if filter_databases is not None and database not in filter_databases:
2016
+ continue
2017
+
2018
+ try:
2019
+ df_tables = self._get_information_schema_tables(database=database)
2020
+
2021
+ print(f"Trying INFORMATION_SCHEMA.COLUMNS for {database}")
2022
+ df_columns = self.run_sql(
2023
+ f"SELECT * FROM {database}.INFORMATION_SCHEMA.COLUMNS"
2024
+ )
2025
+
2026
+ for schema in df_tables["TABLE_SCHEMA"].unique().tolist():
2027
+ if filter_schemas is not None and schema not in filter_schemas:
2028
+ continue
2029
+
2030
+ if (
2031
+ not include_information_schema
2032
+ and schema == "INFORMATION_SCHEMA"
2033
+ ):
2034
+ continue
2035
+
2036
+ df_columns_filtered_to_schema = df_columns.query(
2037
+ f"TABLE_SCHEMA == '{schema}'"
2038
+ )
2039
+
2040
+ try:
2041
+ tables = (
2042
+ df_columns_filtered_to_schema["TABLE_NAME"]
2043
+ .unique()
2044
+ .tolist()
2045
+ )
2046
+
2047
+ for table in tables:
2048
+ df_columns_filtered_to_table = (
2049
+ df_columns_filtered_to_schema.query(
2050
+ f"TABLE_NAME == '{table}'"
2051
+ )
2052
+ )
2053
+ doc = f"The following columns are in the {table} table in the {database} database:\n\n"
2054
+ doc += df_columns_filtered_to_table[
2055
+ [
2056
+ "TABLE_CATALOG",
2057
+ "TABLE_SCHEMA",
2058
+ "TABLE_NAME",
2059
+ "COLUMN_NAME",
2060
+ "DATA_TYPE",
2061
+ "COMMENT",
2062
+ ]
2063
+ ].to_markdown()
2064
+
2065
+ plan._plan.append(
2066
+ TrainingPlanItem(
2067
+ item_type=TrainingPlanItem.ITEM_TYPE_IS,
2068
+ item_group=f"{database}.{schema}",
2069
+ item_name=table,
2070
+ item_value=doc,
2071
+ )
2072
+ )
2073
+
2074
+ except Exception as e:
2075
+ print(e)
2076
+ pass
2077
+ except Exception as e:
2078
+ print(e)
2079
+
2080
+ return plan
2081
+
2082
+ def get_plotly_figure(
2083
+ self, plotly_code: str, df: pd.DataFrame, dark_mode: bool = True
2084
+ ) -> plotly.graph_objs.Figure:
2085
+ """
2086
+ **Example:**
2087
+ ```python
2088
+ fig = vn.get_plotly_figure(
2089
+ plotly_code="fig = px.bar(df, x='name', y='salary')",
2090
+ df=df
2091
+ )
2092
+ fig.show()
2093
+ ```
2094
+ Get a Plotly figure from a dataframe and Plotly code.
2095
+
2096
+ Args:
2097
+ df (pd.DataFrame): The dataframe to use.
2098
+ plotly_code (str): The Plotly code to use.
2099
+
2100
+ Returns:
2101
+ plotly.graph_objs.Figure: The Plotly figure.
2102
+ """
2103
+ try:
2104
+ # Never exec LLM output with this module's globals (vanna-ai/vanna#1098)
2105
+ fig = exec_plotly_code(plotly_code, df)
2106
+ except Exception as e:
2107
+ # Inspect data types
2108
+ numeric_cols = df.select_dtypes(include=["number"]).columns.tolist()
2109
+ categorical_cols = df.select_dtypes(
2110
+ include=["object", "category"]
2111
+ ).columns.tolist()
2112
+
2113
+ # Decision-making for plot type
2114
+ if len(numeric_cols) >= 2:
2115
+ # Use the first two numeric columns for a scatter plot
2116
+ fig = px.scatter(df, x=numeric_cols[0], y=numeric_cols[1])
2117
+ elif len(numeric_cols) == 1 and len(categorical_cols) >= 1:
2118
+ # Use a bar plot if there's one numeric and one categorical column
2119
+ fig = px.bar(df, x=categorical_cols[0], y=numeric_cols[0])
2120
+ elif len(categorical_cols) >= 1 and df[categorical_cols[0]].nunique() < 10:
2121
+ # Use a pie chart for categorical data with fewer unique values
2122
+ fig = px.pie(df, names=categorical_cols[0])
2123
+ else:
2124
+ # Default to a simple line plot if above conditions are not met
2125
+ fig = px.line(df)
2126
+
2127
+ if fig is None:
2128
+ return None
2129
+
2130
+ if dark_mode:
2131
+ fig.update_layout(template="plotly_dark")
2132
+
2133
+ return fig