databao 0.0.5__tar.gz

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 (33) hide show
  1. databao-0.0.5/.gitignore +15 -0
  2. databao-0.0.5/LICENSE.md +80 -0
  3. databao-0.0.5/PKG-INFO +77 -0
  4. databao-0.0.5/README.md +50 -0
  5. databao-0.0.5/databao/__init__.py +15 -0
  6. databao-0.0.5/databao/agents/__init__.py +4 -0
  7. databao-0.0.5/databao/agents/base.py +134 -0
  8. databao-0.0.5/databao/agents/lighthouse/__init__.py +1 -0
  9. databao-0.0.5/databao/agents/lighthouse/agent.py +91 -0
  10. databao-0.0.5/databao/agents/lighthouse/graph.py +334 -0
  11. databao-0.0.5/databao/agents/lighthouse/system_prompt.jinja +36 -0
  12. databao-0.0.5/databao/agents/lighthouse/utils.py +38 -0
  13. databao-0.0.5/databao/agents/react_duckdb/__init__.py +0 -0
  14. databao-0.0.5/databao/agents/react_duckdb/agent.py +36 -0
  15. databao-0.0.5/databao/api.py +28 -0
  16. databao-0.0.5/databao/caches/__init__.py +0 -0
  17. databao-0.0.5/databao/caches/in_mem_cache.py +18 -0
  18. databao-0.0.5/databao/configs/__init__.py +3 -0
  19. databao-0.0.5/databao/configs/llm.py +201 -0
  20. databao-0.0.5/databao/core/__init__.py +8 -0
  21. databao-0.0.5/databao/core/cache.py +17 -0
  22. databao-0.0.5/databao/core/executor.py +31 -0
  23. databao-0.0.5/databao/core/opa.py +8 -0
  24. databao-0.0.5/databao/core/pipe.py +92 -0
  25. databao-0.0.5/databao/core/session.py +125 -0
  26. databao-0.0.5/databao/core/visualizer.py +65 -0
  27. databao-0.0.5/databao/duckdb/__init__.py +12 -0
  28. databao-0.0.5/databao/duckdb/react_tools.py +111 -0
  29. databao-0.0.5/databao/duckdb/utils.py +90 -0
  30. databao-0.0.5/databao/visualizers/__init__.py +0 -0
  31. databao-0.0.5/databao/visualizers/dumb.py +7 -0
  32. databao-0.0.5/databao/visualizers/vega_chat.py +61 -0
  33. databao-0.0.5/pyproject.toml +116 -0
@@ -0,0 +1,15 @@
1
+ # Virtual environment
2
+ .venv/
3
+ # Python cache files
4
+ __pycache__/
5
+ */__pycache__/
6
+ **/__pycache__/
7
+ dist/
8
+
9
+ # Environment variables
10
+ .env
11
+
12
+ # OS generated files
13
+ .DS_Store
14
+
15
+ .idea/
@@ -0,0 +1,80 @@
1
+ JetBrains Data Agent SDK EAP Terms and Conditions
2
+ Copyright (c) 2025 JetBrains s.r.o.
3
+
4
+ This program is licensed under the Apache License, Version 2.0 and the Additional Terms and Conditions (the "License"); you may not use this file except in compliance with the License.
5
+
6
+ ========================================
7
+ Apache License
8
+ Version 2.0, January 2004
9
+ http://www.apache.org/licenses/
10
+ ========================================
11
+
12
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
13
+
14
+ 1. Definitions.
15
+
16
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
17
+
18
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
19
+
20
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
23
+
24
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
25
+
26
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
27
+
28
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
29
+
30
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
31
+
32
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
33
+
34
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
35
+
36
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
37
+
38
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
39
+
40
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
41
+
42
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
43
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
45
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
46
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
47
+
48
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
49
+
50
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
51
+
52
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
53
+
54
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
55
+
56
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
57
+
58
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
59
+
60
+ ========================================
61
+ ADDITIONAL TERMS AND CONDITIONS
62
+ ========================================
63
+
64
+ This is an Early Access Program (EAP) release. The software is experimental, may not be reliable, and may contain errors. Any use of this software is at your own risk.
65
+
66
+ 1. Disclaimers Regarding AI-Generated Content and Agentic Behavior
67
+
68
+ You acknowledge that the software integrates artificial intelligence features that may generate code, queries, text, or other output ("Generated Content") and may perform autonomous actions on your local system ("Agentic Behavior").
69
+
70
+ You are solely responsible for reviewing, testing, and validating all Generated Content for accuracy, security, and fitness for any purpose. You are also solely responsible for supervising all Agentic Behavior and for any consequences thereof, including but not limited to modification of files, code, or system configurations. JetBrains has no liability for any damages or losses arising from your use of, or reliance on, Generated Content or from any Agentic Behavior.
71
+
72
+ 2. Disclaimer Regarding Local Inference and Models
73
+
74
+ The software is designed to operate with a local inference stack and third-party AI models, which may be bundled with the software or configured by you. JetBrains disclaims all warranties and assumes no liability for the performance, security, or compliance of any local inference stack or any AI models, whether provided by JetBrains or by a third party. You are solely responsible for your use of such components and for compliance with any applicable third-party licenses or terms.
75
+
76
+ 3. Disclaimer for Use in Production and Third-Party Applications
77
+
78
+ As an EAP product, this software is not intended for use in production environments. If you choose to incorporate the software into any application, product, workflow or service, you do so at your own risk. JetBrains disclaims all warranties, express or implied, and shall not be liable for any direct, indirect, incidental, special, or consequential damages suffered by you or any third party arising from such use. You agree to defend, indemnify, and hold harmless JetBrains from any and all claims related to the use of the software within your applications.
79
+
80
+ END OF TERMS AND CONDITIONS
databao-0.0.5/PKG-INFO ADDED
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: databao
3
+ Version: 0.0.5
4
+ Summary: databao: NL queries for data
5
+ License-Expression: Apache-2.0 AND LicenseRef-Additional-Terms
6
+ License-File: LICENSE.md
7
+ Classifier: Operating System :: OS Independent
8
+ Classifier: Programming Language :: Python :: 3
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: duckdb>=1.3.0
11
+ Requires-Dist: edaplot-vl~=0.0.3
12
+ Requires-Dist: jinja2>=3.1.6
13
+ Requires-Dist: langchain-anthropic<0.4,>=0.3.10
14
+ Requires-Dist: langchain-ollama>=0.3.10
15
+ Requires-Dist: langchain-openai<0.4,>=0.3.8
16
+ Requires-Dist: langchain<0.4,>=0.3.20
17
+ Requires-Dist: langgraph>=0.6.8
18
+ Requires-Dist: matplotlib>=3.10.0
19
+ Requires-Dist: pandas>=2.2.2
20
+ Requires-Dist: psycopg2-binary>=2.9.10
21
+ Requires-Dist: pydantic<3,>=2.8.0
22
+ Requires-Dist: tabulate>=0.9.0
23
+ Provides-Extra: examples
24
+ Requires-Dist: notebook>=7.4.7; extra == 'examples'
25
+ Requires-Dist: python-dotenv>=1.1.1; extra == 'examples'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # databao: NL queries for data
29
+
30
+ ## Setup connection
31
+
32
+ ```python
33
+ from sqlalchemy import create_engine
34
+
35
+ engine = create_engine(
36
+ "postgresql://readonly_role:>sU9y95R(e4m@ep-young-breeze-a5cq8xns.us-east-2.aws.neon.tech/netflix"
37
+ )
38
+ ```
39
+
40
+ ## Create databao session
41
+
42
+ ```python
43
+ llm_config = LLMConfig(name="gpt-4o-mini", temperature=0)
44
+ session = databao.open_session(llm_config=llm_config)
45
+ session.add_db(engine)
46
+ ```
47
+
48
+ ## Query data
49
+
50
+ ```python
51
+ thread = session.thread()
52
+ thread.ask("list all german shows").df()
53
+ ```
54
+
55
+
56
+ ## Local models
57
+
58
+ databao can be used with local LLMs either using ollama or OpenAI API compatible servers (LM Studio, llama.cpp, etc.).
59
+
60
+ ### Ollama
61
+
62
+ 1. Install [ollama](https://ollama.com/download) for your operating system and make sure it is running.
63
+ 2. Use an LLMConfig with `name` of the form `ollama:model_name`. For an example see [qwen3-8b-ollama.yaml](examples/configs/qwen3-8b-ollama.yaml).
64
+
65
+ The model will be downloaded automatically if it doesn't already exist.
66
+ Alternatively, `ollama pull model_name` to download the model manually.
67
+
68
+ ### OpenAI compatible servers
69
+
70
+ You can use any OAI compatible server by setting `api_base_url` in the LLMConfig. For an example, see [qwen3-8b.yaml](examples/configs/qwen3-8b-oai.yaml).
71
+
72
+ Examples of OAI compatible servers:
73
+ - [LM Studio](https://lmstudio.ai/) - Recommended for macOS (LMX engine for M-based chips, supports the [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses)).
74
+ - [ollama](https://ollama.com/) - Run with `OLLAMA_HOST=127.0.0.1:8080 ollama serve`. We recommend using ollama directly, as described [above](#ollama).
75
+ - [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master/tools/server) using `llama-server`
76
+ - [vLLM](https://github.com/vllm-project/vllm)
77
+ - etc.
@@ -0,0 +1,50 @@
1
+ # databao: NL queries for data
2
+
3
+ ## Setup connection
4
+
5
+ ```python
6
+ from sqlalchemy import create_engine
7
+
8
+ engine = create_engine(
9
+ "postgresql://readonly_role:>sU9y95R(e4m@ep-young-breeze-a5cq8xns.us-east-2.aws.neon.tech/netflix"
10
+ )
11
+ ```
12
+
13
+ ## Create databao session
14
+
15
+ ```python
16
+ llm_config = LLMConfig(name="gpt-4o-mini", temperature=0)
17
+ session = databao.open_session(llm_config=llm_config)
18
+ session.add_db(engine)
19
+ ```
20
+
21
+ ## Query data
22
+
23
+ ```python
24
+ thread = session.thread()
25
+ thread.ask("list all german shows").df()
26
+ ```
27
+
28
+
29
+ ## Local models
30
+
31
+ databao can be used with local LLMs either using ollama or OpenAI API compatible servers (LM Studio, llama.cpp, etc.).
32
+
33
+ ### Ollama
34
+
35
+ 1. Install [ollama](https://ollama.com/download) for your operating system and make sure it is running.
36
+ 2. Use an LLMConfig with `name` of the form `ollama:model_name`. For an example see [qwen3-8b-ollama.yaml](examples/configs/qwen3-8b-ollama.yaml).
37
+
38
+ The model will be downloaded automatically if it doesn't already exist.
39
+ Alternatively, `ollama pull model_name` to download the model manually.
40
+
41
+ ### OpenAI compatible servers
42
+
43
+ You can use any OAI compatible server by setting `api_base_url` in the LLMConfig. For an example, see [qwen3-8b.yaml](examples/configs/qwen3-8b-oai.yaml).
44
+
45
+ Examples of OAI compatible servers:
46
+ - [LM Studio](https://lmstudio.ai/) - Recommended for macOS (LMX engine for M-based chips, supports the [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses)).
47
+ - [ollama](https://ollama.com/) - Run with `OLLAMA_HOST=127.0.0.1:8080 ollama serve`. We recommend using ollama directly, as described [above](#ollama).
48
+ - [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master/tools/server) using `llama-server`
49
+ - [vLLM](https://github.com/vllm-project/vllm)
50
+ - etc.
@@ -0,0 +1,15 @@
1
+ from databao.api import open_session
2
+ from databao.configs.llm import LLMConfig
3
+ from databao.core import ExecutionResult, Executor, Opa, Pipe, Session, VisualisationResult, Visualizer
4
+
5
+ __all__ = [
6
+ "ExecutionResult",
7
+ "Executor",
8
+ "LLMConfig",
9
+ "Opa",
10
+ "Pipe",
11
+ "Session",
12
+ "VisualisationResult",
13
+ "Visualizer",
14
+ "open_session",
15
+ ]
@@ -0,0 +1,4 @@
1
+ from databao.agents.lighthouse.agent import LighthouseAgent
2
+ from databao.agents.react_duckdb.agent import ReactDuckDBAgent
3
+
4
+ __all__ = ["LighthouseAgent", "ReactDuckDBAgent"]
@@ -0,0 +1,134 @@
1
+ import pickle
2
+ from abc import abstractmethod
3
+ from io import BytesIO
4
+ from typing import Any
5
+
6
+ from langchain_core.messages import HumanMessage
7
+
8
+ from databao.configs.llm import LLMConfig
9
+ from databao.core import Executor, Opa, Session
10
+
11
+ try:
12
+ from duckdb import DuckDBPyConnection
13
+ except ImportError:
14
+ DuckDBPyConnection = Any # type: ignore
15
+
16
+
17
+ class AgentExecutor(Executor):
18
+ """
19
+ Base class for agents that execute with a DuckDB connection and LLM configuration.
20
+ Provides common functionality for graph caching, message handling, and OPA processing.
21
+ """
22
+
23
+ def __init__(self) -> None:
24
+ """Initialize agent with graph caching infrastructure."""
25
+ self._cached_compiled_graph: Any | None = None
26
+ self._cached_connection_id: int | None = None
27
+ self._cached_llm_config_id: int | None = None
28
+
29
+ def _get_data_connection(self, session: Session) -> Any:
30
+ """Get DuckDB connection from session."""
31
+ from duckdb import DuckDBPyConnection
32
+
33
+ dbs = session.dbs
34
+ if not dbs:
35
+ raise RuntimeError("No database connection available. Add a database to the session using session.add_db()")
36
+
37
+ # Filter for DuckDB connections only
38
+ duckdb_connections = [conn for conn in dbs.values() if isinstance(conn, DuckDBPyConnection)]
39
+
40
+ if not duckdb_connections:
41
+ raise RuntimeError(
42
+ "No DuckDB connection found. LighthouseAgent requires a DuckDB connection. "
43
+ "Use databao.duckdb.register_sqlalchemy() or similar to attach external databases to DuckDB."
44
+ )
45
+
46
+ # Use the first DuckDB connection
47
+ return duckdb_connections[0]
48
+
49
+ def _get_llm_config(self, session: Session) -> LLMConfig:
50
+ """Get LLM config from session."""
51
+ return session.llm_config
52
+
53
+ def _get_messages(self, session: Session, cache_scope: str) -> list[Any]:
54
+ """Retrieve messages from the session cache."""
55
+ try:
56
+ buffer = BytesIO()
57
+ session.cache.scoped(cache_scope).get("messages", buffer)
58
+ buffer.seek(0)
59
+ result: list[Any] = pickle.load(buffer)
60
+ return result
61
+ except (KeyError, EOFError):
62
+ return []
63
+
64
+ def _set_messages(self, session: Session, cache_scope: str, messages: list[Any]) -> None:
65
+ """Store messages in the session cache."""
66
+ buffer = BytesIO()
67
+ pickle.dump(messages, buffer)
68
+ buffer.seek(0)
69
+ session.cache.scoped(cache_scope).put("messages", buffer)
70
+
71
+ @abstractmethod
72
+ def _create_graph(self, data_connection: Any, llm_config: LLMConfig) -> Any:
73
+ """
74
+ Create and compile the agent graph.
75
+
76
+ Subclasses must implement this method to return their specific graph implementation.
77
+
78
+ Args:
79
+ data_connection: DuckDB connection
80
+ llm_config: LLM configuration
81
+
82
+ Returns:
83
+ Compiled graph ready for execution
84
+ """
85
+ pass
86
+
87
+ def _should_recompile_graph(self, connection_id: int, llm_config_id: int) -> bool:
88
+ """Check if graph needs recompilation due to connection or config changes."""
89
+ return (
90
+ self._cached_compiled_graph is None
91
+ or self._cached_connection_id != connection_id
92
+ or self._cached_llm_config_id != llm_config_id
93
+ )
94
+
95
+ def _cache_graph(self, compiled_graph: Any, connection_id: int, llm_config_id: int) -> None:
96
+ """Cache the compiled graph and associated IDs."""
97
+ self._cached_compiled_graph = compiled_graph
98
+ self._cached_connection_id = connection_id
99
+ self._cached_llm_config_id = llm_config_id
100
+
101
+ def _get_or_create_cached_graph(self, session: Session) -> tuple[Any, Any]:
102
+ """
103
+ Get cached graph or create new one if connection/config changed.
104
+
105
+ Returns:
106
+ Tuple of (data_connection, compiled_graph)
107
+ """
108
+ data_connection = self._get_data_connection(session)
109
+ llm_config = self._get_llm_config(session)
110
+
111
+ connection_id = id(data_connection)
112
+ llm_config_id = id(llm_config)
113
+
114
+ if self._should_recompile_graph(connection_id, llm_config_id):
115
+ compiled_graph = self._create_graph(data_connection, llm_config)
116
+ self._cache_graph(compiled_graph, connection_id, llm_config_id)
117
+
118
+ return data_connection, self._cached_compiled_graph
119
+
120
+ def _process_opa(self, session: Session, opa: Opa, cache_scope: str) -> list[Any]:
121
+ """
122
+ Process a single opa and convert it to a message, appending to message history.
123
+
124
+ Returns:
125
+ All messages including the new one
126
+ """
127
+ messages = self._get_messages(session, cache_scope)
128
+ messages.append(HumanMessage(content=opa.query))
129
+ return messages
130
+
131
+ def _update_message_history(self, session: Session, cache_scope: str, final_messages: list[Any]) -> None:
132
+ """Update message history in cache with final messages from graph execution."""
133
+ if final_messages:
134
+ self._set_messages(session, cache_scope, final_messages)
@@ -0,0 +1,91 @@
1
+ from pathlib import Path
2
+ from typing import Any
3
+
4
+ from langchain_core.messages import SystemMessage
5
+ from langchain_core.runnables import RunnableConfig
6
+
7
+ from databao.agents.base import AgentExecutor
8
+ from databao.agents.lighthouse.graph import ExecuteSubmit
9
+ from databao.agents.lighthouse.utils import get_today_date_str, read_prompt_template
10
+ from databao.configs.llm import LLMConfig
11
+ from databao.core import ExecutionResult, Opa, Session
12
+ from databao.duckdb.utils import describe_duckdb_schema
13
+
14
+
15
+ class LighthouseAgent(AgentExecutor):
16
+ def __init__(self) -> None:
17
+ """Initialize agent with lazy graph compilation."""
18
+ super().__init__()
19
+ self._cached_graph: ExecuteSubmit | None = None
20
+
21
+ def render_system_prompt(self, data_connection: Any, session: Session) -> str:
22
+ """Render system prompt with database schema."""
23
+ prompt_template = read_prompt_template(Path("system_prompt.jinja"))
24
+ db_schema = describe_duckdb_schema(data_connection)
25
+ db_contexts, df_contexts = session.context
26
+ context = ""
27
+ for db_name, db_context in db_contexts.items():
28
+ context += f"## Context for DB {db_name}\n\n{db_context}\n\n"
29
+ for df_name, df_context in df_contexts.items():
30
+ context += f"## Context for DF {df_name} (fully qualified name 'temp.main.{df_name}')\n\n{df_context}\n\n"
31
+
32
+ prompt = prompt_template.render(
33
+ date=get_today_date_str(),
34
+ db_schema=db_schema,
35
+ context=context,
36
+ )
37
+ return prompt
38
+
39
+ def _create_graph(self, data_connection: Any, llm_config: LLMConfig) -> Any:
40
+ """Create and compile the Lighthouse agent graph."""
41
+ self._cached_graph = ExecuteSubmit(data_connection)
42
+ return self._cached_graph.compile(llm_config)
43
+
44
+ def _get_graph_and_compiled(self, session: Session) -> tuple[Any, ExecuteSubmit, Any]:
45
+ """Get connection, uncompiled graph, and compiled graph."""
46
+ data_connection, compiled_graph = self._get_or_create_cached_graph(session)
47
+
48
+ if self._cached_graph is None:
49
+ raise RuntimeError("Graph was not properly initialized after creation")
50
+
51
+ return data_connection, self._cached_graph, compiled_graph
52
+
53
+ def execute(
54
+ self, session: Session, opa: Opa, *, rows_limit: int = 100, cache_scope: str = "common_cache"
55
+ ) -> ExecutionResult:
56
+ # TODO rows_limit is ignored
57
+
58
+ # Get or create graph (cached after first use)
59
+ data_connection, graph, compiled_graph = self._get_graph_and_compiled(session)
60
+
61
+ messages = self._process_opa(session, opa, cache_scope)
62
+
63
+ # Prepend system message if not present
64
+ messages_with_system = messages
65
+ if not messages_with_system or messages_with_system[0].type != "system":
66
+ messages_with_system = [
67
+ SystemMessage(self.render_system_prompt(data_connection, session)),
68
+ *messages_with_system,
69
+ ]
70
+
71
+ init_state = graph.init_state(messages_with_system)
72
+ last_state: dict[str, Any] | None = None
73
+ try:
74
+ for chunk in compiled_graph.stream(
75
+ init_state,
76
+ stream_mode="values",
77
+ config=RunnableConfig(recursion_limit=50),
78
+ ):
79
+ assert isinstance(chunk, dict)
80
+ last_state = chunk
81
+ except Exception as e:
82
+ return ExecutionResult(text=str(e), meta={"messages": messages_with_system})
83
+ assert last_state is not None
84
+
85
+ # Update message history (excluding system message which we add dynamically)
86
+ final_messages = last_state.get("messages", [])
87
+ if final_messages:
88
+ messages_without_system = [msg for msg in final_messages if msg.type != "system"]
89
+ self._update_message_history(session, cache_scope, messages_without_system)
90
+
91
+ return graph.get_result(last_state)