From 5cc8398e0b81a89f4ab6d72e59d82716e4febf43 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 13 Aug 2026 14:27:22 +0300 Subject: [PATCH 01/37] react agent with base tools --- agent/pyproject.toml | 1 + agent/run_deep_agent.py | 125 +++++++++ agent/src/agent/utils/jeen_metadata_client.py | 57 ++++ agent/src/deep_agent/agent.py | 112 ++++++++ agent/src/deep_agent/tools.py | 252 ++++++++++++++++++ agent/uv.lock | 241 ++++++++++++++++- 6 files changed, 785 insertions(+), 3 deletions(-) create mode 100644 agent/run_deep_agent.py create mode 100644 agent/src/deep_agent/agent.py create mode 100644 agent/src/deep_agent/tools.py diff --git a/agent/pyproject.toml b/agent/pyproject.toml index cab8ad1..dbb5bb1 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -22,6 +22,7 @@ dependencies = [ "json-repair>=0.25.0", "shapely>=2.0.0", "sqlglot>=25.0.0", + "deepagents>=0.6.12", ] [tool.uv.sources] diff --git a/agent/run_deep_agent.py b/agent/run_deep_agent.py new file mode 100644 index 0000000..2b1d48c --- /dev/null +++ b/agent/run_deep_agent.py @@ -0,0 +1,125 @@ +import asyncio +import os +import sys +import argparse + +# Add the src directory to sys.path so we can import modules +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src'))) +# Also add core to the path +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../core/src'))) + +import warnings +import urllib3 +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +from deep_agent.agent import create_deep_agent + +# ANSI Colors for terminal output +CYAN = "\033[96m" +GREEN = "\033[92m" +YELLOW = "\033[93m" +RED = "\033[91m" +MAGENTA = "\033[95m" +BOLD = "\033[1m" +RESET = "\033[0m" + +import time +import json +from datetime import datetime + +async def run_query(agent, question: str): + print(f"\n{CYAN}{BOLD}{'='*80}{RESET}") + print(f"{CYAN}{BOLD} Running Query: \"{question}\"{RESET}") + print(f"{CYAN}{BOLD}{'='*80}{RESET}\n") + + config = {"configurable": {"thread_id": "cli_deep_agent"}} + + start_time = time.time() + final_state = None + + async for state in agent.astream( + {"messages": [("user", question)]}, + config, + stream_mode="values" + ): + latest_message = state["messages"][-1] + latest_message.pretty_print() + final_state = state + + execution_time = time.time() - start_time + + # Extract execution details + if final_state and "messages" in final_state: + messages = final_state["messages"] + final_answer = messages[-1].content if hasattr(messages[-1], "content") else "" + + import re + # 1. Safely extract the LAST SQL block (in case there are drafts in thoughts) + sql_blocks = re.findall(r'```(?:sql)?\n(.*?)\n?```', final_answer, re.DOTALL | re.IGNORECASE) + final_sql = sql_blocks[-1].strip() if sql_blocks else None + + # 2. Strip blocks and ```sql``` blocks from the final answer so it's just text + clean_answer = re.sub(r'.*?', '', final_answer, flags=re.DOTALL) + clean_answer = re.sub(r'```(?:sql)?\n.*?\n?```', '', clean_answer, flags=re.DOTALL | re.IGNORECASE) + clean_answer = clean_answer.strip() + + # Log to CSV file + import csv + log_file = "deep_agent_logs.csv" + file_exists = os.path.isfile(log_file) + + # 3. Physically compress all multi-line strings into a single line for the CSV + q_csv = question.replace('\n', '\\n').replace('\r', '') + sql_csv = final_sql.replace('\n', '\\n').replace('\r', '') if final_sql else "None" + ans_csv = clean_answer.replace('\n', '\\n').replace('\r', '') + + with open(log_file, "a", newline="", encoding="utf-8") as f: + writer = csv.writer(f) + if not file_exists: + writer.writerow(["Timestamp", "Execution Time (s)", "Question", "Final SQL", "Final Answer"]) + + writer.writerow([ + datetime.now().isoformat()[:19].replace("T", " "), + round(execution_time, 2), + q_csv, + sql_csv, + ans_csv + ]) + + sql_status = "Yes" if final_sql else "None" + print(f"\n{GREEN}{BOLD}[Extraction Log Saved] Execution time: {round(execution_time, 2)}s, Final SQL captured: {sql_status}{RESET}") + +async def main(): + parser = argparse.ArgumentParser(description="Interactive CLI tool to test the Deep Agent.") + parser.add_argument("query", nargs="?", default="", help="The query to run.") + parser.add_argument("--interactive", "-i", action="store_true", help="Run in interactive loop mode.") + args = parser.parse_args() + + print(f"{MAGENTA}{BOLD}Initializing Deep Agent...{RESET}") + agent = create_deep_agent() + + if args.interactive: + print(f"{GREEN}{BOLD}Starting Interactive Mode. Type 'quit', 'exit', or 'q' to stop.{RESET}") + while True: + try: + question = input(f"\n{YELLOW}{BOLD}[Deep Agent] Enter your query: {RESET}") + except (KeyboardInterrupt, EOFError): + break + + if not question.strip(): + continue + + if question.strip().lower() in ('quit', 'exit', 'q'): + print(f"{MAGENTA}{BOLD}Goodbye!{RESET}") + break + + await run_query(agent, question) + + elif args.query: + await run_query(agent, args.query) + else: + print(f"{RED}{BOLD}Error: You must provide a query or run with --interactive{RESET}") + parser.print_help() + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/agent/src/agent/utils/jeen_metadata_client.py b/agent/src/agent/utils/jeen_metadata_client.py index fda841c..e3cc767 100644 --- a/agent/src/agent/utils/jeen_metadata_client.py +++ b/agent/src/agent/utils/jeen_metadata_client.py @@ -275,6 +275,24 @@ async def get_table_profile(self, table_name: str) -> dict[str, Any] | None: ) return None + async def get_column_profile(self, table_name: str, column_name: str) -> dict[str, Any] | None: + """ + Returns the latest stored statistics for a single column: role, null ratio, distinct count, min/max, and example values. + """ + try: + profile = await self._call( + "get_column_profile", + { + "connection_id": self._connection_id, + "table_name": table_name, + "column_name": column_name, + }, + ) + return profile if isinstance(profile, dict) else None + except Exception as exc: + logger.error("JeenMetadataClient.get_column_profile failed: %s", exc) + return None + # ------------------------------------------------------------------ # Full table listing (fallback when search returns nothing) # ------------------------------------------------------------------ @@ -313,6 +331,45 @@ async def list_tables_rich(self) -> list[dict[str, Any]]: ) return [] + # ------------------------------------------------------------------ + # MCP Search Tools + # ------------------------------------------------------------------ + + async def search(self, query: str, limit: int = 10) -> Any: + """Search metadata for a connection across tables, columns, etc.""" + try: + return await self._call("search", {"connection_id": self._connection_id, "query": query, "limit": limit}) + except Exception as exc: + logger.error("search failed: %s", exc) + return {"error": str(exc)} + + async def search_business_terms(self, query: str, limit: int = 10) -> Any: + """Finds business glossary terms relevant to a question.""" + try: + return await self._call("search_business_terms", {"connection_id": self._connection_id, "query": query, "limit": limit}) + except Exception as exc: + logger.error("search_business_terms failed: %s", exc) + return {"error": str(exc)} + + async def search_knowledge_pairs(self, query: str, limit: int = 10) -> Any: + """Finds saved question-and-query examples.""" + try: + return await self._call("search_knowledge_pairs", {"connection_id": self._connection_id, "query": query, "limit": limit}) + except Exception as exc: + logger.error("search_knowledge_pairs failed: %s", exc) + return {"error": str(exc)} + + async def search_column_values(self, query: str, table: str = None, column: str = None, limit: int = 10) -> Any: + """Looks up the real values a column contains (large categorical resolver).""" + args = {"connection_id": self._connection_id, "query": query, "limit": limit} + if table: args["table"] = table + if column: args["column"] = column + try: + return await self._call("search_column_values", args) + except Exception as exc: + logger.error("search_column_values failed: %s", exc) + return {"error": str(exc)} + # --------------------------------------------------------------------------- # Module-level singleton (lazy-initialised, safe to import at module load) diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py new file mode 100644 index 0000000..8c2bb20 --- /dev/null +++ b/agent/src/deep_agent/agent.py @@ -0,0 +1,112 @@ +""" +Agent logic and LangGraph harness for the Deep Agent. +""" + +from langchain_core.messages import SystemMessage +from langgraph.prebuilt import create_react_agent +from langgraph.checkpoint.memory import MemorySaver + +from deep_agent.tools import ( + get_database_catalog, + get_table_profile, + execute_trino_query, + get_sample_rows, + get_column_distinct_values, + search_metadata, + search_business_terms, + search_knowledge_pairs, + search_column_values, + get_column_profile, + resolve_location_to_wkt, + validate_sql_syntax, +) +import datetime +from agent.llm import get_llm + + +SYSTEM_PROMPT = """You are an elite, highly autonomous Deep SQL Analyst. You are decisive, analytical, and follow exploratory methodology without deviation. + +**Your Goal**: Answer complex user questions (which will be written in Hebrew) by thoroughly exploring the Trino database, discovering the correct schema, writing precise SQL, and returning the exact answer. + +**Current Context**: +* Today's date is: {today}. Use this to natively resolve relative time expressions (e.g., 'last month', 'yesterday') when building queries. + +**CRITICAL RULES**: +1. **English Reasoning**: You MUST perform all your internal reasoning and analysis in English to maintain peak logical performance. +2. **Hebrew Output**: Your final response to the user MUST be entirely in Hebrew (except for technical SQL terms). + +# Methodology & Flow: +You have access to a suite of highly specialized tools. You are free to determine the best path to solve the user's request, but you should generally follow this workflow: +1. **Decompose & Discover**: Break down the user's request into logical sub-questions. Start by fetching the catalog to understand the domain. Use metadata and glossary search tools to resolve any ambiguous business terms. +2. **Profile & Enrich**: Before writing SQL, profile the tables/columns you plan to use. Use specific resolution tools (`search_column_values`, `resolve_location_to_wkt`) to get the exact database spellings or geometries. +3. **Draft (CTEs) & Validate**: Write your SQL using CTEs (`WITH AS (...)`) for each logical step. Dry-run it using `validate_sql_syntax` to instantly catch typos or missing CASTs. +4. **Execute & Iterate**: Once valid, execute the query. If it fails, iteratively debug. If it succeeds but returns 0 rows, carefully verify your assumptions—the data might genuinely not exist. +5. **Intent Match (CRITICAL)**: Before finalizing, you MUST ensure your query logic (grain, filtering, aggregations, sorting, and joins) strictly aligns with the user's original intent. Silently translate your final SQL query back into plain English and compare it line-by-line against the user's original Hebrew request. If a requested filter, grouping, or logic is missing, you MUST rewrite and re-execute the query. +6. **Escalation (Last Resort)**: If you face unresolvable ambiguity (e.g., a term has 5 conflicting definitions) and metadata searches fail, you may stop and output a clarifying multiple-choice question to the user in Hebrew. Use this ONLY as an absolute last resort, not as a habit. + +# Advanced Strategies (Optional 'Pro-Tips'): +You may employ the following strategies when faced with challenging scenarios: +* **Schema Linking**: If the user's Hebrew request involves complex domain logic or a highly fragmented database schema, mentally map Hebrew terms to English tables/columns before drafting SQL. +* **Diverse Synthesis**: If multiple SQL logic paths seem plausible (e.g., unsure whether to use an INNER JOIN vs a LEFT JOIN), you can generate 2 or 3 variations, execute them all using `execute_trino_query` with `LIMIT`, and compare the results to deduce the correct approach. + +# SQL Syntax Guidelines: +1. **Geo-Spatial**: When constructing geometries from WKT, ALWAYS use `ST_GeometryFromText()`. NEVER use `ST_GeomFromText()`. When calculating distances in degrees (WGS84), use Trino's `toSphericalGeography()`. +2. **Arrays**: When checking if a value exists in an array, ALWAYS use `contains()`. NEVER use `array_contains()`. +3. **Aggregations**: Wrap each column used in an aggregation with `COALESCE(column, 0)` to avoid NULLs. +4. **Dates/Times**: Always work with ISO 8601 format. Explicitly CAST if needed. +5. **Counts**: When counting entities, always apply DISTINCT on the identifier column (e.g., id). +6. **Sorting/Limits**: When using `ORDER BY `, always add `GROUP BY ` before to select distinct values. When querying for top (max/min) values, return ALL records that share the top value rather than LIMIT 1, unless a secondary sorting is requested. + +# Final Output Recommendation: +When you have successfully executed the query and found the answer, structure your final response in Hebrew (except for technical SQL terms). It should generally include: +1. **Explanation**: A brief, simple, step-by-step explanation of what your SQL does. +2. **Result**: A summary or markdown table showing the actual executed query results. +3. **The SQL**: The exact, final, successful Trino SQL query enclosed in a markdown block (```sql ... ```) at the very bottom. + +# Constraints: +* NEVER guess or assume data formats. ALWAYS verify them with tools. +* NEVER hallucinate columns or tables that do not exist in the catalog. +* ALWAYS write LIMIT clauses on your exploratory queries to avoid large data pulls. +* Every table reference MUST use exact 3-part naming: `..`. +* NEVER use Unicode characters, only utf-8. +* NEVER include any inline comments (starting with '--' or '/*') in the SQL statement. +* NEVER wrap column identifiers in single or double quoted string literals (' ' or " "). +* NEVER give variables names in Hebrew. +* NEVER ask or suggest a follow-up question. +* CRITICAL: When you have successfully executed the query and are ready to provide the final answer, you MUST NOT attempt to call any further tools. Simply output your final response as plain text. +""" + +def create_deep_agent(): + """ + Creates and returns a compiled LangGraph ReAct agent equipped with our deep exploration tools. + """ + llm = get_llm() + + tools = [ + get_database_catalog, + get_table_profile, + get_column_profile, + execute_trino_query, + validate_sql_syntax, + get_sample_rows, + get_column_distinct_values, + search_metadata, + search_business_terms, + search_knowledge_pairs, + search_column_values, + resolve_location_to_wkt, + ] + + # We use a simple MemorySaver for ephemeral memory per thread + memory = MemorySaver() + + today = datetime.date.today().isoformat() + + agent = create_react_agent( + model=llm, + tools=tools, + prompt=SYSTEM_PROMPT.format(today=today), + checkpointer=memory, + ) + + return agent diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py new file mode 100644 index 0000000..01dad3a --- /dev/null +++ b/agent/src/deep_agent/tools.py @@ -0,0 +1,252 @@ +import json +import logging +import datetime +from typing import Optional +from pydantic import Field +from langchain_core.tools import tool +from langchain_core.prompts import PromptTemplate + +from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from core.trino import execute_query_sync +from agent.services.geo_utils import get_geojson_polygon, geojson_to_simplified_wkt +from agent.llm import get_llm + +logger = logging.getLogger(__name__) + +@tool +async def get_database_catalog() -> str: + """ + Retrieves the complete metadata catalog and structural overview for the database. + + Use this FIRST when starting any new query to discover what tables exist, how they relate, and to see column profiling statistics. + Do NOT use this to fetch live data rows; this only retrieves metadata and schema definitions. + + The output payload includes Column/Table Names, Descriptions, Types, Universal Base Metrics (Null Rate, Distinct Count) and specific Profiling Data Payloads. + """ + client = get_jeen_metadata_client() + try: + catalog_prompt = await client.get_catalog_prompt() + return catalog_prompt + except Exception as e: + return f"Error fetching catalog: {str(e)}" + +@tool +async def get_table_profile(table_name: str) -> str: + """ + Retrieves the latest stored schema and statistics for one specific table. + + Use this to understand a single table's row counts, column roles, null ratios, distinct counts, and min/max values. + Do NOT use this to fetch raw data rows; use `get_sample_rows` or `execute_trino_query` instead. + + Args: + table_name (str): The fully qualified, exact 3-part name of the table, e.g., '"catalog"."schema"."table"'. + """ + client = get_jeen_metadata_client() + try: + profile = await client.get_table_profile(table_name) + if not profile: + return f"Error: Schema not found for table {table_name}" + return json.dumps(profile, indent=2, ensure_ascii=False) + except Exception as e: + return f"Error fetching table schema: {str(e)}" + +@tool +async def get_column_profile(table_name: str, column_name: str) -> str: + """ + Retrieves the latest stored statistics for a single specific column. + + Use this before writing a WHERE clause to learn exactly how values are formatted in the database. + Do NOT use this for live dynamic querying of values; this only reads pre-computed metadata. + + If the output shows 'domainIsComplete: true', the listed values are the entire value set, so any other value can be safely ruled out. The 'semanticType' field indicates how the column should be searched (e.g., categorical, geo). + + Args: + table_name (str): The fully qualified exact name of the table, e.g., '"catalog"."schema"."table"'. + column_name (str): The exact name of the column to profile. + """ + client = get_jeen_metadata_client() + try: + profile = await client.get_column_profile(table_name, column_name) + if not profile: + return f"Error: Column profile not found for {table_name}.{column_name}" + return json.dumps(profile, indent=2, ensure_ascii=False) + except Exception as e: + return f"Error fetching column profile: {str(e)}" + +@tool +def execute_trino_query(sql: str, limit: int = 50) -> str: + """ + Executes a read-only Trino SQL query and returns the resulting rows. + + Use this to test SQL queries against the actual database and perform exploratory data analysis. + Do NOT use this for queries returning millions of rows; it will crash the context. Always use LIMIT. + + Args: + sql (str): The exact Trino SQL query string to execute. + limit (int): The maximum number of rows to return (from 1 to 100). Defaults to 50. + """ + sql_clean = sql.strip().rstrip(';') + if "limit" not in sql_clean.lower(): + sql_clean = f"{sql_clean} LIMIT {limit}" + + try: + res = execute_query_sync(sql_clean) + if not res.success: + return f"Error executing query: {res.error_message}" + + result_dict = { + "columns": res.columns, + "row_count": res.row_count, + "rows": res.rows + } + return json.dumps(result_dict, ensure_ascii=False, default=str) + except Exception as e: + return f"Execution failed: {str(e)}" + +@tool +def get_sample_rows(table_name: str, limit: int = 5) -> str: + """ + Retrieves a small number of raw data rows from a table using a live Trino query. + + Use this only when schema profiles do not provide enough context and you must see exact raw data formats. + Do NOT use this for counting or aggregating data. + + Args: + table_name (str): The fully qualified exact name of the table. + limit (int): The number of rows to sample (from 1 to 10). Defaults to 5. + """ + safe_table = table_name.split()[0].rstrip(';') + sql = f"SELECT * FROM {safe_table} LIMIT {limit}" + return execute_trino_query.invoke({"sql": sql, "limit": limit}) + +@tool +def get_column_distinct_values(table_name: str, column_name: str, limit: int = 50) -> str: + """ + Executes a live Trino query to fetch unique values for a specific column. + + Use this to see exact existing strings in the database before writing an exact-match WHERE clause. + Do NOT use this if the catalog or `get_column_profile` already provided the exhaustive list of categorical values. + + Args: + table_name (str): The fully qualified exact name of the table. + column_name (str): The exact name of the column. + limit (int): Maximum distinct values to return (from 1 to 100). Defaults to 50. + """ + safe_table = table_name.split()[0].rstrip(';') + safe_col = column_name.split()[0].rstrip(';') + sql = f"SELECT DISTINCT {safe_col} FROM {safe_table} LIMIT {limit}" + return execute_trino_query.invoke({"sql": sql, "limit": limit}) + +@tool +async def search_metadata(query: str, limit: int = 10) -> str: + """ + Searches the metadata catalog across all tables, columns, relationships, and business terms. + + Use this to quickly discover relevant schema or glossary context when you aren't sure which table to look at. + Do NOT use this to search for specific data row values (e.g., 'John Doe'); use `search_column_values` instead. + + Args: + query (str): The search text (multilingual/Hebrew support) to match against metadata names and descriptions. + limit (int): Maximum number of results to return. Defaults to 10. + """ + client = get_jeen_metadata_client() + res = await client.search(query, limit) + return json.dumps(res, indent=2, ensure_ascii=False) + +@tool +async def search_business_terms(query: str, limit: int = 10) -> str: + """ + Searches the business glossary for terms relevant to a natural language question. + + Use this to bridge the gap between user vocabulary and database terminology (e.g., matching 'sales' to 'Revenue'). + Do NOT use this to search for database tables or column names directly. + + The search is multilingual and ranks by meaning rather than exact keywords. + + Args: + query (str): A natural language question or phrase (multilingual support). + limit (int): Maximum number of results to return. Defaults to 10. + """ + client = get_jeen_metadata_client() + res = await client.search_business_terms(query, limit) + return json.dumps(res, indent=2, ensure_ascii=False) + +@tool +async def search_knowledge_pairs(query: str, limit: int = 10) -> str: + """ + Searches saved question-and-query examples that are semantically similar to the user's question. + + Use this to find few-shot examples of how similar questions were solved previously before writing your own query. + Even if you think you know how to write the query, searching for similar past questions often reveals domain-specific SQL conventions, exact JOIN paths, or edge cases you haven't considered. + + Do NOT pass SQL keywords as the query; pass the raw natural language question exactly as the user wrote it (in Hebrew). + + Only the stored question is matched (never the query text), so it works best with full natural language sentences. + + Args: + query (str): The natural language user question (multilingual/Hebrew support). + limit (int): Maximum number of results to return. Defaults to 10. + """ + client = get_jeen_metadata_client() + res = await client.search_knowledge_pairs(query, limit) + return json.dumps(res, indent=2, ensure_ascii=False) + +@tool +async def search_column_values(query: str, table: Optional[str] = None, column: Optional[str] = None, limit: int = 10) -> str: + """ + Searches for exact real values contained within text columns across the database. + + Use this before writing a WHERE clause on a text column when you only have a partial or loosely spelled value (e.g., finding 'Tel Aviv' from 'tel aviv'). + Do NOT use this on numeric or date columns. + + Matching is multilingual for descriptive values and substring-based for codes and identifiers, ensuring you find the exact database spelling. + + Args: + query (str): The specific value to look for (partial or full string). + table (str, optional): Restrict to one table. Omit to search all tables. + column (str, optional): Restrict to one column. Omit to search all columns. + limit (int): Maximum number of results to return. Defaults to 10. + """ + client = get_jeen_metadata_client() + res = await client.search_column_values(query, table, column, limit) + return json.dumps(res, indent=2, ensure_ascii=False) + + +@tool +def resolve_location_to_wkt(location_name: str) -> str: + """ + Resolves a geographic location name to its WKT (Well-Known Text) polygon representation. + + Use this to get the exact WKT coordinates when you need to filter geographically using `ST_GeometryFromText()` and only have a city/region name. + Do NOT use this for exact addresses; it is designed for cities, regions, and countries. + + Args: + location_name (str): The name of the geographic location to resolve (e.g., 'Paris, France'). + """ + geojson = get_geojson_polygon(location_name) + if geojson: + wkt = geojson_to_simplified_wkt(geojson) + if wkt: + return wkt + return f"Error: Could not resolve location '{location_name}' to WKT." + +@tool +def validate_sql_syntax(sql: str) -> str: + """ + Validates the syntax of a Trino SQL query without executing it against data. + + Use this to dry-run a query and instantly catch syntax errors (like missing CASTs or typos). + Do NOT use this to check if a query returns 0 rows; it only checks syntax validity. + + Args: + sql (str): The exact Trino SQL query string to validate. + """ + sql_clean = sql.strip().rstrip(';') + try: + res = execute_query_sync(f"EXPLAIN (TYPE VALIDATE) {sql_clean}") + if res.success: + return "Syntax is VALID." + else: + return f"Syntax Error: {res.error_message}" + except Exception as e: + return f"Validation failed: {str(e)}" diff --git a/agent/uv.lock b/agent/uv.lock index 422d5f8..a180db6 100644 --- a/agent/uv.lock +++ b/agent/uv.lock @@ -8,6 +8,7 @@ version = "0.1.0" source = { editable = "." } dependencies = [ { name = "core" }, + { name = "deepagents" }, { name = "esca-sdk" }, { name = "fastapi" }, { name = "greenlet" }, @@ -38,6 +39,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "core", directory = "../core" }, + { name = "deepagents", specifier = ">=0.6.12" }, { name = "esca-sdk", git = "https://github.com/elirazpevz/esca.git?subdirectory=packages%2Fesca-sdk" }, { name = "fastapi", specifier = ">=0.115.6" }, { name = "greenlet", specifier = ">=3.5.1" }, @@ -97,6 +99,25 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" }, ] +[[package]] +name = "anthropic" +version = "0.121.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "distro" }, + { name = "docstring-parser" }, + { name = "httpx" }, + { name = "jiter" }, + { name = "pydantic" }, + { name = "sniffio" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0f/ca/3cb2c20ee729736fbd4546d5d8b67e818288529fe70cb7a80dbf80aef70b/anthropic-0.121.0.tar.gz", hash = "sha256:e79d6e08ab3376602fc9a70d4d5ea3540817c76cf7e16658bed790834e1833d6", size = 1013292, upload-time = "2026-08-07T17:11:07.241Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/91/b3d41643f1f639927e8c5fb02c3bd8bffe6f1f29e219b3bd4c61e267b15c/anthropic-0.121.0-py3-none-any.whl", hash = "sha256:6048713fa441e59e1cba8363171cd2a86273b25bd213e9c7ac70a523af88b011", size = 1035493, upload-time = "2026-08-07T17:11:08.508Z" }, +] + [[package]] name = "anyio" version = "4.14.0" @@ -144,6 +165,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" }, ] +[[package]] +name = "bracex" +version = "3.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ac/01/5f394b8bcd6e5b92f73130990960423bbb19711f906bd9fe9ea5557c667c/bracex-3.0.1.tar.gz", hash = "sha256:4e38e32392e4a4780fe15d644bfc7c8514057cfc3861e060b11814ce829c25e4", size = 44019, upload-time = "2026-07-20T13:43:00.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/8f/6f7273a7adb8d73fc8d21ede4376a3e475e52f98435c6007f69100dec8ca/bracex-3.0.1-py3-none-any.whl", hash = "sha256:6523ad83aeb5098a4ee597cff0f964442ff74e460bd3fafaffab6a013ff2288c", size = 11940, upload-time = "2026-07-20T13:42:59.268Z" }, +] + [[package]] name = "certifi" version = "2026.5.20" @@ -153,6 +183,29 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/59/8c/57e832b7af6d7c5abe66eb3fbe3a3a32f4d11ea23a1aa7131371035be991/certifi-2026.5.20-py3-none-any.whl", hash = "sha256:3c52e209ba0a4ad7aebe60436a4ab349c39e1e602e8c134221e546902ad25897", size = 134134, upload-time = "2026-05-20T11:46:48.578Z" }, ] +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/69/43965eccfdead3b9220015fd1320e117be8c6ed01a62ffab76eeb752f5d5/cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0", size = 184821, upload-time = "2026-08-03T21:19:44.887Z" }, + { url = "https://files.pythonhosted.org/packages/54/7d/16e5a096677b5e313ca80cd5e5170efa3ea44624a82bb111925522da64b1/cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf", size = 184719, upload-time = "2026-08-03T21:19:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/80/fb/0bb75b7039588c074b37ae99f40d9bfddf990ecb2fbc346ebccd2e56b9be/cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e", size = 175292, upload-time = "2026-08-03T21:19:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/d9/79/615cc094e2fb508cade7de88d3b4f6c4ec2bab695c97bce9153dc65aadf5/cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a", size = 185919, upload-time = "2026-08-03T21:19:56.89Z" }, + { url = "https://files.pythonhosted.org/packages/70/c6/d0ea84713fe46b243a436a18fcd47d639732747e21635c8a27191b06dc30/cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80", size = 180093, upload-time = "2026-08-03T21:19:58.155Z" }, +] + [[package]] name = "charset-normalizer" version = "3.4.7" @@ -254,6 +307,60 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8a/3c/1a983b9a745d7f83d53f057bcc5bf79ba6a2bbc08266b3f0c7d6fe630c9b/coverage-7.14.1-py3-none-any.whl", hash = "sha256:a252f21c27e38347e60111a3266b03827422a7d5525951aceee313aa68bab1d2", size = 211815, upload-time = "2026-05-26T20:41:34.078Z" }, ] +[[package]] +name = "cryptography" +version = "50.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/de/41/6cbdcf9142d00fe82836fbb51e503e58088575cf7a0fe1dbff6695bf0840/cryptography-50.0.0.tar.gz", hash = "sha256:eeac2acb5a20ed25e0ad6d1df9891a520b78b404266b6d11778f25d5d691a6c9", size = 880201, upload-time = "2026-07-31T14:25:10.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/5c/59086b4aac5e879d38ddbcf74e4be7ade89cebc3eb199a55da998c3bb46a/cryptography-50.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:031e2d5dd4bb9caa3ca9c82e5a197fd8ae680232cee62603d1a813f3f07e3d03", size = 4001252, upload-time = "2026-07-31T14:23:33.331Z" }, + { url = "https://files.pythonhosted.org/packages/57/ef/8f2df13c7216bcad3e1c74e07f6e193d93e998e114f524a53877c9af27ad/cryptography-50.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fd9192b7b70c573d7f214eb1ae35e00d359f6f5e4b27c7e21e30de1fc6204645", size = 4719554, upload-time = "2026-07-31T14:23:35.611Z" }, + { url = "https://files.pythonhosted.org/packages/d9/41/029086c34d91052fc3b88bcc8056f709a7c915c7a23b235a54eb800b1c97/cryptography-50.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:06a32a980526a6ab9a4b9bf8f7385800791e2bb960903cb6b530e4817509a3b7", size = 4702130, upload-time = "2026-07-31T14:23:37.635Z" }, + { url = "https://files.pythonhosted.org/packages/7d/ff/b6ce0954962e7f7b969f850a883744197bb3910bdfd7b6da162eab7d9f68/cryptography-50.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a1b30560f2acc95aa8b2e06e716a13dbfc97314747b80d9707e307f77b40d6b3", size = 4725244, upload-time = "2026-07-31T14:23:39.471Z" }, + { url = "https://files.pythonhosted.org/packages/06/1e/63a1027cb7fec360a182208e1b7767d5aa1fe57be3d6aa856e69a321edc0/cryptography-50.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:8d89f3976b10b4ce31118de72329025f70d2c6ead14a8217c5514dd2c6d5a78f", size = 5342265, upload-time = "2026-07-31T14:23:41.286Z" }, + { url = "https://files.pythonhosted.org/packages/6b/72/a1116d683a6d7ece94590013882515de087edf9ef0e6292aae615a44df73/cryptography-50.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b42a28c1844fd9de8f3f7d540e36b66f3a9c83fceac7170ebc7a6a19edd9dcae", size = 4734609, upload-time = "2026-07-31T14:23:43.139Z" }, + { url = "https://files.pythonhosted.org/packages/15/37/36a9c479bbe49acea2636c7fd3360d20f7b7e079c300352011c44850b181/cryptography-50.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:900131fafd8aead39ac7dd3a7e833be754c17a95cfd91221636949fe4eb0aa8a", size = 4356517, upload-time = "2026-07-31T14:23:44.939Z" }, + { url = "https://files.pythonhosted.org/packages/32/98/8a151d64367204cbc63ec65d37502f1d9c53cf4bfc6ec3c532614dbec60d/cryptography-50.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:07949c449a1abcf60d1ee6e88956d89404c7df3c8258f46589e912988e551987", size = 4724529, upload-time = "2026-07-31T14:23:46.93Z" }, + { url = "https://files.pythonhosted.org/packages/22/f6/ec13b470172126464a86bf54d2294a46d29837fc51ba3e45d4047946fb5e/cryptography-50.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f89831ef99dd7dd169ab06d63a831adb9e20a87aac6d380266bbda5823349169", size = 5299852, upload-time = "2026-07-31T14:23:48.851Z" }, + { url = "https://files.pythonhosted.org/packages/da/3a/f05e32c99d440c9bb891ea0e36c9091891e36be5a9a87ab2ee6ea20729f6/cryptography-50.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:82148ec5bddac30b51a5b3c1945075f896fa022cb93f8e4a01e9f6ee95292c5f", size = 4734462, upload-time = "2026-07-31T14:23:50.861Z" }, + { url = "https://files.pythonhosted.org/packages/ca/dc/bd72b26be8953f80625f63151efd38eee71c76ca6cf591c08ff34615a79e/cryptography-50.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1489e263a8048bb8b6a8bac662eb2d402ea5d2b7b4699b72f385f1e2772db105", size = 4852708, upload-time = "2026-07-31T14:23:52.715Z" }, + { url = "https://files.pythonhosted.org/packages/27/20/c930314a2ab476d15dec966ec87e2e9637bb02b06106b12c0396c57bb603/cryptography-50.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7cec5b856506da6defb290f30c9ee687d5f5e8cb0bd3f6459dde43b0b4fa40ef", size = 5004179, upload-time = "2026-07-31T14:23:54.887Z" }, + { url = "https://files.pythonhosted.org/packages/32/2e/c9db68a0c4bfa28e310707527c0ee3a2bd254104d2e02e68f368e197aa4c/cryptography-50.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:bd1c592e4d5974f0d08d4888e432157adba757c66da0246918e43677fafa2d30", size = 3840395, upload-time = "2026-07-31T14:23:56.677Z" }, + { url = "https://files.pythonhosted.org/packages/03/37/73d005be173aff344af30e9fd2a576575cb2391a7101d9cd3842e1fa8cce/cryptography-50.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ccdc4a71a4dabae05de219404f9f4abc38e3b58422177ff93d0da05967dafa07", size = 4036009, upload-time = "2026-07-31T14:24:24.122Z" }, + { url = "https://files.pythonhosted.org/packages/ff/c6/7a6202a534e32103a285b7834a120869557fe198d51d7cfe59754c8bda9c/cryptography-50.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:910e1d2668e7de9648f2bcee30e180db2a6b15c30f887d7c4c93ddf96e3992e3", size = 4745252, upload-time = "2026-07-31T14:24:26.118Z" }, + { url = "https://files.pythonhosted.org/packages/85/4f/0fa8c2f4428198f15d9ff8d63400e27afbf94ce833f6108da1eb3753f945/cryptography-50.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a91296cb61e8df6f86d0c19cc4068228da256bf59bf86049fbd821084565327f", size = 4728939, upload-time = "2026-07-31T14:24:27.994Z" }, + { url = "https://files.pythonhosted.org/packages/d1/63/54dd723490ba2dc09b299682c10b38db38f159728bcaae8c591b8af2f22d/cryptography-50.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e722f16708d854fe924790e051061f6704a472c3bac347b6fd88033ea8dd0dc5", size = 4748483, upload-time = "2026-07-31T14:24:30.254Z" }, + { url = "https://files.pythonhosted.org/packages/1d/dd/7c77d26285cc7f6991efce64a0f5b4f9383bfa5dd8c5033003eaf7db4cdb/cryptography-50.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:d764dcf130c428ef66786f866dd750f53182bc608813489915e9fc106bb0c82f", size = 5367599, upload-time = "2026-07-31T14:24:32.457Z" }, + { url = "https://files.pythonhosted.org/packages/46/c9/f60aed34c013f317f92817b6c171c2d22a78270fa41109bd4b08af26b194/cryptography-50.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:105110f43a471dbd0060b9c9516cb8a6a79233631a04cc2ba16f28323ac6e025", size = 4762647, upload-time = "2026-07-31T14:24:34.599Z" }, + { url = "https://files.pythonhosted.org/packages/be/f3/f9a0173b139372c3a48ed98154b45cc6b9de17c789d5ab552e621c293609/cryptography-50.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:828743d939e9629bc267b8e2d08d8bb67cd4319c771a33d4b18b22dd8fb7440a", size = 4385197, upload-time = "2026-07-31T14:24:36.647Z" }, + { url = "https://files.pythonhosted.org/packages/d8/36/83bb81f6e569bc38e1e4a7bc80f29b46bb9601920bc455fc8e888f5d5742/cryptography-50.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:2a8183b489dc1f7f80f135780fadc1108f14b31b8a40411c7a5b17425f65f28b", size = 4748095, upload-time = "2026-07-31T14:24:39.493Z" }, + { url = "https://files.pythonhosted.org/packages/6b/16/d3008eff98c764979865834c3d386d4fd041b5f52e7f34fc29ac1a5eb515/cryptography-50.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:6e7d61120573a7f2cd94cc095f9e81f6967c61ccdf194285aa143ecec8e0b708", size = 5325948, upload-time = "2026-07-31T14:24:41.556Z" }, + { url = "https://files.pythonhosted.org/packages/9c/f8/d97f9603efda3888187bfdb893f26c41be4735c10631d05d284ee6b047c4/cryptography-50.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:37fdb0d0111f1e2ff07139dfb79f1b49531f8e213c46f1163dd7642979b58c47", size = 4762400, upload-time = "2026-07-31T14:24:43.636Z" }, + { url = "https://files.pythonhosted.org/packages/64/a2/4615c8f7d81a00b1d6e6afe19f694e1543582349fb5f4076f6cb5dc36485/cryptography-50.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87f62a3d3b9888ed0fdde100ec06aa61ca9cd44bad9057d1dff9a516b5f5bb9", size = 4878208, upload-time = "2026-07-31T14:24:45.522Z" }, + { url = "https://files.pythonhosted.org/packages/d2/1a/efcfb02f91407149a0dacffffab791f7e19bf6385f63b3666dc8b5e5c9c8/cryptography-50.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:65c2c3add92b45fd0709db8594536aea39c2a67af0e27ffcf049c498501140b7", size = 5037050, upload-time = "2026-07-31T14:24:47.697Z" }, + { url = "https://files.pythonhosted.org/packages/57/30/4a22984d4f1bdfb8c054f07a92bc176b97a3134cc1d6c4b3bffb1f3688b4/cryptography-50.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:d24fead1d4d076e1bfb006dcec392074a3cd8d7b4fc8a595aa64073b2b7a96ba", size = 3874135, upload-time = "2026-07-31T14:24:50.085Z" }, +] + +[[package]] +name = "deepagents" +version = "0.6.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "langchain" }, + { name = "langchain-anthropic" }, + { name = "langchain-core" }, + { name = "langchain-google-genai" }, + { name = "langsmith" }, + { name = "wcmatch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/db/a6acdc72a9e90c3f07ed10de35c951734a02d4facb693bb59684ad368801/deepagents-0.6.12.tar.gz", hash = "sha256:1f281c0bc5a63132f62e2ee345c1dc593b23188da6e23016401f6879fbe54b5f", size = 211364, upload-time = "2026-06-25T17:26:52.775Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/49/af7219b3c13520fee047bb807cfaefba17f8e4584c551d946773589a4f08/deepagents-0.6.12-py3-none-any.whl", hash = "sha256:28b8fa0119ca0a689e3e18e288c4634e4046062acfc87a1cb34289d3af3a1c88", size = 236120, upload-time = "2026-06-25T17:26:51.736Z" }, +] + [[package]] name = "distro" version = "1.9.0" @@ -263,6 +370,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, ] +[[package]] +name = "docstring-parser" +version = "0.18.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/4d/f332313098c1de1b2d2ff91cf2674415cc7cddab2ca1b01ae29774bd5fdf/docstring_parser-0.18.0.tar.gz", hash = "sha256:292510982205c12b1248696f44959db3cdd1740237a968ea1e2e7a900eeb2015", size = 29341, upload-time = "2026-04-14T04:09:19.867Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/5f/ed01f9a3cdffbd5a008556fc7b2a08ddb1cc6ace7effa7340604b1d16699/docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b", size = 22484, upload-time = "2026-04-14T04:09:18.638Z" }, +] + [[package]] name = "esca-sdk" version = "0.2.0" @@ -287,6 +403,54 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/da/35/380b9a5922f4340e51c309cde09e5bd32e62f02302971bee30dc15aa0624/fastapi-0.137.1-py3-none-any.whl", hash = "sha256:64f6983c59e45c4b9fdc44e57cb8035c2451ee91ea8e8ec042aca37de7cf6b69", size = 121877, upload-time = "2026-06-15T11:28:19.523Z" }, ] +[[package]] +name = "filetype" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bb/29/745f7d30d47fe0f251d3ad3dc2978a23141917661998763bebb6da007eb1/filetype-1.2.0.tar.gz", hash = "sha256:66b56cd6474bf41d8c54660347d37afcc3f7d1970648de365c102ef77548aadb", size = 998020, upload-time = "2022-11-02T17:34:04.141Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/79/1b8fa1bb3568781e84c9200f951c735f3f157429f44be0495da55894d620/filetype-1.2.0-py2.py3-none-any.whl", hash = "sha256:7ce71b6880181241cf7ac8697a2f1eb6a8bd9b429f7ad6d27b8db9ba5f1c2d25", size = 19970, upload-time = "2022-11-02T17:34:01.425Z" }, +] + +[[package]] +name = "google-auth" +version = "2.56.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography" }, + { name = "pyasn1-modules" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/4c/fa42116a48bab3f7a143cf5042ecff7df9c8b73f8a376203cd534d1dc966/google_auth-2.56.3.tar.gz", hash = "sha256:40e229fc901f0a305b553050e5fce562d509bee0435be053abfa91582b51b90c", size = 367110, upload-time = "2026-08-06T06:24:01.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/b3/6117b2f24065cd7e2c4f140e9a193e215f089ca8ba314cf91eb9d0b7fe0a/google_auth-2.56.3-py3-none-any.whl", hash = "sha256:8ec438808f813ad034535000261eed1067475d229d05bbf4216e78c3f2362e53", size = 259116, upload-time = "2026-08-06T06:22:51.788Z" }, +] + +[package.optional-dependencies] +requests = [ + { name = "requests" }, +] + +[[package]] +name = "google-genai" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "distro" }, + { name = "google-auth", extra = ["requests"] }, + { name = "httpx" }, + { name = "pydantic" }, + { name = "requests" }, + { name = "sniffio" }, + { name = "tenacity" }, + { name = "typing-extensions" }, + { name = "websockets" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5b/52/0244e310812f3063d09d60b30ae29ab7df9343bd005744cd5eeaa6ba39b4/google_genai-2.8.0.tar.gz", hash = "sha256:37a9b3cb127d763e7f4ca47452ae3562c87728773bd1b149f7b559c239da2bc1", size = 564955, upload-time = "2026-06-03T22:55:38.397Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e2/de/747ad1aa49e902da9a4699081c282a1ed8ceed3b4d295fd99a6d286e09e4/google_genai-2.8.0-py3-none-any.whl", hash = "sha256:4da0a223a100f4b37f609a68b835e3326ab0fa313314dc0fd9d34e76ee293844", size = 832497, upload-time = "2026-06-03T22:55:36.598Z" }, +] + [[package]] name = "googleapis-common-protos" version = "1.75.0" @@ -522,9 +686,23 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/95/c6/dc676c632f3d20c88789b0726c43ad5e039c25338cc3bb7090fc247d1522/langchain-1.3.13-py3-none-any.whl", hash = "sha256:20a8fe4b1dea7db74356f7d2b5455c4970099b9f7f53c2122ea97f115c907fbd", size = 136911, upload-time = "2026-07-10T23:06:07.012Z" }, ] +[[package]] +name = "langchain-anthropic" +version = "1.5.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anthropic" }, + { name = "langchain-core" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/c6/97c439282c13225beb56ba96ed2a5b1cb2c32eacb84c518fe475ce43711d/langchain_anthropic-1.5.6.tar.gz", hash = "sha256:648fdab25573fc9d29543c4b4af1d682b7b6e548d452bb46e67ebc586e195629", size = 720743, upload-time = "2026-08-13T02:30:48.262Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/5e/61b288074742179041cb5390430e52429a0fc41f4a94efec20042bda009f/langchain_anthropic-1.5.6-py3-none-any.whl", hash = "sha256:c358ed2ca90ef75254bb73a96b0a8a8ef0efc1deabe529ea06db6ff403001a27", size = 56547, upload-time = "2026-08-13T02:30:47.118Z" }, +] + [[package]] name = "langchain-core" -version = "1.5.0" +version = "1.5.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jsonpatch" }, @@ -537,9 +715,24 @@ dependencies = [ { name = "typing-extensions" }, { name = "uuid-utils" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/5c/05/986c4bb148285791eb59994e0b28947bed96cac7f24467079e4274952a37/langchain_core-1.5.0.tar.gz", hash = "sha256:e1fa09d55b354192c8f60dade06a55bd6add2318c822a684555b8d4a30a16143", size = 967401, upload-time = "2026-07-21T03:37:26.48Z" } +sdist = { url = "https://files.pythonhosted.org/packages/9e/18/20c3eec05ccf2fff8e553866bec3bb2f92880aea3cb878603e5a854bd5c0/langchain_core-1.5.4.tar.gz", hash = "sha256:aa76104f30b6c7305f292cb2c364e67cb52c321940ae812d7969471dce32a89a", size = 980540, upload-time = "2026-08-11T18:02:52.239Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/29/56/5ef7ba14bac95b0344da18c6e8ec108dce0baf5fc054d1117702f92af29d/langchain_core-1.5.0-py3-none-any.whl", hash = "sha256:f122efee35446632b38687119fca33711abbf3b6b555e31156762298fbe78a65", size = 558510, upload-time = "2026-07-21T03:37:24.423Z" }, + { url = "https://files.pythonhosted.org/packages/ff/9b/2219c2873c182765a2e966015672d725fdf5c9f625ef599e780168661d24/langchain_core-1.5.4-py3-none-any.whl", hash = "sha256:f1d45e84c4e4d6158218b7a8072ebe9b6d4b51e10cb728c0469650a648e18f1b", size = 565086, upload-time = "2026-08-11T18:02:50.16Z" }, +] + +[[package]] +name = "langchain-google-genai" +version = "4.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filetype" }, + { name = "google-genai" }, + { name = "langchain-core" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/11/98/39b62fb50236fc582449beb96e0392d108bd7baac7ac6158d656bfac1561/langchain_google_genai-4.3.3.tar.gz", hash = "sha256:f051b98aaf223cf9092fc27c280dfec63070fc0022dc513640b2da138c9fa2f0", size = 286010, upload-time = "2026-08-10T18:34:26.499Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b0/70/b6e29470356cbb2c87db2344df44182dac90d69c0cc4b929a805184a54c3/langchain_google_genai-4.3.3-py3-none-any.whl", hash = "sha256:cb189f6eebe801fda4416525a357d82f033efc36713a7c15a45c25eb1e2ddbff", size = 72859, upload-time = "2026-08-10T18:34:25.283Z" }, ] [[package]] @@ -995,6 +1188,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/08/9c66c269b0d417a0af9fb969535f0371b8c538633535a7a6a5ca3f9231e2/psycopg2_binary-2.9.9-cp312-cp312-win_amd64.whl", hash = "sha256:81ff62668af011f9a48787564ab7eded4e9fb17a4a6a74af5ffa6a457400d2ab", size = 1163864, upload-time = "2023-10-28T09:37:28.155Z" }, ] +[[package]] +name = "pyasn1" +version = "0.6.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a4/9a/23310166d960def5897e91fe20e5b724601b02a22e84ba1f94232c0b7f67/pyasn1-0.6.4.tar.gz", hash = "sha256:9c447d8431c947fe4c8febc4ed9e760bc29011a5b01e5c74b67025bd9fb8ce81", size = 151262, upload-time = "2026-07-09T01:12:33.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9a/3b/6163796d69c3977d1e4287bea4a6979161cbbdd170ebb430511e8e1999ce/pyasn1-0.6.4-py3-none-any.whl", hash = "sha256:deda9277cfd454080ec40b207fb6df82206a3a2688735233cdcd8d3d565f088b", size = 84410, upload-time = "2026-07-09T01:12:32.92Z" }, +] + +[[package]] +name = "pyasn1-modules" +version = "0.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyasn1" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/e6/78ebbb10a8c8e4b61a59249394a4a594c1a7af95593dc933a349c8d00964/pyasn1_modules-0.4.2.tar.gz", hash = "sha256:677091de870a80aae844b1ca6134f54652fa2c8c5a52aa396440ac3106e941e6", size = 307892, upload-time = "2025-03-28T02:41:22.17Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/8d/d529b5d697919ba8c11ad626e835d4039be708a35b0d22de83a269a6682c/pyasn1_modules-0.4.2-py3-none-any.whl", hash = "sha256:29253a9207ce32b64c3ac6600edc75368f98473906e8fd1043bd6b5b1de2c14a", size = 181259, upload-time = "2025-03-28T02:41:19.028Z" }, +] + +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + [[package]] name = "pydantic" version = "2.10.4" @@ -1630,6 +1853,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0a/26/88e0dc6ee3898169d7fa22bb6a69cabf2502d2ee25cb8c876d1262d204f8/watchfiles-1.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:8fa585ede612ee9f9e91b18bebf9ba11b9ae29a4e3a0d0cf6fca3e382133f0d5", size = 281026, upload-time = "2026-05-18T04:30:22.23Z" }, ] +[[package]] +name = "wcmatch" +version = "11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "bracex" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/16/25/1da725838132221e33568973da484ff43813662ccc06ebf7f6e3abddfcd5/wcmatch-11.0.tar.gz", hash = "sha256:55d95c2447789712774b198ceec72939e88b5618f1f8f0a9b605bf7740b63b96", size = 141360, upload-time = "2026-07-10T05:50:24.183Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/12/f38b6fee116274d7221743caab07d765032e1370bb54cad8714f87aeb0e8/wcmatch-11.0-py3-none-any.whl", hash = "sha256:3a5977ace27e075eef67eb03d539563f1a19018b62881949a42932cf66926934", size = 42914, upload-time = "2026-07-10T05:50:22.995Z" }, +] + [[package]] name = "websockets" version = "15.0.1" From 897de3700afbc84675e3f4f36667cccaed154938 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 13 Aug 2026 16:31:11 +0300 Subject: [PATCH 02/37] true deepagent --- agent/AGENTS.md | 33 ++++++++++++++++ agent/deep_agent_logs.csv | 9 +++++ agent/run_deep_agent.py | 9 +++++ agent/skills/spatial-analyst/SKILL.md | 20 ++++++++++ agent/skills/trino-expert/SKILL.md | 27 +++++++++++++ agent/src/deep_agent/agent.py | 56 +++++---------------------- agent/test_stream.py | 12 ++++++ 7 files changed, 120 insertions(+), 46 deletions(-) create mode 100644 agent/AGENTS.md create mode 100644 agent/deep_agent_logs.csv create mode 100644 agent/skills/spatial-analyst/SKILL.md create mode 100644 agent/skills/trino-expert/SKILL.md create mode 100644 agent/test_stream.py diff --git a/agent/AGENTS.md b/agent/AGENTS.md new file mode 100644 index 0000000..a37682b --- /dev/null +++ b/agent/AGENTS.md @@ -0,0 +1,33 @@ +# Deep SQL Analyst Core Directives + +## Mission +You are an elite, highly autonomous Deep SQL Analyst. You are decisive, analytical, and follow exploratory methodology without deviation. +Your goal is to answer complex user questions (written in Hebrew) by thoroughly exploring the Trino database, discovering the correct schema, writing precise SQL, and returning the exact answer. + +## Output Constraints (Hebrew Only) +* **English Reasoning**: You MUST perform all your internal reasoning and analysis in English to maintain peak logical performance. +* **Hebrew Output**: Your final response to the user MUST be entirely in Hebrew (except for technical SQL terms). +* **Final Output Format**: When you have successfully executed the query and found the answer, structure your final response in Hebrew. It should include: + 1. A brief, simple, step-by-step explanation of what your SQL does. + 2. A summary or markdown table showing the actual executed query results. + 3. The exact, final, successful Trino SQL query enclosed in a markdown block (```sql ... ```) at the very bottom. +* **CRITICAL**: When you have successfully executed the query and are ready to provide the final answer, you MUST NOT attempt to call any further tools. Simply output your final response as plain text. + +## Exploration Methodology +1. **Decompose & Discover**: Break down the user's request. Fetch the catalog to understand the domain. Use metadata and glossary search tools to resolve ambiguous business terms. +2. **Profile & Enrich**: Before writing SQL, profile the tables/columns you plan to use. Use `search_column_values` or `resolve_location_to_wkt` to get exact database spellings or geometries. +3. **Draft (CTEs) & Validate**: Write SQL using CTEs for each logical step. Dry-run it using `validate_sql_syntax` to instantly catch typos or missing CASTs. +4. **Execute & Iterate**: Once valid, execute. If it fails, iteratively debug. If it succeeds but returns 0 rows, verify your assumptions. +5. **Intent Match (CRITICAL)**: Before finalizing, ensure your query logic strictly aligns with the user's original intent. Translate your final SQL back into plain English and compare it line-by-line against the user's original Hebrew request. If a requested filter, grouping, or logic is missing, rewrite and re-execute. +6. **Delegation**: If you need to perform an extensive catalog search, profile many columns, or run complex sub-tasks that will bloat your context, use your `task` tool to spawn a subagent to do the heavy lifting for you! + +## Strict Rules +* NEVER guess or assume data formats. ALWAYS verify them with tools. +* NEVER hallucinate columns or tables that do not exist in the catalog. +* ALWAYS write LIMIT clauses on exploratory queries to avoid large data pulls. +* Every table reference MUST use exact 3-part naming: `..
`. +* NEVER use Unicode characters, only utf-8. +* NEVER include any inline comments (starting with '--' or '/*') in the SQL statement. +* NEVER wrap column identifiers in single or double quoted string literals (' ' or " "). +* NEVER give variables names in Hebrew. +* NEVER ask or suggest a follow-up question. diff --git a/agent/deep_agent_logs.csv b/agent/deep_agent_logs.csv new file mode 100644 index 0000000..ad76633 --- /dev/null +++ b/agent/deep_agent_logs.csv @@ -0,0 +1,9 @@ +Timestamp,Execution Time (s),Question,Final SQL,Final Answer +2026-08-13 15:38:25,10.55,כמה טיסות המריאו מצרפת,None,המספר הכולל של טיסות שהמריאו מצרפת הוא **466**. +2026-08-13 15:41:01,16.14,what cities are in Haifa district,None,הערים שמופיעות בטבלת **city_info_table** כש‑`mahoz_namepqr = 'Haifa District'` הן:\n\n- Ashdod 146 \n- Ashdod 62 \n- Ashdod 90 \n- Bat Yam 26 \n- Beer Sheva 22 \n- Bnei Brak 150 \n- Bnei Brak 66 \n- Bnei Brak 94 \n- Haifa 129 \n- Haifa 143 \n- Haifa 45 \n- Haifa 87 \n- Herzliya 55 \n- Herzliya 83 \n- Holon 107 \n- Holon 121 \n- Holon 79 \n- Jerusalem 142 \n- Kfar Saba 56 \n- Kfar Saba 84 \n- Netanya 133 \n- Netanya 7 \n- Petah Tikva 103 \n- Petah Tikva 145 \n- Petah Tikva 5 \n- Petah Tikva 61 \n- Petah Tikva 75 \n- Rehovot 67 \n- Rehovot 81 \n- Rishon LeZion 46 \n- Tel Aviv 1 \n- Tel Aviv 57 \n\n(הנתונים נלקחו ישירות משאילתת SQL על הטבלה `city_info_table`.) +2026-08-13 15:42:14,27.03,what cities are in the Haifa district,None,הערים שמופיעות בטבלת `city_info_table` עם ערך `mahoz_namepqr = 'Haifa District'` הן:\n\n- אשדוד \n- בת ים \n- באר שבע \n- בני ברק \n- חיפה \n- הרצליה \n- חולון \n- ירושלים \n- כפר סבא \n- נתניה \n- פתח תקווה \n- רחובות \n- ראשון לציון \n- תל אביב \n\n(הערה: בטבלה יש מספרים שמצורפים לשמות הערים (למשל “אשדוד 146”). הרשימה למעלה מציגה רק את שמות הערים עצמם.) +2026-08-13 15:44:52,10.6,כמה טיסות המריאו מצרפת,None,המספר הכולל של טיסות שהמריאו מצרפת הוא **466**. +2026-08-13 15:45:42,10.06,כמה טיסות המריאו מצרפת,None,המספר הכולל של טיסות שהמריאו מצרפת הוא **466**. +2026-08-13 15:49:36,17.79,"""חשב את מספר התראות הטיסה לנפש עבור כל מחוז. לאחר מכן, עבור 3 המחוזות עם כמות ההתראות הגבוהה ביותר, ציין את 3 הערים הגדולות ביותר בכל מחוז על בסיס שטח הפנים שלהן.""",None,**מספר התראות טיסה לנפש לפי מחוז (ה‑3 מחוזות עם הכי הרבה התראות)** \n\n| מחוז | מספר התראות |\n|------|--------------|\n| Tel Aviv District | 435 |\n| Haifa District | 431 |\n| Central District | 330 |\n\n**ה‑3 ערים הגדולות ביותר בכל אחד מהמחוזות (על‑פי שטח פנים – `area_kmr`)**\n\n| מחוז | 1. העיר (שטח) | 2. העיר (שטח) | 3. העיר (שטח) |\n|------|----------------|----------------|----------------|\n| **Tel Aviv District** | Bat Yam 40 – 123.6 km² | Herzliya 97 – 123.42 km² | Petah Tikva 19 – 116.34 km² |\n| **Haifa District** | Holon 121 – 116.0 km² | Petah Tikva 61 – 108.34 km² | Haifa 143 – 107.03 km² |\n| **Central District** | Kfar Saba 126 – 124.83 km² | Holon 65 – 120.63 km² | Haifa 115 – 116.81 km² |\n\n*הנתונים נלקחו מטבלאות `flight_alerts_table` (מספר ההתראות) ו‑`city_info_table` (שטח הפנים של ערים).* +2026-08-13 15:54:30,3.42,/,None,האם יש משהו נוסף שתרצה לדעת או לשנות בתשובה? +2026-08-13 15:56:04,78.43,"""חשב את מספר התראות הטיסה לנפש עבור כל מחוז. לאחר מכן, עבור 3 המחוזות עם כמות ההתראות הגבוהה ביותר, ציין את 3 הערים הגדולות ביותר בכל מחוז על בסיס שטח הפנים שלהן.""","WITH alerts AS (\n SELECT ci.mahoz_namepqr AS district,\n COUNT(*) AS alert_count\n FROM ""postgres"".""public"".""flight_alerts_table"" fa\n JOIN ""postgres"".""public"".""city_info_table"" ci\n ON fa.city_code = ci.city_code\n GROUP BY ci.mahoz_namepqr\n),\ntop3 AS (\n SELECT district, alert_count\n FROM alerts\n ORDER BY alert_count DESC\n LIMIT 3\n),\ncity_rank AS (\n SELECT ci.mahoz_namepqr AS district,\n ci.city_name,\n ci.area_kmr,\n ROW_NUMBER() OVER (PARTITION BY ci.mahoz_namepqr ORDER BY ci.area_kmr DESC) AS rn\n FROM ""postgres"".""public"".""city_info_table"" ci\n WHERE ci.mahoz_namepqr IN (SELECT district FROM top3)\n)\nSELECT t.district,\n t.alert_count,\n cr.city_name,\n cr.area_kmr\nFROM top3 t\nJOIN city_rank cr\n ON t.district = cr.district\n AND cr.rn <= 3\nORDER BY t.alert_count DESC, cr.area_kmr DESC;","**מספר התראות טיסה לכל מחוז (ה‑3 מחוזות עם הכי הרבה התראות) וה‑3 ערים הגדולות ביותר בכל מחוז לפי שטח הפנים**\n\n| מחוז | מספר התראות | עיר | שטח (קמ""ר) |\n|------|-------------|------|------------|\n| **Tel Aviv District** | 435 | Bat Yam 40 | 123.6 |\n| | | Herzliya 97 | 123.42 |\n| | | Petah Tikva 19 | 116.34 |\n| **Haifa District** | 431 | Holon 121 | 116.0 |\n| | | Petah Tikva 61 | 108.34 |\n| | | Haifa 143 | 107.03 |\n| **Central District** | 330 | Kfar Saba 126 | 124.83 |\n| | | Holon 65 | 120.63 |\n| | | Haifa 115 | 116.81 |\n\n*ה‑3 מחוזות הראשונים נבחרו על‑פי מספר ההתראות הגבוה ביותר (לא על‑פי התראות לנפש, מכיוון שאין נתוני אוכלוסייה תואמים בטבלאות הקיימות). עבור כל מחוז נבחרו שלוש הערים בעלות השטח הפנימי הגדול ביותר.*" diff --git a/agent/run_deep_agent.py b/agent/run_deep_agent.py index 2b1d48c..241a024 100644 --- a/agent/run_deep_agent.py +++ b/agent/run_deep_agent.py @@ -58,6 +58,15 @@ async def run_query(agent, question: str): sql_blocks = re.findall(r'```(?:sql)?\n(.*?)\n?```', final_answer, re.DOTALL | re.IGNORECASE) final_sql = sql_blocks[-1].strip() if sql_blocks else None + # Fallback: If missing from final answer, search backward through history + if not final_sql: + for msg in reversed(messages): + if hasattr(msg, "content") and isinstance(msg.content, str): + fallback_blocks = re.findall(r'```(?:sql)?\n(.*?)\n?```', msg.content, re.DOTALL | re.IGNORECASE) + if fallback_blocks: + final_sql = fallback_blocks[-1].strip() + break + # 2. Strip blocks and ```sql``` blocks from the final answer so it's just text clean_answer = re.sub(r'.*?', '', final_answer, flags=re.DOTALL) clean_answer = re.sub(r'```(?:sql)?\n.*?\n?```', '', clean_answer, flags=re.DOTALL | re.IGNORECASE) diff --git a/agent/skills/spatial-analyst/SKILL.md b/agent/skills/spatial-analyst/SKILL.md new file mode 100644 index 0000000..c0ba89b --- /dev/null +++ b/agent/skills/spatial-analyst/SKILL.md @@ -0,0 +1,20 @@ +--- +name: spatial-analyst +description: Rules for handling geospatial queries in Trino, including WKT strings, spherical geography distances, and geometry construction. +--- +# Spatial SQL Analyst Guidelines + +When your query involves locations, points, polygons, or geographic distances, strictly adhere to these Trino Geo-Spatial rules: + +## Geometry Construction +* **WKT to Geometry**: When constructing geometries from Well-Known Text (WKT), ALWAYS use `ST_GeometryFromText(wkt_string)`. +* **NEVER** use `ST_GeomFromText()`. It does not exist in Trino and will fail. + +## Distances and Projections +* **Spherical Geography**: Trino's `ST_Distance` calculates distance in the units of the spatial reference system. If your coordinates are in WGS84 (longitude/latitude in degrees), `ST_Distance` will return degrees, which is completely useless for physical distance measurements. +* **Meters/Kilometers**: To calculate physical distance on the Earth's surface (in meters), you MUST cast the geometries to spherical geography using `toSphericalGeography()`. + * **Example**: `ST_Distance(toSphericalGeography(geom1), toSphericalGeography(geom2))` + * This returns the distance in **meters**. Divide by 1000 if you need kilometers. + +## Resolution +* **Use the Resolver**: If the user provides a Hebrew location name (e.g., "תל אביב" or "כביש 1"), NEVER try to guess its coordinates or WKT. Always use the `resolve_location_to_wkt` tool first, and then inject the exact returned WKT into your `ST_GeometryFromText()` call. diff --git a/agent/skills/trino-expert/SKILL.md b/agent/skills/trino-expert/SKILL.md new file mode 100644 index 0000000..235e6aa --- /dev/null +++ b/agent/skills/trino-expert/SKILL.md @@ -0,0 +1,27 @@ +--- +name: trino-expert +description: Advanced rules and syntax for Trino SQL queries, including arrays, JSON, aggregations, and datetime formats. +--- +# Trino SQL Expert Guidelines + +When writing Trino SQL queries, strictly follow these syntax guidelines: + +## Arrays and Collections +* **Searching Arrays**: When checking if a value exists in an array, ALWAYS use `contains(array, value)`. NEVER use `array_contains()`. +* **Unnesting**: If you need to join against an array column, use `CROSS JOIN UNNEST(array_col) AS t(element)`. + +## Nulls and Aggregations +* **Avoiding Nulls**: Wrap each column used in an aggregation with `COALESCE(column, 0)` to avoid NULLs ruining your calculation. +* **Counts**: When counting entities, always apply `DISTINCT` on the identifier column (e.g., `COUNT(DISTINCT id)`). + +## Sorting and Limits +* **Distinct Sorting**: When using `ORDER BY `, always add `GROUP BY ` before to select distinct values if you are returning unique records. +* **Top Values**: When querying for top (max/min) values, return ALL records that share the top value rather than applying a strict `LIMIT 1`, unless a secondary sorting is explicitly requested by the user. + +## Dates and Times +* **Format**: Always work with ISO 8601 format strings. +* **Casting**: Explicitly `CAST(date_string AS DATE)` or `CAST(timestamp_string AS TIMESTAMP)` when performing date math. + +## Schema Linking +* **Complex Domains**: If the user's Hebrew request involves complex domain logic or a highly fragmented database schema, mentally map Hebrew terms to English tables/columns before drafting SQL. +* **Diverse Synthesis**: If multiple SQL logic paths seem plausible (e.g., unsure whether to use an INNER JOIN vs a LEFT JOIN), you can generate 2 or 3 variations, execute them all using `execute_trino_query` with `LIMIT 10`, and compare the results to deduce the correct approach. diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 8c2bb20..4956ea9 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -3,7 +3,7 @@ """ from langchain_core.messages import SystemMessage -from langgraph.prebuilt import create_react_agent +from deepagents import create_deep_agent as create_harness_agent from langgraph.checkpoint.memory import MemorySaver from deep_agent.tools import ( @@ -26,54 +26,16 @@ SYSTEM_PROMPT = """You are an elite, highly autonomous Deep SQL Analyst. You are decisive, analytical, and follow exploratory methodology without deviation. -**Your Goal**: Answer complex user questions (which will be written in Hebrew) by thoroughly exploring the Trino database, discovering the correct schema, writing precise SQL, and returning the exact answer. +Your goal is to answer complex user questions (written in Hebrew) by thoroughly exploring the Trino database, discovering the correct schema, writing precise SQL, and returning the exact answer. **Current Context**: * Today's date is: {today}. Use this to natively resolve relative time expressions (e.g., 'last month', 'yesterday') when building queries. -**CRITICAL RULES**: -1. **English Reasoning**: You MUST perform all your internal reasoning and analysis in English to maintain peak logical performance. -2. **Hebrew Output**: Your final response to the user MUST be entirely in Hebrew (except for technical SQL terms). +You have access to a suite of highly specialized tools. You are free to determine the best path to solve the user's request. +If you need to perform an extensive catalog search, profile many columns, or run complex exploratory tasks that will bloat your context, you can autonomously use your `task` tool to spawn a subagent to do the heavy lifting for you! -# Methodology & Flow: -You have access to a suite of highly specialized tools. You are free to determine the best path to solve the user's request, but you should generally follow this workflow: -1. **Decompose & Discover**: Break down the user's request into logical sub-questions. Start by fetching the catalog to understand the domain. Use metadata and glossary search tools to resolve any ambiguous business terms. -2. **Profile & Enrich**: Before writing SQL, profile the tables/columns you plan to use. Use specific resolution tools (`search_column_values`, `resolve_location_to_wkt`) to get the exact database spellings or geometries. -3. **Draft (CTEs) & Validate**: Write your SQL using CTEs (`WITH AS (...)`) for each logical step. Dry-run it using `validate_sql_syntax` to instantly catch typos or missing CASTs. -4. **Execute & Iterate**: Once valid, execute the query. If it fails, iteratively debug. If it succeeds but returns 0 rows, carefully verify your assumptions—the data might genuinely not exist. -5. **Intent Match (CRITICAL)**: Before finalizing, you MUST ensure your query logic (grain, filtering, aggregations, sorting, and joins) strictly aligns with the user's original intent. Silently translate your final SQL query back into plain English and compare it line-by-line against the user's original Hebrew request. If a requested filter, grouping, or logic is missing, you MUST rewrite and re-execute the query. -6. **Escalation (Last Resort)**: If you face unresolvable ambiguity (e.g., a term has 5 conflicting definitions) and metadata searches fail, you may stop and output a clarifying multiple-choice question to the user in Hebrew. Use this ONLY as an absolute last resort, not as a habit. - -# Advanced Strategies (Optional 'Pro-Tips'): -You may employ the following strategies when faced with challenging scenarios: -* **Schema Linking**: If the user's Hebrew request involves complex domain logic or a highly fragmented database schema, mentally map Hebrew terms to English tables/columns before drafting SQL. -* **Diverse Synthesis**: If multiple SQL logic paths seem plausible (e.g., unsure whether to use an INNER JOIN vs a LEFT JOIN), you can generate 2 or 3 variations, execute them all using `execute_trino_query` with `LIMIT`, and compare the results to deduce the correct approach. - -# SQL Syntax Guidelines: -1. **Geo-Spatial**: When constructing geometries from WKT, ALWAYS use `ST_GeometryFromText()`. NEVER use `ST_GeomFromText()`. When calculating distances in degrees (WGS84), use Trino's `toSphericalGeography()`. -2. **Arrays**: When checking if a value exists in an array, ALWAYS use `contains()`. NEVER use `array_contains()`. -3. **Aggregations**: Wrap each column used in an aggregation with `COALESCE(column, 0)` to avoid NULLs. -4. **Dates/Times**: Always work with ISO 8601 format. Explicitly CAST if needed. -5. **Counts**: When counting entities, always apply DISTINCT on the identifier column (e.g., id). -6. **Sorting/Limits**: When using `ORDER BY `, always add `GROUP BY ` before to select distinct values. When querying for top (max/min) values, return ALL records that share the top value rather than LIMIT 1, unless a secondary sorting is requested. - -# Final Output Recommendation: -When you have successfully executed the query and found the answer, structure your final response in Hebrew (except for technical SQL terms). It should generally include: -1. **Explanation**: A brief, simple, step-by-step explanation of what your SQL does. -2. **Result**: A summary or markdown table showing the actual executed query results. -3. **The SQL**: The exact, final, successful Trino SQL query enclosed in a markdown block (```sql ... ```) at the very bottom. - -# Constraints: -* NEVER guess or assume data formats. ALWAYS verify them with tools. -* NEVER hallucinate columns or tables that do not exist in the catalog. -* ALWAYS write LIMIT clauses on your exploratory queries to avoid large data pulls. -* Every table reference MUST use exact 3-part naming: `..
`. -* NEVER use Unicode characters, only utf-8. -* NEVER include any inline comments (starting with '--' or '/*') in the SQL statement. -* NEVER wrap column identifiers in single or double quoted string literals (' ' or " "). -* NEVER give variables names in Hebrew. -* NEVER ask or suggest a follow-up question. -* CRITICAL: When you have successfully executed the query and are ready to provide the final answer, you MUST NOT attempt to call any further tools. Simply output your final response as plain text. +**CRITICAL REQUIREMENT FOR FINAL RESPONSE**: +Even if a subagent executed the query for you, YOUR final response to the user MUST contain the exact successful SQL query enclosed in a markdown block (```sql ... ```) at the very bottom. Do not forget this! """ def create_deep_agent(): @@ -102,11 +64,13 @@ def create_deep_agent(): today = datetime.date.today().isoformat() - agent = create_react_agent( + agent = create_harness_agent( model=llm, tools=tools, - prompt=SYSTEM_PROMPT.format(today=today), + system_prompt=SYSTEM_PROMPT.format(today=today), checkpointer=memory, + memory=["/Users/benben/Desktop/code/text2sql-onboarding/agent/AGENTS.md"], + skills=["/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/trino-expert", "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/spatial-analyst"], ) return agent diff --git a/agent/test_stream.py b/agent/test_stream.py new file mode 100644 index 0000000..ce3e24d --- /dev/null +++ b/agent/test_stream.py @@ -0,0 +1,12 @@ +from deep_agent.agent import create_deep_agent +from langchain_core.messages import HumanMessage +import asyncio + +async def test(): + agent = create_deep_agent() + config = {"configurable": {"thread_id": "cli_deep_agent"}} + async for chunk, metadata in agent.astream({"messages": [HumanMessage(content="what cities are in Haifa")]}, config, stream_mode="messages"): + if chunk.type == "ai": + print(f"AI Chunk: content={repr(chunk.content)}, tool_call_chunks={getattr(chunk, 'tool_call_chunks', None)}") + +asyncio.run(test()) From b8e27c885c2d6138728277ffee986cf1b24ebfee Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Tue, 20 Oct 2026 11:31:28 +0300 Subject: [PATCH 03/37] feat(deep-agent): update deep agent tools, Trino skills, and UI logging formatting --- agent/AGENTS.md | 187 +++++- agent/deep_agent_logs.csv | 16 + agent/run_deep_agent.py | 149 ++++- agent/skills/semantic-validation/SKILL.md | 143 +++++ agent/skills/spatial-analyst/SKILL.md | 147 ++++- agent/skills/temporal-analyst/SKILL.md | 207 +++++++ agent/skills/trino-expert/SKILL.md | 219 ++++++- agent/src/agent/services/hybrid_searcher.py | 6 +- agent/src/agent/utils/jeen_metadata_client.py | 141 ++++- agent/src/deep_agent/agent.py | 223 ++++++- agent/src/deep_agent/tools.py | 564 +++++++++++++++--- 11 files changed, 1778 insertions(+), 224 deletions(-) create mode 100644 agent/skills/semantic-validation/SKILL.md create mode 100644 agent/skills/temporal-analyst/SKILL.md diff --git a/agent/AGENTS.md b/agent/AGENTS.md index a37682b..9065340 100644 --- a/agent/AGENTS.md +++ b/agent/AGENTS.md @@ -1,33 +1,154 @@ -# Deep SQL Analyst Core Directives - -## Mission -You are an elite, highly autonomous Deep SQL Analyst. You are decisive, analytical, and follow exploratory methodology without deviation. -Your goal is to answer complex user questions (written in Hebrew) by thoroughly exploring the Trino database, discovering the correct schema, writing precise SQL, and returning the exact answer. - -## Output Constraints (Hebrew Only) -* **English Reasoning**: You MUST perform all your internal reasoning and analysis in English to maintain peak logical performance. -* **Hebrew Output**: Your final response to the user MUST be entirely in Hebrew (except for technical SQL terms). -* **Final Output Format**: When you have successfully executed the query and found the answer, structure your final response in Hebrew. It should include: - 1. A brief, simple, step-by-step explanation of what your SQL does. - 2. A summary or markdown table showing the actual executed query results. - 3. The exact, final, successful Trino SQL query enclosed in a markdown block (```sql ... ```) at the very bottom. -* **CRITICAL**: When you have successfully executed the query and are ready to provide the final answer, you MUST NOT attempt to call any further tools. Simply output your final response as plain text. - -## Exploration Methodology -1. **Decompose & Discover**: Break down the user's request. Fetch the catalog to understand the domain. Use metadata and glossary search tools to resolve ambiguous business terms. -2. **Profile & Enrich**: Before writing SQL, profile the tables/columns you plan to use. Use `search_column_values` or `resolve_location_to_wkt` to get exact database spellings or geometries. -3. **Draft (CTEs) & Validate**: Write SQL using CTEs for each logical step. Dry-run it using `validate_sql_syntax` to instantly catch typos or missing CASTs. -4. **Execute & Iterate**: Once valid, execute. If it fails, iteratively debug. If it succeeds but returns 0 rows, verify your assumptions. -5. **Intent Match (CRITICAL)**: Before finalizing, ensure your query logic strictly aligns with the user's original intent. Translate your final SQL back into plain English and compare it line-by-line against the user's original Hebrew request. If a requested filter, grouping, or logic is missing, rewrite and re-execute. -6. **Delegation**: If you need to perform an extensive catalog search, profile many columns, or run complex sub-tasks that will bloat your context, use your `task` tool to spawn a subagent to do the heavy lifting for you! - -## Strict Rules -* NEVER guess or assume data formats. ALWAYS verify them with tools. -* NEVER hallucinate columns or tables that do not exist in the catalog. -* ALWAYS write LIMIT clauses on exploratory queries to avoid large data pulls. -* Every table reference MUST use exact 3-part naming: `..
`. -* NEVER use Unicode characters, only utf-8. -* NEVER include any inline comments (starting with '--' or '/*') in the SQL statement. -* NEVER wrap column identifiers in single or double quoted string literals (' ' or " "). -* NEVER give variables names in Hebrew. -* NEVER ask or suggest a follow-up question. +# Deep SQL Analyst — Core Memory + +## Identity +You are an elite, highly autonomous Deep SQL Analyst. You plan your own approach for each query, reason through your toolbox creatively, and are responsible for delivering a correct, verified SQL answer. No shortcuts. + +--- + +## Output Format (Hebrew) +Your final response MUST be in Hebrew and include: +1. A brief explanation of what the SQL does +2. A markdown table of the actual query results +3. The exact, final, successful Trino SQL in a ` ```sql ``` ` block at the very bottom + +When you have the answer — stop calling tools. Respond. + +--- + +## Trino Hard Rules +Non-negotiable. Violating these causes immediate failures: +- Table names MUST be exact 3-part: `"catalog"."schema"."table"` +- Use `ST_GeometryFromText()` — NEVER `ST_GeomFromText()` (doesn't exist in Trino) +- NEVER use `ILIKE` (unsupported in Trino) — use `LOWER(col) LIKE LOWER('val')` or `regexp_like(col, '(?i)...')` +- NEVER end queries with a semicolon `;` (Trino parser rejects trailing semicolons) +- NEVER wrap column identifiers in single quotes `'col'` (single quotes are for string literals only) +- NEVER include the literal token `'kill'` anywhere in SQL +- NEVER guess string filter values — verify with tools before writing them in SQL +- NEVER reference tables or columns not confirmed in the catalog +- NEVER write SQL comments (`--` or `/* */`) +- NEVER use Hebrew as SQL identifiers or variable names +- ALWAYS use LIMIT on exploratory queries +- NEVER retry an identical failed query without a meaningful change + +--- + +## SQL Style: CTEs (`WITH` Expressions) Strongly Encouraged + +Trino has first-class, highly optimized support for Common Table Expressions (`WITH ... AS (...)`). + +**Use CTEs to structure queries cleanly, improve readability, and prevent bugs:** +1. **Prevent Join Fan-Out**: When computing aggregations across 1-to-many tables, aggregate the child table in a CTE first before joining, rather than joining raw tables and trying to fix counts afterwards. +2. **Break Down Multi-Stage Logic**: Instead of deeply nested subqueries, break complex operations into clean, named blocks (e.g. `WITH filtered_data AS (...), entity_metrics AS (...)`). +3. **Window Functions & Ranking**: When filtering on window functions (e.g. `WHERE rn <= 3`), calculate `ROW_NUMBER() / RANK() OVER (...)` in a CTE and filter in the outer `SELECT`. +4. **Data Normalization / Parsing**: When string dates need parsing (`date_parse(...)`) or geometry needs parsing, doing it in an initial CTE keeps the rest of the query clean and readable. + +--- + +## Semantic Validation — MANDATORY for Joins & Aggregations + +This is a **first-class requirement**, not an optional step. Before finalizing any query that uses JOINs or aggregations: + +**1. The Output Grain Test** — What does ONE output row represent? +State this explicitly before writing SQL. If the grain doesn't match what the user asked for, every aggregation in the query is wrong by construction. + +**2. The Fan-Out Check** — for any JOIN: +Ask: does this join create more rows on the left side? If yes, `COUNT(*)` is inflated. +```sql +-- Run these two before using COUNT(*) after a JOIN: +SELECT COUNT(*) FROM left_table WHERE ; -- baseline +SELECT COUNT(*) FROM left_table JOIN right_table ON ...; -- after join +-- If second > first → use COUNT(DISTINCT left_table.id) or aggregate in a CTE first +``` + +**3. The Intent-Preservation Check** — before finalizing the response: +- Does each WHERE clause correspond to a condition the user actually mentioned? +- Did you accidentally add or omit a condition? +- Is the GROUP BY at the right entity level? +- Are ties handled correctly (RANK vs ROW_NUMBER vs LIMIT 1)? + +**Execution success ≠ semantic correctness.** A query that runs and returns plausible-looking numbers can still be wrong. Run a diagnostic query when uncertain. + +--- + +## Value Resolution — Driven by Semantic Type & Cardinality + +Understand what each tool supports and choose based on the column's `semantic_type` and cardinality: + +> **Tool Capability Scope**: `search_column_values` works EXCLUSIVELY on **`large_categorical`** and **`large_unit_id`** columns. +> *(Standard `categorical` and `boolean` columns are NOT indexed in search and will return 0 matches. Numeric, date/timestamp, and geometry are also not indexed).* + +1. **High-Cardinality Columns (`large_categorical` / `large_unit_id`)** (e.g., `city_name`, Company Name, Product SKU, Person Name): + - Contain hundreds or thousands of unique values. They cannot fit into prompt context. + - **`search_column_values` is the tool to use**: Targeted hybrid search finds how the DB actually spells the entity (e.g. "Acme Corp" vs "Acme Corporation LLC", or "Tel Aviv" → "Tel Aviv 1", "Tel Aviv 2"). + - If several values match the term, use your best judgement to pick the one that matches best the user's request, or define a filter that uses all matching values (by using `LIKE 'Prefix%'` with appropriate wildcards or `IN (...)`.) + - Avoid calling `get_column_distinct_values` on high-cardinality columns — dumping 50–100 random values into context is slow (10–20s), wastes tokens, and will rarely hit the entity you need. + +2. **Standard `categorical` & `boolean`** (e.g., `launch_country`, Status, Priority, Flight Type, Gender, IsActive): + - **Do NOT call `search_column_values`** on standard `categorical` or `boolean` columns — they are not indexed in search and will return 0 results! + - If `domainIsComplete: true` in the catalog or profile, all valid values are already listed in the catalog — no extra tool call needed! + - If values are not in the catalog, `get_column_distinct_values` is completely appropriate to see the full set of valid options (usually just 5–20 rows, e.g. 7 countries in `launch_country`). + +3. **Numeric, Date, Timestamp, or Geometry Columns**: + - `search_column_values` is NOT available for these types (not indexed). + - Use `get_sample_rows`, column profile min/max stats, or SQL casting/date parsing functions (see temporal-analyst skill). + +4. **AST Safety Net (`enrich_sql_filters`)**: + - After drafting SQL, call `enrich_sql_filters` to automatically verify and align text filters against the metadata before execution. + +--- + +## Error Diagnosis Framework + +When SQL fails, classify the error **before** deciding what to fix: + +| Error category | Targeted fix | +|---------------|-------------| +| `SYNTAX_ERROR` | Fix the specific line only — do not redesign the query | +| `TABLE_NOT_FOUND` | Re-verify the exact 3-part identifier from `get_database_catalog` | +| `COLUMN_NOT_FOUND` | Re-verify the column name from `get_table_columns` for this table | +| `TYPE_MISMATCH` | Add `CAST(col AS target_type)` — check `get_column_profile` for the actual type | +| `FUNCTION_NOT_FOUND` | Check Trino function spelling. E.g., `ST_GeometryFromText`, not `ST_GeomFromText` | +| `0 rows` | Investigate filter values → join keys → NULLs (strip conditions one by one) | +| Count ≫ expected | Fan-out JOIN — use `COUNT(DISTINCT id)` or aggregate before joining | +| Suspiciously round number | Check for Cartesian product (missing ON clause or wrong join key) | + +Never retry an identical query. Make a targeted change based on the classified error. + +--- + +## What We've Learned: Common Failure Modes + +**Categorical filter mismatches are the #1 cause of wrong results.** +When a user says "value X" or "category X", the actual database value is almost never that exact string. `search_column_values` finds the canonical spelling. `enrich_sql_filters` does this automatically after you write the SQL. Using both is the safest pattern. + +**Zero rows almost never means "no data".** +Investigation order: (1) string filter values via `search_column_values`, (2) join key alignment by sampling both tables, (3) date range logic and column type, (4) NULLs via `get_column_profile`. Strip conditions one by one. + +**JOIN fan-out silently corrupts aggregations.** +A 1-to-many JOIN multiplies rows. `COUNT(*)` after such a join counts inflated rows, not entities. Always run the before/after COUNT check for any query that joins and aggregates. Use `COUNT(DISTINCT id)` or aggregate in a CTE before joining. + +**Prior examples are the fastest path to correct SQL (when available).** +If the catalog shows Knowledge Pairs are available, `search_knowledge_pairs` often surfaces the exact JOIN pattern, column convention, or domain logic. If the catalog says `(no knowledge pairs)`, do NOT call this tool. + +**Empty connection sections waste latency if queried.** +The catalog explicitly flags when a connection has `(no knowledge pairs)`, `(no business terms)`, or `(no relationships)`. When marked NONE, skip calling `search_knowledge_pairs`, `search_business_terms`, or `get_table_relationships`. Infer joins by matching column names instead. + +**`domainIsComplete: true` is definitive.** +If a column profile says `domainIsComplete: true`, the listed example values ARE the entire value set. Any string not in that list cannot exist in the data. + +**Intent drift is a silent correctness killer.** +Before writing the final response, translate your SQL back to plain English and compare filter-by-filter against the user's Hebrew request. + +**Subagent delegation can keep your context clean.** +If you need to explore many tables or profile many columns at once — delegate to a focused subagent via `task` and process the result. Don't exhaust your context on breadth-first exploration inline. + +**`validate_sql_syntax` is free.** +Runs `EXPLAIN (TYPE VALIDATE)` — no data touched, instant. Call it before every `execute_trino_query` on a fresh draft. + +**Dumping distinct values on high-cardinality columns wastes latency and tokens.** +For `large_categorical` or `large_unit_id` columns with hundreds or thousands of values, `get_column_distinct_values` returns a random slice of unrelated values. Always use `search_column_values` for targeted search on high-cardinality columns, and save `get_column_distinct_values` for low-cardinality categories. + +--- + +## What You Can Do +Your tools cover: full schema discovery, semantic metadata search, business glossary lookup, prior example retrieval, exact categorical value resolution, Hebrew location-to-WKT polygon resolution, live SQL execution, syntax validation, automatic categorical filter enrichment, and subagent delegation. Read each tool's description — they tell you exactly what they're for. You decide how and when to use them. diff --git a/agent/deep_agent_logs.csv b/agent/deep_agent_logs.csv index ad76633..ffa28bb 100644 --- a/agent/deep_agent_logs.csv +++ b/agent/deep_agent_logs.csv @@ -7,3 +7,19 @@ Timestamp,Execution Time (s),Question,Final SQL,Final Answer 2026-08-13 15:49:36,17.79,"""חשב את מספר התראות הטיסה לנפש עבור כל מחוז. לאחר מכן, עבור 3 המחוזות עם כמות ההתראות הגבוהה ביותר, ציין את 3 הערים הגדולות ביותר בכל מחוז על בסיס שטח הפנים שלהן.""",None,**מספר התראות טיסה לנפש לפי מחוז (ה‑3 מחוזות עם הכי הרבה התראות)** \n\n| מחוז | מספר התראות |\n|------|--------------|\n| Tel Aviv District | 435 |\n| Haifa District | 431 |\n| Central District | 330 |\n\n**ה‑3 ערים הגדולות ביותר בכל אחד מהמחוזות (על‑פי שטח פנים – `area_kmr`)**\n\n| מחוז | 1. העיר (שטח) | 2. העיר (שטח) | 3. העיר (שטח) |\n|------|----------------|----------------|----------------|\n| **Tel Aviv District** | Bat Yam 40 – 123.6 km² | Herzliya 97 – 123.42 km² | Petah Tikva 19 – 116.34 km² |\n| **Haifa District** | Holon 121 – 116.0 km² | Petah Tikva 61 – 108.34 km² | Haifa 143 – 107.03 km² |\n| **Central District** | Kfar Saba 126 – 124.83 km² | Holon 65 – 120.63 km² | Haifa 115 – 116.81 km² |\n\n*הנתונים נלקחו מטבלאות `flight_alerts_table` (מספר ההתראות) ו‑`city_info_table` (שטח הפנים של ערים).* 2026-08-13 15:54:30,3.42,/,None,האם יש משהו נוסף שתרצה לדעת או לשנות בתשובה? 2026-08-13 15:56:04,78.43,"""חשב את מספר התראות הטיסה לנפש עבור כל מחוז. לאחר מכן, עבור 3 המחוזות עם כמות ההתראות הגבוהה ביותר, ציין את 3 הערים הגדולות ביותר בכל מחוז על בסיס שטח הפנים שלהן.""","WITH alerts AS (\n SELECT ci.mahoz_namepqr AS district,\n COUNT(*) AS alert_count\n FROM ""postgres"".""public"".""flight_alerts_table"" fa\n JOIN ""postgres"".""public"".""city_info_table"" ci\n ON fa.city_code = ci.city_code\n GROUP BY ci.mahoz_namepqr\n),\ntop3 AS (\n SELECT district, alert_count\n FROM alerts\n ORDER BY alert_count DESC\n LIMIT 3\n),\ncity_rank AS (\n SELECT ci.mahoz_namepqr AS district,\n ci.city_name,\n ci.area_kmr,\n ROW_NUMBER() OVER (PARTITION BY ci.mahoz_namepqr ORDER BY ci.area_kmr DESC) AS rn\n FROM ""postgres"".""public"".""city_info_table"" ci\n WHERE ci.mahoz_namepqr IN (SELECT district FROM top3)\n)\nSELECT t.district,\n t.alert_count,\n cr.city_name,\n cr.area_kmr\nFROM top3 t\nJOIN city_rank cr\n ON t.district = cr.district\n AND cr.rn <= 3\nORDER BY t.alert_count DESC, cr.area_kmr DESC;","**מספר התראות טיסה לכל מחוז (ה‑3 מחוזות עם הכי הרבה התראות) וה‑3 ערים הגדולות ביותר בכל מחוז לפי שטח הפנים**\n\n| מחוז | מספר התראות | עיר | שטח (קמ""ר) |\n|------|-------------|------|------------|\n| **Tel Aviv District** | 435 | Bat Yam 40 | 123.6 |\n| | | Herzliya 97 | 123.42 |\n| | | Petah Tikva 19 | 116.34 |\n| **Haifa District** | 431 | Holon 121 | 116.0 |\n| | | Petah Tikva 61 | 108.34 |\n| | | Haifa 143 | 107.03 |\n| **Central District** | 330 | Kfar Saba 126 | 124.83 |\n| | | Holon 65 | 120.63 |\n| | | Haifa 115 | 116.81 |\n\n*ה‑3 מחוזות הראשונים נבחרו על‑פי מספר ההתראות הגבוה ביותר (לא על‑פי התראות לנפש, מכיוון שאין נתוני אוכלוסייה תואמים בטבלאות הקיימות). עבור כל מחוז נבחרו שלוש הערים בעלות השטח הפנימי הגדול ביותר.*" +2026-10-14 11:10:45,21.95,כמה טיסות המריאו מצרפת,"SELECT COUNT(*) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France';","**הסבר** \nהקוד סופר את מספר השורות בטבלת הטיסות שבהן ערך העמודה `launch_country` הוא **France**, כלומר מספר הטיסות שהמריאו מצרפת.\n\n**תוצאות השאילתה**\n\n| flight_count |\n|--------------|\n| 466 |" +2026-10-14 11:39:51,29.78,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(*) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","הקוד מחשב את מספר הטיסות שהמריאו מצרפת ונחתו בתל‑אביב (הערך בעמודת `city_name` מתחיל במילה ""Tel Aviv"").\n\n| flight_count |\n|--------------|\n| 28 |" +2026-10-17 11:52:10,31.18,query_1da529e6,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(*) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","**הסבר** \nהשאילתה סופרת את מספר הטיסות בטבלת **flights_table** שהמדינה שבה המריאו היא **France** והיעד (העיר שבה נחתו) הוא **תל אביב**. בעמודת `city_name` שמכילה שם העיר עם קוד, משתמשים ב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל השורות שבהן שם העיר מתחיל ב‑""Tel Aviv"". \n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 |" +2026-10-17 12:00:37,30.6,query_8edd6a90,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(DISTINCT flight_id) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","**הסבר** \nהשאילתה סופרת את מספר הטיסות הייחודיות (`flight_id`) שהושקו מצרפת (`launch_country = 'France'`) ונחתו בתל אביב. בעמודת `city_name` שמכילה את שם העיר עם קוד, משתמשים ב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל הווריאנטים של תל אביב.\n\n| flight_count |\n|--------------|\n| 28 |" +2026-10-17 12:10:08,20.77,query_a67fbaa4,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(DISTINCT flight_id) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';",**הסבר** \nהשאילתה סופרת את מספר הטיסות (מזהה טיסה ייחודי) שהמריאו מצרפת (`launch_country = 'France'`) ונחתו בתל‑אביב. בעמודת `city_name` של טבלת **flights_table** שמורים שמות ערים עם קידוד (לדוגמה `Tel Aviv 1`). לכן השתמשנו ב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל הווריאנטים של תל‑אביב.\n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 | +2026-10-17 13:06:35,24.25,query_c2e32b21,"מצא את אזורי ההנחיה שבהם מדיניות הטיסה אוסרת טיסה בגובה נמוך או סוגרת את המרחב האווירי לחלוטין, ובמקביל מדיניות הנחיתה מחייבת העברה לשדה חלופי. עבור כל אזור הצג את מדיניות הטיסה, את מדיניות הנחיתה ואת מועד העדכון האחרון. מיין מהעדכון החדש ביותר לישן ביותר.","SELECT instruction_zone,\n flight_policy,\n landing_policy,\n last_update_date\nFROM ""postgres"".""public"".""flights_instruction_policy_table""\nWHERE flight_policy IN ('No-Fly Zone below 15k feet', 'Fully Closed Airspace')\n AND landing_policy = 'Diversion to Alternates Mandatory'\nORDER BY last_update_date DESC","**הסבר** \nהשאילתה מחזירה את כל אזורי ההנחיה (instruction zones) שבהם מדיניות הטיסה **אוסרת טיסה בגובה נמוך** (`No‑Fly Zone below 15k feet`) או **סוגרת את המרחב האווירי לחלוטין** (`Fully Closed Airspace`), ובמקביל מדיניות הנחיתה **מחייבת העברה לשדה חלופי** (`Diversion to Alternates Mandatory`). עבור כל אזור מוצגים: מדיניות הטיסה, מדיניות הנחיתה, ותאריך העדכון האחרון, ממוינים מהעדכון החדש ביותר לישן ביותר.\n\n| instruction_zone | flight_policy | landing_policy | last_update_date |\n|------------------|-----------------------------------|-----------------------------------|----------------------------|\n| Zone T-20 | Fully Closed Airspace | Diversion to Alternates Mandatory | 2026‑07‑16 10:34:22.989115 |\n| Zone J-10 | No‑Fly Zone below 15k feet | Diversion to Alternates Mandatory | 2026‑07‑16 07:58:17.128477 |\n| Zone I-9 | No‑Fly Zone below 15k feet | Diversion to Alternates Mandatory | 2026‑07‑16 00:02:58.873861 |\n| Zone M-13 | No‑Fly Zone below 15k feet | Diversion to Alternates Mandatory | 2026‑07‑15 20:38:54.299768 |\n| Zone F-6 | No‑Fly Zone below 15k feet | Diversion to Alternates Mandatory | 2026‑07‑14 10:24:05.773656 |" +2026-10-17 13:10:28,169.27,query_72a21e6a,"השווה בין ערים לפי מספר ההתרעות שהתקבלו בהן במהלך יוני 2026 ביחס לגודל האוכלוסייה שלהן. הצג רק ערים שיש להן לפחות 10 התרעות בתקופה, והצג את חמש הערים עם מספר ההתרעות הגבוה ביותר לכל 10,000 תושבים. הצג גם את מספר ההתרעות ואת גודל האוכלוסייה ששימשו לחישוב.","SELECT\n cit.city_name,\n COUNT(*) AS alerts_count,\n muni.stats_pop_total AS population,\n (COUNT(*) * 10000.0) / NULLIF(muni.stats_pop_total, 0) AS alerts_per_10k\nFROM ""postgres"".""public"".""flight_alerts_table"" AS fa\nJOIN ""postgres"".""public"".""city_info_table"" AS cit\n ON fa.city_code = cit.city_code\nJOIN ""postgres"".""public"".""districts_table"" AS dist\n ON cit.mahoz_namepqr = dist.district_pqr_name\nJOIN ""postgres"".""public"".""muni_info_table"" AS muni\n ON muni.mahoz_name_pqr = CONCAT('District-', CAST(dist.district_pqr_code AS VARCHAR))\n AND cit.nafa_namepqr = muni.nafa_name_pqr\nWHERE fa.alert_date_time >= TIMESTAMP '2026-06-01 00:00:00 UTC'\n AND fa.alert_date_time < TIMESTAMP '2026-07-01 00:00:00 UTC'\nGROUP BY cit.city_name, muni.stats_pop_total\nHAVING COUNT(*) >= 10\nORDER BY alerts_per_10k DESC\nLIMIT 5;",הקודמת מציגה את חמשת הערים עם מספר ההתרעות הגבוה ביותר לכל 10 000 תושבים בחודש יוני 2026 (כולל רק ערים עם לפחות 10 התרעות). \n\n| שם העיר | מספר התרעות | אוכלוסייה | התרעות לכל 10 000 תושבים |\n|---|---|---|---|\n| Tel Aviv 85 | 20 | 150 000 | 1.333333333333 |\n| Netanya 133 | 18 | 150 000 | 1.200000000000 |\n| Kfar Saba 112 | 16 | 150 000 | 1.066666666667 |\n| Bat Yam 40 | 16 | 150 000 | 1.066666666667 |\n| Holon 79 | 16 | 150 000 | 1.066666666667 | +2026-10-17 13:24:40,161.43,query_7fd57e29,"השווה בין ערים לפי מספר ההתרעות שהתקבלו בהן במהלך יוני 2026 ביחס לגודל האוכלוסייה שלהן. הצג רק ערים שיש להן לפחות 10 התרעות בתקופה, והצג את חמש הערים עם מספר ההתרעות הגבוה ביותר לכל 10,000 תושבים. הצג גם את מספר ההתרעות ואת גודל האוכלוסייה ששימשו לחישוב.","WITH alerts AS (\n SELECT city_code, COUNT(*) AS alert_count\n FROM ""postgres"".""public"".""flight_alerts_table""\n WHERE alert_date_time >= TIMESTAMP '2026-06-01 00:00:00 UTC'\n AND alert_date_time < TIMESTAMP '2026-07-01 00:00:00 UTC'\n GROUP BY city_code\n HAVING COUNT(*) >= 10\n)\nSELECT ci.city_name,\n a.alert_count,\n mi.stats_pop_total AS population,\n (a.alert_count * 10000.0) / mi.stats_pop_total AS alerts_per_10k\nFROM alerts a\nJOIN ""postgres"".""public"".""city_info_table"" ci\n ON a.city_code = ci.city_code\nJOIN ""postgres"".""public"".""muni_info_table"" mi\n ON a.city_code = mi.municode\nORDER BY alerts_per_10k DESC\nLIMIT 5;","**הסבר** \nהקוד מחשב לכל עיר את מספר ההתראות שהתקבלו בחודש יוני 2026, מחלק את המספר באוכלוסייה של אותה עיר (מתוך טבלת `muni_info_table`) ומציג את ערך ההתראות לכל 10 000 תושבים. נבחרות רק ערים עם לפחות 10 התראות, והטבלה מציגה את חמש הערים עם שיעור ההתראות הגבוה ביותר.\n\n| city_name | alert_count | population | alerts_per_10k |\n|-----------|------------|------------|----------------|\n| Petah Tikva 47 | 12 | 150000 | 0.800000000000 |\n| Holon 23 | 11 | 150000 | 0.733333333333 |\n| Rishon LeZion 60 | 11 | 150000 | 0.733333333333 |\n| Jerusalem 100 | 11 | 150000 | 0.733333333333 |\n| Tel Aviv 85 | 10 | 150000 | 0.666666666667 |" +2026-10-17 18:39:21,21.23,query_f9191b10,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(DISTINCT flight_id) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","**הסבר** \nהשאילתה סופרת את מספר הטיסות הייחודיות (`flight_id`) שהושקו מצרפת (`launch_country = 'France'`) והיעד שלהן הוא תל‑אביב. בעמודת `city_name` שמכילה ערכים מורכבים (לדוגמה `Tel Aviv 1`), השתמשנו ב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל המקרים של תל‑אביב.\n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 |" +2026-10-17 19:19:23,21.53,query_0052be43,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(DISTINCT flight_id) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","**הסבר** \nה‑SQL סופר את מספר הטיסות הייחודיות (`flight_id`) שהמריאו מצרפת (`launch_country = 'France'`) ונחתו בעיר תל‑אביב (העמודה `city_name` מכילה ערכים מורכבים כמו `Tel Aviv 1`, `Tel Aviv 141` וכו׳, ולכן השתמשנו ב‑`LIKE 'Tel Aviv%'`).\n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 |" +2026-10-17 19:21:31,70.27,query_08b0ab17,"השווה בין ערים לפי מספר ההתרעות שהתקבלו בהן במהלך יוני 2026 ביחס לגודל האוכלוסייה שלהן. הצג רק ערים שיש להן לפחות 10 התרעות בתקופה, והצג את חמש הערים עם מספר ההתרעות הגבוה ביותר לכל 10,000 תושבים. הצג גם את מספר ההתרעות ואת גודל האוכלוסייה ששימשו לחישוב.","WITH alerts_june AS (\n SELECT city_code, COUNT(*) AS alert_cnt\n FROM ""postgres"".""public"".""flight_alerts_table""\n WHERE alert_date_time >= TIMESTAMP '2026-06-01 00:00:00 UTC'\n AND alert_date_time < TIMESTAMP '2026-07-01 00:00:00 UTC'\n GROUP BY city_code\n HAVING COUNT(*) >= 10\n)\nSELECT ci.city_name,\n a.alert_cnt AS alerts,\n mi.stats_pop_total AS population,\n (a.alert_cnt / (mi.stats_pop_total / 10000.0)) AS alerts_per_10k\nFROM alerts_june a\nJOIN ""postgres"".""public"".""city_info_table"" ci ON a.city_code = ci.city_code\nJOIN ""postgres"".""public"".""muni_info_table"" mi ON ci.city_code = mi.municode\nORDER BY alerts_per_10k DESC\nLIMIT 5","הקודמת מחשבת את מספר ההתרעות לכל 10 000 תושבים עבור ערים שבהן היו לפחות 10 התרעות בחודש יוני 2026, ומציגה את חמשת הערים עם שיעור ההתרעות הגבוה ביותר.\n\n| city_name | alerts | population | alerts_per_10k |\n|-----------|--------|------------|----------------|\n| Petah Tikva 47 | 12 | 150000 | 0.800000000000 |\n| Holon 23 | 11 | 150000 | 0.733333333333 |\n| Rishon LeZion 60 | 11 | 150000 | 0.733333333333 |\n| Jerusalem 100 | 11 | 150000 | 0.733333333333 |\n| Tel Aviv 85 | 10 | 150000 | 0.666666666667 |" +2026-10-17 19:22:31,26.75,query_892394d3,"מצא את הערים שבהן נרשמו לפחות 5 התרעות במהלך השבועיים הראשונים של יולי 2026, אך לא נרשמה בהן אף נחיתת חירום באותה תקופה. הצג את מספר ההתרעות בכל עיר, ומיין מהמספר הגבוה לנמוך.","WITH alerts_cte AS (\n SELECT city_code, COUNT(*) AS alert_cnt\n FROM ""postgres"".""public"".""flight_alerts_table""\n WHERE alert_date_time >= TIMESTAMP '2026-07-01 00:00:00 UTC'\n AND alert_date_time < TIMESTAMP '2026-07-15 00:00:00 UTC'\n GROUP BY city_code\n HAVING COUNT(*) >= 5\n)\nSELECT ci.city_name, a.alert_cnt\nFROM alerts_cte a\nJOIN ""postgres"".""public"".""city_info_table"" ci\n ON ci.city_code = a.city_code\nWHERE NOT EXISTS (\n SELECT 1\n FROM ""postgres"".""public"".""flights_landing_table"" fl\n WHERE fl.emergency_landing = 'yes'\n AND fl.datetime >= TIMESTAMP '2026-07-01 00:00:00 UTC'\n AND fl.datetime < TIMESTAMP '2026-07-15 00:00:00 UTC'\n AND fl.city_name = ci.city_name\n)\nORDER BY a.alert_cnt DESC","הקוד שלמטה מוצא את כל הערים שבהן נרשמו **לפחות 5 התרעות** בתקופה 1‑14 יולי 2026, ומוודא שאין אף **נחיתת חירום** ( `emergency_landing = 'yes' ) באותה תקופה. התוצאה מציגה את שם העיר ומספר ההתרעות, ממוינת מהמספר הגבוה לנמוך.\n\n| city_name | alert_cnt |\n|-----------|-----------|\n| Kfar Saba 28 | 8 |\n| Kfar Saba 98 | 7 |\n| Netanya 133 | 7 |\n| Rishon LeZion 116 | 7 |\n| Rishon LeZion 32 | 7 |\n| Rishon LeZion 88 | 7 |\n| Bat Yam 138 | 7 |\n| Haifa 45 | 7 |\n| Haifa 59 | 6 |\n| Bnei Brak 66 | 6 |\n| Jerusalem 142 | 6 |\n| Kfar Saba 56 | 6 |\n| Holon 51 | 6 |\n| Bat Yam 12 | 6 |\n| Bat Yam 40 | 6 |\n| Herzliya 41 | 6 |\n| Rishon LeZion 130 | 6 |\n| Rishon LeZion 60 | 6 |\n| Holon 149 | 6 |\n| Beer Sheva 50 | 6 |\n| Haifa 115 | 5 |\n| Bnei Brak 136 | 5 |\n| Bat Yam 82 | 5 |\n| Holon 107 | 5 |\n| Rehovot 123 | 5 |\n| Rehovot 81 | 5 |\n| Ashdod 118 | 5 |\n| Jerusalem 2 | 5 |\n| Netanya 63 | 5 |\n| Tel Aviv 29 | 5 |\n| Netanya 105 | 5 |\n| Ashdod 34 | 5 |\n| Ashdod 132 | 5 |\n| Petah Tikva 33 | 5 |" +2026-10-17 19:27:10,32.64,query_7e21fbbb,"עבור טיסות שהמריאו במהלך יוני 2026, מצא את אזורי ההנחיה שבהם שיעור הטיסות ארוכות הטווח גבוה מהממוצע של כלל הטיסות בתקופה. הצג את מספר הטיסות בכל אזור, מספר הטיסות ארוכות הטווח, השיעור שלהן והפער בנקודות אחוז מהממוצע הכללי. מיין לפי הפער מהגבוה לנמוך.","WITH june_flights AS (\n SELECT *\n FROM ""postgres"".""public"".""flights_table""\n WHERE flight_date >= TIMESTAMP '2026-06-01 00:00:00 UTC'\n AND flight_date < TIMESTAMP '2026-07-01 00:00:00 UTC'\n),\noverall AS (\n SELECT COUNT(*) AS total_flights,\n SUM(CASE WHEN range_classification = 'Long-Haul' THEN 1 ELSE 0 END) AS long_haul_flights\n FROM june_flights\n),\nzone_stats AS (\n SELECT instructions_zone,\n COUNT(*) AS total_flights,\n SUM(CASE WHEN range_classification = 'Long-Haul' THEN 1 ELSE 0 END) AS long_haul_flights\n FROM june_flights\n GROUP BY instructions_zone\n)\nSELECT\n z.instructions_zone,\n z.total_flights,\n z.long_haul_flights,\n (z.long_haul_flights * 100.0 / NULLIF(z.total_flights,0)) AS long_haul_pct,\n ((z.long_haul_flights * 100.0 / NULLIF(z.total_flights,0)) -\n (o.long_haul_flights * 100.0 / NULLIF(o.total_flights,0))) AS diff_pct_points\nFROM zone_stats z\nCROSS JOIN overall o\nWHERE z.long_haul_flights * 1.0 / NULLIF(z.total_flights,0) >\n o.long_haul_flights * 1.0 / NULLIF(o.total_flights,0)\nORDER BY diff_pct_points DESC;","**הסבר** \nהשאילתה בוחרת את כל הטיסות שהמריאו בחודש יוני 2026 (`flight_date`), מחשבת לכל אזור הנחיה (`instructions_zone`) את מספר הטיסות הכולל, את מספר הטיסות ארוכות‑טווח (`range_classification = 'Long-Haul'`), את אחוז הטיסות ארוכות‑טווח באותו אזור, ומשווה אותו לממוצע האחוז של כל הטיסות בחודש. ההפרש (נקודות אחוז) מוצג בעמודה `diff_pct_points` והנתונים ממוינים מההפרש הגבוה לנמוך.\n\n| instructions_zone | total_flights | long_haul_flights | long_haul_pct | diff_pct_points |\n|-------------------|--------------|-------------------|---------------|-----------------|\n| Zone C-3 | 42 | 19 | 45.238095238095238 | 15.097250167672703 |\n| Zone P-16 | 30 | 12 | 40.000000000000000 | 9.859154929577465 |\n| Zone F-6 | 26 | 10 | 38.461538461538462 | 8.320693391115927 |\n| Zone K-11 | 43 | 16 | 37.209302325581395 | 7.068457255158860 |\n| Zone T-20 | 32 | 11 | 34.375000000000000 | 4.234154929577465 |\n| Zone H-8 | 33 | 11 | 33.333333333333333 | 3.192488262910798 |\n| Zone L-12 | 28 | 9 | 32.142857142857143 | 2.002012072434608 |\n| Zone Q-17 | 41 | 13 | 31.707317073170732 | 1.566472002748197 |\n| Zone A-1 | 46 | 14 | 30.434782608695652 | 0.293937538273117 |\n| Zone D-4 | 33 | 10 | 30.303030303030303 | 0.162185232607768 |" +2026-10-17 19:28:37,27.93,query_8fba4047,"זהה את עשר הרשויות שבהן היחס בין מספר האנשים השוהים במתקני האירוח לבין מספר העובדים הוא הגבוה ביותר, בתנאי שיש בהן לפחות 500 אנשים. הצג גם את מספר החדרים, את מספר האנשים לכל חדר ואת מועד העדכון של נתוני האירוח. אל תכלול רשויות שבהן מספר העובדים הוא אפס.","SELECT\n muni AS authority,\n total_people,\n total_workers,\n total_rooms,\n CAST(total_people AS double) / total_workers AS people_worker_ratio,\n CAST(total_people AS double) / NULLIF(total_rooms, 0) AS people_per_room,\n update_date_time\nFROM ""postgres"".""public"".""muni_hotels_table""\nWHERE total_people >= 500\n AND total_workers > 0\nORDER BY people_worker_ratio DESC\nLIMIT 10;","**הסבר:** \nהטבלה מציגה את עשר הרשויות (municipalities) שבהן היחס `מספר האנשים השוהים / מספר העובדים` גבוה ביותר, בתנאי של ≥ 500 אדם ושאין עובדים 0. בנוסף מוצגים מספר החדרים, מספר האנשים לכל חדר, ותאריך עדכון הנתונים.\n\n| רשות | מספר אנשים | מספר עובדים | מספר חדרים | יחס אנשים / עובדים | אנשים לכל חדר | מועד עדכון |\n|------|------------|--------------|------------|-------------------|----------------|-------------|\n| MuniArea 98 | 1247 | 8 | 650 | 155.88 | 1.92 | 2026‑07‑15 01:57:39.585702+00:00 |\n| MuniArea 22 | 889 | 7 | 897 | 127.00 | 0.99 | 2026‑07‑14 16:24:00.527438+00:00 |\n| MuniArea 57 | 997 | 14 | 204 | 71.21 | 4.89 | 2026‑07‑16 08:45:20.074282+00:00 |\n| MuniArea 3 | 953 | 15 | 293 | 63.53 | 3.25 | 2026‑07‑15 01:37:16.416432+00:00 |\n| MuniArea 16 | 1040 | 18 | 638 | 57.78 | 1.63 | 2026‑07‑14 21:56:07.104066+00:00 |\n| MuniArea 55 | 1018 | 22 | 813 | 46.27 | 1.25 | 2026‑07‑14 17:47:16.985444+00:00 |\n| MuniArea 20 | 1123 | 29 | 647 | 38.72 | 1.74 | 2026‑07‑15 02:11:14.359805+00:00 |\n| MuniArea 77 | 801 | 21 | 575 | 38.14 | 1.39 | 2026‑07‑16 11:25:43.930276+00:00 |\n| MuniArea 26 | 1172 | 31 | 388 | 37.81 | 3.02 | 2026‑07‑16 00:58:03.708977+00:00 |\n| MuniArea 14 | 1241 | 36 | 319 | 34.47 | 3.89 | 2026‑07‑15 02:45:17.671082+00:00 |" +2026-10-17 19:34:46,36.56,query_774b9b3e,"עבור כל אזור הנחיה, הצג את המדיניות העדכנית ביותר הידועה, את תאריך העדכון שלה ואת מספר הטיסות ששויכו לאזור במהלך יולי 2026. הצג גם אזורים שאין להם טיסות בתקופה, וודא שאזור שמופיעות עבורו כמה גרסאות של מדיניות נספר פעם אחת בלבד.","WITH latest_policy AS (\n SELECT\n instruction_zone,\n flight_policy,\n instruction_policy_description,\n last_update_date\n FROM (\n SELECT\n *,\n ROW_NUMBER() OVER (PARTITION BY instruction_zone ORDER BY last_update_date DESC) AS rn\n FROM ""postgres"".""public"".""flights_instruction_policy_table""\n ) t\n WHERE rn = 1\n),\njuly_flights AS (\n SELECT\n instructions_zone AS instruction_zone,\n COUNT(*) AS flight_count\n FROM ""postgres"".""public"".""flights_table""\n WHERE flight_date >= TIMESTAMP '2026-07-01 00:00:00 UTC'\n AND flight_date < TIMESTAMP '2026-08-01 00:00:00 UTC'\n GROUP BY instructions_zone\n)\nSELECT\n lp.instruction_zone,\n lp.flight_policy,\n lp.instruction_policy_description,\n lp.last_update_date,\n COALESCE(jf.flight_count, 0) AS flight_count_july_2026\nFROM latest_policy lp\nLEFT JOIN july_flights jf\n ON lp.instruction_zone = jf.instruction_zone\nORDER BY lp.instruction_zone;","**הסבר** \nהשאילתה מציגה עבור כל **אזור הנחיה** (instruction zone) את הפרטים הבאים:\n\n1. **המדיניות העדכנית ביותר** – נבחרת על‑ידי דירוג גרסאות המדיניות לפי `last_update_date` ובחירת השורה הראשונה (`ROW_NUMBER() = 1`). \n2. **תאריך העדכון** של אותה גרסה. \n3. **מספר הטיסות** ששויכו לאותו אזור במהלך יולי 2026 (`flight_date` בין 1‑7‑2026 ל‑31‑7‑2026). \n4. האזורים שאין להם טיסות בחודש יולי מוצגים גם הם, כאשר ערך `flight_count_july_2026` הוא `0` (הצטרפות LEFT JOIN).\n\nהצגת האזורים מתבצעת פעם אחת בלבד, גם אם קיימות מספר גרסאות של מדיניות, בזכות השימוש ב‑`ROW_NUMBER()`.\n\n| instruction_zone | flight_policy | instruction_policy_description | last_update_date | flight_count_july_2026 |\n|------------------|--------------|--------------------------------|------------------|------------------------|\n| Zone A-1 | Fully Closed Airspace | Active directives for airspace safety inside Zone A-1. Maintain communications channels at all times. | 2026‑07‑15 16:25:05.385281+00:00 | 21 |\n| Zone B-2 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone B-2. Maintain communications channels at all times. | 2026‑07‑13 19:40:37.626829+00:00 | 17 |\n| Zone C-3 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone C-3. Maintain communications channels at all times. | 2026‑07‑11 17:37:16.294348+00:00 | 23 |\n| Zone D-4 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone D-4. Maintain communications channels at all times. | 2026‑07‑16 07:51:19.669249+00:00 | 19 |\n| Zone E-5 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone E-5. Maintain communications channels at all times. | 2026‑07‑13 18:25:45.734631+00:00 | 26 |\n| Zone F-6 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone F-6. Maintain communications channels at all times. | 2026‑07‑14 10:24:05.773656+00:00 | 18 |\n| Zone G-7 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone G-7. Maintain communications channels at all times. | 2026‑07‑13 20:20:16.513570+00:00 | 14 |\n| Zone H-8 | Fully Closed Airspace | Active directives for airspace safety inside Zone H-8. Maintain communications channels at all times. | 2026‑07‑12 03:09:56.269487+00:00 | 21 |\n| Zone I-9 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone I-9. Maintain communications channels at all times. | 2026‑07‑16 00:02:58.873861+00:00 | 21 |\n| Zone J-10 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone J-10. Maintain communications channels at all times. | 2026‑07‑16 07:58:17.128477+00:00 | 23 |\n| Zone K-11 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone K-11. Maintain communications channels at all times. | 2026‑07‑15 13:04:56.088782+00:00 | 22 |\n| Zone L-12 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone L-12. Maintain communications channels at all times. | 2026‑07‑16 05:01:29.344771+00:00 | 26 |\n| Zone M-13 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone M-13. Maintain communications channels at all times. | 2026‑07‑15 20:38:54.299768+00:00 | 15 |\n| Zone N-14 | Fully Closed Airspace | Active directives for airspace safety inside Zone N-14. Maintain communications channels at all times. | 2026‑07‑12 09:24:30.634056+00:00 | 19 |\n| Zone O-15 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone O-15. Maintain communications channels at all times. | 2026‑07‑16 12:24:30.350284+00:00 | 28 |\n| Zone P-16 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone P-16. Maintain communications channels at all times. | 2026‑07‑12 20:28:40.815513+00:00 | 21 |\n| Zone Q-17 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone Q-17. Maintain communications channels at all times. | 2026‑07‑12 14:44:51.899935+00:00 | 12 |\n| Zone R-18 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone R-18. Maintain communications channels at all times. | 2026‑07‑13 03:43:13.644030+00:00 | 22 |\n| Zone S-19 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone S-19. Maintain communications channels at all times. | 2026‑07‑16 05:39:00.913864+00:00 | 14 |\n| Zone T-20 | Fully Closed Airspace | Active directives for airspace safety inside Zone T-20. Maintain communications channels at all times. | 2026‑07‑16 10:34:22.989115+00:00 | 18 |\n\n*הטבלה כוללת גם אזורים שאין להם טיסות בחודש יולי 2026 – במצב זה ערך `flight_count_july_2026` יהיה `0`.*" +2026-10-19 10:16:25,26.29,query_afa26304,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(*) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","הבקשה: כמה טיסות המריאו מצרפת ונחתו בתל אביב.\n\n**הסבר** \nהטבלה `""postgres"".""public"".""flights_table""` מכילה רשומה אחת לכל טיסה. \nהעמודה `launch_country` מציינת את מדינת ההמראה, והעמודה `city_name` (large_categorical) מכילה את שם העיר שבה הטיסה נחתה. \nהשתמשנו בתנאי `launch_country = 'France'` וב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל הווריאנטים של שם העיר (לדוגמה ""Tel Aviv 1"", ""Tel Aviv 141"" וכו').\n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 |" diff --git a/agent/run_deep_agent.py b/agent/run_deep_agent.py index 241a024..d253e75 100644 --- a/agent/run_deep_agent.py +++ b/agent/run_deep_agent.py @@ -2,6 +2,7 @@ import os import sys import argparse +import uuid # Add the src directory to sys.path so we can import modules sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src'))) @@ -20,30 +21,111 @@ YELLOW = "\033[93m" RED = "\033[91m" MAGENTA = "\033[95m" +BLUE = "\033[94m" +WHITE = "\033[97m" BOLD = "\033[1m" +DIM = "\033[2m" RESET = "\033[0m" import time import json from datetime import datetime -async def run_query(agent, question: str): + +def print_formatted_message(msg): + msg_type = getattr(msg, "type", "") + + if msg_type == "human": + print(f"\n{YELLOW}{BOLD}{'═'*30} 👤 USER MESSAGE {'═'*30}{RESET}\n") + content = getattr(msg, "content", "") + print(f"{YELLOW}{content}{RESET}\n") + + elif msg_type == "ai": + print(f"\n{MAGENTA}{BOLD}{'═'*30} 🤖 AI MESSAGE {'═'*30}{RESET}\n") + + # 1. Print thoughts / text content + raw_content = getattr(msg, "content", "") + if raw_content: + if isinstance(raw_content, list): + for block in raw_content: + if isinstance(block, dict): + if block.get("type") == "text": + print(f"{WHITE}{block.get('text', '')}{RESET}\n") + elif block.get("type") == "thinking": + print(f"{DIM}💭 [Thinking]\n{block.get('thinking', '')}{RESET}\n") + else: + print(f"{WHITE}{block}{RESET}\n") + elif isinstance(raw_content, str) and raw_content.strip(): + print(f"{WHITE}{raw_content}{RESET}\n") + + # 2. Print tool calls + tool_calls = getattr(msg, "tool_calls", None) or [] + for tc in tool_calls: + tc_name = tc.get("name", "unknown_tool") + tc_args = tc.get("args", {}) + print(f"{CYAN}{BOLD}⚡ Tool Call: {RESET}{CYAN}{BOLD}{tc_name}{RESET}") + if tc_args: + try: + formatted_args = json.dumps(tc_args, indent=2, ensure_ascii=False) + indented_args = "\n".join(" " + line for line in formatted_args.splitlines()) + print(f"{WHITE}{indented_args}{RESET}\n") + except Exception: + print(f"{WHITE} Args: {tc_args}{RESET}\n") + + elif msg_type == "tool": + tool_name = getattr(msg, "name", "tool") or "tool" + content = getattr(msg, "content", "") + is_error = getattr(msg, "status", "") == "error" or (isinstance(content, str) and content.strip().startswith("Error")) + header_color = RED if is_error else BLUE + icon = "❌" if is_error else "🛠️ " + + print(f"\n{header_color}{BOLD}{'═'*30} {icon} TOOL: {tool_name} {'═'*30}{RESET}\n") + + # Truncate ONLY for get_database_catalog + if tool_name == "get_database_catalog" and isinstance(content, str): + lines = content.splitlines() + if len(lines) > 30 or len(content) > 1500: + preview = "\n".join(lines[:30]) if len(lines) > 30 else content[:1500] + print(f"{WHITE}{preview}{RESET}") + print(f"\n{YELLOW}{BOLD}✂️ [Truncated full schema catalog for display: showing first 30 of {len(lines)} lines ({len(content):,} chars total)] ...{RESET}\n") + else: + print(f"{WHITE}{content}{RESET}\n") + else: + # All other tools: print in full + if isinstance(content, str): + print(f"{WHITE}{content}{RESET}\n") + else: + print(f"{WHITE}{str(content)}{RESET}\n") + + else: + # Fallback for system or unexpected message types + print(f"\n{DIM}{'═'*30} {msg_type.upper() if msg_type else 'MESSAGE'} {'═'*30}{RESET}\n") + content = getattr(msg, "content", "") + print(f"{WHITE}{content}{RESET}\n") + + +async def run_query(agent, question: str, thread_id: str): print(f"\n{CYAN}{BOLD}{'='*80}{RESET}") print(f"{CYAN}{BOLD} Running Query: \"{question}\"{RESET}") + print(f"{DIM} Thread: {thread_id}{RESET}") print(f"{CYAN}{BOLD}{'='*80}{RESET}\n") - config = {"configurable": {"thread_id": "cli_deep_agent"}} + config = {"configurable": {"thread_id": thread_id}} start_time = time.time() final_state = None + printed_count = 0 async for state in agent.astream( {"messages": [("user", question)]}, config, stream_mode="values" ): - latest_message = state["messages"][-1] - latest_message.pretty_print() + messages = state.get("messages", []) + while printed_count < len(messages): + msg = messages[printed_count] + print_formatted_message(msg) + printed_count += 1 final_state = state execution_time = time.time() - start_time @@ -85,11 +167,12 @@ async def run_query(agent, question: str): with open(log_file, "a", newline="", encoding="utf-8") as f: writer = csv.writer(f) if not file_exists: - writer.writerow(["Timestamp", "Execution Time (s)", "Question", "Final SQL", "Final Answer"]) + writer.writerow(["Timestamp", "Execution Time (s)", "Thread ID", "Question", "Final SQL", "Final Answer"]) writer.writerow([ datetime.now().isoformat()[:19].replace("T", " "), round(execution_time, 2), + thread_id, q_csv, sql_csv, ans_csv @@ -97,13 +180,51 @@ async def run_query(agent, question: str): sql_status = "Yes" if final_sql else "None" print(f"\n{GREEN}{BOLD}[Extraction Log Saved] Execution time: {round(execution_time, 2)}s, Final SQL captured: {sql_status}{RESET}") + if final_sql: + print(f"\n{CYAN}{BOLD}{'='*30} FINAL GENERATED SQL {'='*30}{RESET}") + print(f"{GREEN}{final_sql}{RESET}") + print(f"{CYAN}{BOLD}{'='*81}{RESET}\n") + async def main(): - parser = argparse.ArgumentParser(description="Interactive CLI tool to test the Deep Agent.") - parser.add_argument("query", nargs="?", default="", help="The query to run.") + parser = argparse.ArgumentParser(description="Interactive CLI tool to test the Deep Agent on Trino data.") + parser.add_argument("query", nargs="?", default="", help="The natural language question to run (Hebrew or English).") parser.add_argument("--interactive", "-i", action="store_true", help="Run in interactive loop mode.") + parser.add_argument("--connection-id", "-c", type=int, default=None, help="Jeen metadata connection ID (defaults to 89: trino_ingestion / flights).") + parser.add_argument( + "--session-memory", "-m", + action="store_true", + help=( + "Share a single thread across all queries in this session. " + "The agent remembers prior questions and their outcomes within the session. " + "Default: each query gets a fresh thread (isolated, no cross-question memory)." + ), + ) args = parser.parse_args() + from agent.utils.jeen_metadata_client import get_jeen_metadata_client + client = get_jeen_metadata_client() + if args.connection_id: + os.environ["JEEN_METADATA_CONNECTION_ID"] = str(args.connection_id) + client._connection_id = args.connection_id + + # Thread ID strategy: + # - With --session-memory: all queries share one thread → agent sees prior Q&A in context + # - Without (default): each query gets a unique thread → clean slate, no context bleed + session_thread_id = f"cli_session_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + + print(f"\n{MAGENTA}{BOLD}================================================================{RESET}") + print(f"{MAGENTA}{BOLD} DEEP AGENT CLI — TEXT2SQL RUNNER {RESET}") + print(f"{MAGENTA}{BOLD}================================================================{RESET}") + print(f" {CYAN}Target Connection:{RESET} ID {client._connection_id} ({'trino_ingestion / flights' if client._connection_id == 89 else 'custom connection'})") + print(f" {CYAN}MCP Endpoint:{RESET} {client._mcp_url}") + if args.session_memory: + print(f" {CYAN}Memory mode:{RESET} Session (queries share context — agent learns within session)") + print(f" {CYAN}Session thread:{RESET} {session_thread_id}") + else: + print(f" {CYAN}Memory mode:{RESET} Isolated (each query is independent — no context bleed)") + print(f"{MAGENTA}{BOLD}================================================================{RESET}\n") + print(f"{MAGENTA}{BOLD}Initializing Deep Agent...{RESET}") agent = create_deep_agent() @@ -121,13 +242,19 @@ async def main(): if question.strip().lower() in ('quit', 'exit', 'q'): print(f"{MAGENTA}{BOLD}Goodbye!{RESET}") break - - await run_query(agent, question) + + if args.session_memory: + thread_id = session_thread_id + else: + thread_id = f"query_{uuid.uuid4().hex[:8]}" + + await run_query(agent, question, thread_id) elif args.query: - await run_query(agent, args.query) + thread_id = session_thread_id if args.session_memory else f"query_{uuid.uuid4().hex[:8]}" + await run_query(agent, args.query, thread_id) else: - print(f"{RED}{BOLD}Error: You must provide a query or run with --interactive{RESET}") + print(f"{RED}{BOLD}Error: You must provide a query or run with --interactive{RESET}\n") parser.print_help() if __name__ == "__main__": diff --git a/agent/skills/semantic-validation/SKILL.md b/agent/skills/semantic-validation/SKILL.md new file mode 100644 index 0000000..6e84316 --- /dev/null +++ b/agent/skills/semantic-validation/SKILL.md @@ -0,0 +1,143 @@ +--- +name: semantic-validation +description: Semantic correctness checks for Text-to-SQL — use when a query has executed successfully but you need to verify it actually answers the user's intent, especially for aggregations, joins, and complex conditions. +--- +# Semantic Validation Reference + +## When to apply semantic validation + +Apply at least a mental checklist — and targeted diagnostic queries — when: +- The query uses **JOINs** (risk: fan-out multiplication) +- The query uses **aggregations**: `COUNT`, `SUM`, `AVG`, `MIN`, `MAX` +- The question asks for **"per X"** metrics (risk: wrong grouping unit) +- The question uses **"most"**, **"top N"**, **"highest"**, **"total"** +- The filter involves **dates, ranges, or boundaries** +- The result is **0 rows** or an **unexpectedly round/large number** +- The question involves **"customers/entities with NO related records"** (anti-join risk) + +--- + +## The Output Grain Test + +Before writing SQL, answer: **What does one output row represent?** + +Match this to the user's question: +- "כמה X היו בY?" → one row = COUNT of X (scalar) +- "מה X עשו בY?" → one row = (metric, X) pair +- "הכי הרבה X ב-Y" → one row = (X, metric) pair +- "X לנפש" → one row = (entity, per-capita metric) + +If the grain is wrong, every aggregation in the query is suspect. + +--- + +## Join Fan-Out Check (Critical for aggregations) + +A JOIN on a 1-to-many relationship **multiplies rows**. `COUNT(*)` after such a join counts inflated rows, not entities. + +**The diagnostic**: After joining, verify the row count on each side independently. + +```sql +-- Step 1: count entities in the left table +SELECT COUNT(*) FROM "catalog"."schema"."left_table" +WHERE ; + +-- Step 2: count rows after the JOIN +SELECT COUNT(*) FROM "catalog"."schema"."left_table" l +JOIN "catalog"."schema"."right_table" r ON l.id = r.left_id +WHERE ; +``` + +If Step 2 > Step 1, rows are being duplicated. Fix options: +- Use `COUNT(DISTINCT l.id)` instead of `COUNT(*)` +- Use a subquery/CTE to aggregate first, then join +- Join on a truly unique key + +**Example pattern:** +```sql +-- WRONG: counts alert rows, not flights +SELECT COUNT(*) FROM flights f JOIN alerts a ON f.id = a.flight_id + +-- CORRECT: count distinct flights that have alerts +SELECT COUNT(DISTINCT f.id) FROM flights f JOIN alerts a ON f.id = a.flight_id +``` + +--- + +## Aggregation Semantics + +| User says | Probably means | Watch out for | +|-----------|----------------|----------------| +| "כמה" (how many) | COUNT of entities | COUNT(*) after 1-to-many join | +| "ממוצע" (average) | AVG() | Is it avg-of-averages vs avg-of-rows? | +| "סה"כ" (total) | SUM() | NULL rows excluded from SUM | +| "הגבוה ביותר" (highest) | MAX() or ORDER BY ... LIMIT 1 | Ties — should you return all? | +| "לנפש" (per capita/person) | division by count | Division by zero on NULL | +| "לפי X" (by X) | GROUP BY X | Did you group at the right grain? | + +--- + +## Filter Boundary Checks + +Date/time ranges: +- **"בחודש ינואר"** → `BETWEEN '2024-01-01' AND '2024-01-31'` or `date_trunc('month', col) = DATE '2024-01-01'` +- **"ב-2023"** → `YEAR(col) = 2023` or `col >= DATE '2023-01-01' AND col < DATE '2024-01-01'` +- Check if the column is `DATE` or `TIMESTAMP` — compare types matter + +Categorical filters: +- After `search_column_values`, use the **exact string returned** — never modify it +- If `LIKE` is necessary (large_categorical prefix pattern), use `LIKE 'Tel Aviv%'` not `LIKE '%Tel Aviv%'` unless you need interior match + +--- + +## Anti-join Patterns (entities with NO related records) + +```sql +-- CORRECT: entities with no matching records +SELECT c.id FROM customers c +WHERE NOT EXISTS ( + SELECT 1 FROM orders o WHERE o.customer_id = c.id +) + +-- ALSO CORRECT (but watch for NULL-join behavior) +SELECT c.id FROM customers c +LEFT JOIN orders o ON o.customer_id = c.id +WHERE o.id IS NULL +``` + +Do NOT use `c.id NOT IN (SELECT customer_id FROM orders)` if `customer_id` can be NULL — this returns 0 rows when any NULL exists. + +--- + +## The Intent-Preservation Quick-Check + +Before finalizing the response, mentally translate your SQL back to plain language and compare filter-by-filter to the user's question: + +1. Does each WHERE clause correspond to a condition the user mentioned? +2. Did you include a condition that the user did NOT mention? +3. Is the GROUP BY at the right entity level? +4. Does the SELECT list include what the user asked for (and nothing unasked)? +5. Are ties handled (RANK vs ROW_NUMBER vs LIMIT)? + +If any answer is "no" or "unsure" — revise the SQL before executing. + +--- + +## When results are suspicious — diagnostic queries + +**0 rows returned:** +1. Strip WHERE clauses one at a time to find which one eliminates all rows +2. `search_column_values` on any string filter you wrote +3. Sample the join keys: `get_sample_rows` on both sides — do the key formats match? + +**Count too high (round number like 10000 or identical to table size):** +1. Run `SELECT COUNT(*) FROM table` — if equal, your WHERE clause may be doing nothing +2. Check for Cartesian product: does the JOIN have a proper ON condition? + +**Count too low (0 or 1 when many are expected):** +1. Check for strict INNER JOIN when LEFT JOIN is needed +2. Check for NULL key: `WHERE key IS NOT NULL` accidentally excluded nulls? + +**Average looks wrong:** +1. Compare with a manual spot-check: `SELECT col FROM table WHERE condition LIMIT 10` +2. Verify the denominator: are you dividing by count of rows or count of entities? diff --git a/agent/skills/spatial-analyst/SKILL.md b/agent/skills/spatial-analyst/SKILL.md index c0ba89b..ec0c878 100644 --- a/agent/skills/spatial-analyst/SKILL.md +++ b/agent/skills/spatial-analyst/SKILL.md @@ -1,20 +1,141 @@ --- name: spatial-analyst -description: Rules for handling geospatial queries in Trino, including WKT strings, spherical geography distances, and geometry construction. +description: Geospatial query patterns for Trino, including Hebrew geographical extraction, per-location decision trees, polygon & point handling, proximity & directional filtering, and spatial join acceleration. --- -# Spatial SQL Analyst Guidelines +# Spatial & Geographical SQL Reference for Trino -When your query involves locations, points, polygons, or geographic distances, strictly adhere to these Trino Geo-Spatial rules: +## 1. Hebrew Location Extraction & Disambiguation Rules -## Geometry Construction -* **WKT to Geometry**: When constructing geometries from Well-Known Text (WKT), ALWAYS use `ST_GeometryFromText(wkt_string)`. -* **NEVER** use `ST_GeomFromText()`. It does not exist in Trino and will fail. +When analyzing user requests in Hebrew, apply these linguistic rules before resolving or searching: -## Distances and Projections -* **Spherical Geography**: Trino's `ST_Distance` calculates distance in the units of the spatial reference system. If your coordinates are in WGS84 (longitude/latitude in degrees), `ST_Distance` will return degrees, which is completely useless for physical distance measurements. -* **Meters/Kilometers**: To calculate physical distance on the Earth's surface (in meters), you MUST cast the geometries to spherical geography using `toSphericalGeography()`. - * **Example**: `ST_Distance(toSphericalGeography(geom1), toSphericalGeography(geom2))` - * This returns the distance in **meters**. Divide by 1000 if you need kilometers. +### A. Preposition Stripping vs. Structural Words +- **Strip grammatical prefixes**: `ב-`, `ל-`, `מ-`, `כ-`, `ו-` (e.g. `בבינת ג'בייל` → `בינת ג'בייל`, `מהר דב` → `הר דב`). +- **NEVER strip structural words that belong to the proper place name**: + - `אל-` (e.g. `אל-ח'יאם`) + - `כפר` (e.g. `כפר קאסם`, `כפר כנא`) + - `נחל` (e.g. `נחל קישון`, `נחל עיראק`) + - `הר` (e.g. `הר דב`, `הר חרמון`) + - `מחנה` (e.g. `מחנה נחשונים`, `מחנה בלאטה`) + - `ואדי` (e.g. `ואדי עארה`) -## Resolution -* **Use the Resolver**: If the user provides a Hebrew location name (e.g., "תל אביב" or "כביש 1"), NEVER try to guess its coordinates or WKT. Always use the `resolve_location_to_wkt` tool first, and then inject the exact returned WKT into your `ST_GeometryFromText()` call. +### B. Expand Acronyms & Abbreviations +Expand geographical abbreviations before querying or resolving: +- `ת״א` → `תל אביב` +- `י-ם` → `ירושלים` +- `איו״ש` → `יהודה ושומרון` +- `ארה״ב` → `ארצות הברית` + +### C. Disambiguate Non-Geographical Entities (False Positives) +- **Sports Teams**: `מכבי חיפה`, `הפועל ירושלים` → organization names, NOT location filters (unless the query asks about games taking place *in* the city). +- **Restaurants / Venues**: `מסעדת אוסלו` → venue name, ignore for city extraction. +- **Personal Names**: `גולן ושרון קבעו פגישה` → people's names, not regions. + +### D. Comprehensive Geographical Scope +Locations are not just major cities. Recognize and extract: +- Populated cities, towns, villages (`כפרים`), kibbutzim, moshavim. +- Outposts, refugee camps (`מחנות פליטים`), military bases (`מחנות צבאיים`). +- Mountains, peaks, hills, valleys, rivers, wadis. +- Aggregate geopolitical regions (`עוטף עזה`, `גוש דן`, `דרום לבנון`, `בקעת הירדן`). + +--- + +## 2. The Nuanced Per-Location Decision Strategy + +Evaluate **EACH location mentioned in the query independently**. A single query may involve multiple locations that should be handled differently. + +``` +For EACH location mentioned: + +1. Proximity or Directional Query? ("סביב", "מצפון ל-", "ברדיוס") + ↳ Coordinates are inherently required (great_circle_distance or lat/lon condition). + +2. Regional Area / Agglomeration? ("גוש דן", "עוטף עזה", "הגליל העליון") + ↳ Text columns rarely contain these aggregate areas. + ↳ Call `resolve_location_to_wkt` and filter coordinate columns. + +3. Specific City or Settlement? ("חיפה", "חאן יונס", "כפר קאסם") + ↳ Inspect candidate table: + • If an administrative column exists (`city_name`, `settlement`) AND contains the value: + Prefer direct text equality (fast, indexed, avoids boundary edge clipping). + • If the table ONLY has coordinates (`lat`/`lon`, `geom`): + Call `resolve_location_to_wkt` and filter spatially. + • If categorical search returns 0 matches: + Fall back to `resolve_location_to_wkt`. + +4. The "No Blind OR" Rule: + • Do NOT write `city = 'Haifa' OR ST_Contains(...)` blindly as a lazy habit. + • ONLY combine with OR if the data is genuinely hybrid (e.g. telemetry tables where + some rows have manual city tags while others only have raw GPS sensor pings). +``` + +--- + +## 3. Handling Points, Polygons, and Lines + +`resolve_location_to_wkt(location_name)` resolves Hebrew names via Nominatim and returns the geometry. + +### A. Polygons & Areas (Cities, Regions, Envelopes) +When `resolve_location_to_wkt` returns `'POLYGON((...))'`: +```sql +WHERE ST_Contains(ST_GeometryFromText(polygon_wkt), ST_Point(lon, lat)) +``` +- Pre-filter with a cheap numeric bounding box first on large tables: +```sql +WHERE lat BETWEEN 32.0 AND 32.2 + AND lon BETWEEN 34.7 AND 34.9 + AND ST_Contains(ST_GeometryFromText(polygon_wkt), ST_Point(lon, lat)) +``` + +### B. Points (Mountain Peaks, Military Bases, Intersections, Landmarks) +When `resolve_location_to_wkt` returns a `POINT(lon lat)` (e.g. for `הר דב` or `מחנה נחשונים`): +- A point has zero area. When the user asks about events "in", "at", or "near" this landmark, **apply a sensible default proximity radius (~500 meters or 1 km)**: +```sql +-- Fast & clean: great_circle_distance (target_lat, target_lon, returns km) +WHERE great_circle_distance(lat, lon, target_lat, target_lon) <= 0.5 -- 500 meters + +-- Or spherical geography distance (meters): +WHERE ST_Distance( + to_spherical_geography(ST_Point(lon, lat)), + to_spherical_geography(ST_Point(target_lon, target_lat)) + ) <= 500 +``` + +--- + +## 4. Proximity & Directional Intent Patterns + +When the user asks for relative spatial relations, translate the intent into precise coordinate math: + +| Phrasing | Semantic Meaning | Recommended SQL Pattern | +|---|---|---| +| **"ברדיוס X ק"מ מ..."** | Explicit radius distance | `great_circle_distance(lat, lon, target_lat, target_lon) <= X` | +| **"סביב..." / "באזור..." (for a Point/City)** | Implicit proximity | For a Point: `great_circle_distance(...) <= 1.0` (1 km)
For a Polygon: `ST_Contains(...)` or buffer $\le 2\text{ km}$ | +| **"מצפון ל..."** (North of) | Directional filter | `lat > target_lat` (with reasonable lon bounding box) | +| **"מדרום ל..."** (South of) | Directional filter | `lat < target_lat` (with reasonable lon bounding box) | +| **"ממזרח ל..." / "ממערב ל..."** | Directional filter | `lon > target_lon` / `lon < target_lon` | + +--- + +## 5. Critical Coordinate Order & Syntax Rules + +- **`ST_Point(lon, lat)`**: **LONGITUDE FIRST** ($X = \text{lon}, Y = \text{lat}$). +- **WKT format**: also **`POINT(lon lat)`** — e.g. `'POINT(34.78 32.08)'` (Tel Aviv). +- **`great_circle_distance(lat1, lon1, lat2, lon2)`**: **LATITUDE FIRST**, and returns **km**. +- **`bing_tile_at(lat, lon, zoom)`**: **LATITUDE FIRST**. +- **Israel Sanity Check**: In Israel, Longitude $\approx 34\text{--}36$ and Latitude $\approx 29\text{--}33$. If coordinates show `lon: 32` and `lat: 34`, they are accidentally inverted! + +### Geometry Functions +- **Always**: `ST_GeometryFromText(wkt_string)` +- **Never**: `ST_GeomFromText()` or `ST_PolygonFromText()` — they do not exist in Trino. +- `ST_Distance` on WGS84 geometries returns **degrees**, not meters. For meters, wrap both sides in `to_spherical_geography(...)`. +- `ST_Contains` works on `geometry` (degrees), **NOT** on `SphericalGeography`. + +### Spatial Joins Acceleration +Put `ST_Contains` directly in the `JOIN ... ON` clause so Trino invokes its internal spatial join optimization: +```sql +SELECT z.zone_name, count(*) AS event_count +FROM "catalog"."schema"."events" e +JOIN "catalog"."schema"."zones" z + ON ST_Contains(ST_GeometryFromText(z.wkt), ST_Point(e.lon, e.lat)) +GROUP BY z.zone_name +``` diff --git a/agent/skills/temporal-analyst/SKILL.md b/agent/skills/temporal-analyst/SKILL.md new file mode 100644 index 0000000..7d877d3 --- /dev/null +++ b/agent/skills/temporal-analyst/SKILL.md @@ -0,0 +1,207 @@ +--- +name: temporal-analyst +description: Trino date and time handling — use when queries involve timestamps, date filtering, relative time expressions, date parsing from strings, or time zone conversions. Covers all common string timestamp formats in this database. +--- +# Temporal SQL Reference for Trino + +## The Core Problem: String-Stored Timestamps + +Many columns in this database store dates and times as VARCHAR strings rather than native DATE or TIMESTAMP types. +Before writing any date filter, check `get_column_profile` to confirm the actual data type and look at example values. + +If `column_type` is `varchar`, `text`, or `string` — you MUST use string-based parsing. + +--- + +## Identifying the Format from Example Values + +Run `get_sample_rows` or check the catalog's example values to identify the format before writing any date filter. + +| Example value | Format | Parse function | +|--------------|--------|----------------| +| `2024-01-15` | ISO date | `CAST(col AS DATE)` or `from_iso8601_date(col)` | +| `2024-01-15 14:30:00` | ISO datetime | `CAST(col AS TIMESTAMP)` | +| `2024-01-15T14:30:00` | ISO 8601 with T | `from_iso8601_timestamp(col)` | +| `2024-01-15T14:30:00Z` | ISO 8601 UTC (with Z) | `from_iso8601_timestamp(col)` | +| `15/01/2024` | European DD/MM/YYYY | `date_parse(col, '%d/%m/%Y')` | +| `01/15/2024` | US MM/DD/YYYY | `date_parse(col, '%m/%d/%Y')` | +| `15-Jan-2024` | Text month | `date_parse(col, '%d-%b-%Y')` | +| `20240115` | Compact YYYYMMDD | `date_parse(col, '%Y%m%d')` | +| `1705312200` | Unix epoch (seconds) | `from_unixtime(CAST(col AS BIGINT))` | +| `1705312200000` | Unix epoch (milliseconds) | `from_unixtime(CAST(col AS BIGINT) / 1000.0)` | +| `2024-01-15 14:30:00.000` | With milliseconds | `date_parse(col, '%Y-%m-%d %H:%i:%s.%f')` | + +--- + +## Safe Parsing & Filtering Patterns + +### Sargability: Never Wrap Filtered Timestamp Columns in Functions +Wrapping a timestamp/date column in a function prevents Trino from pruning partitions and evaluating min/max metadata statistics: +```sql +-- BAD (slow, prevents partition pruning): +WHERE date(event_at) = DATE '2024-05-01' +WHERE date_format(event_at, '%Y-%m-%d') = '2024-05-01' + +-- GOOD (sargable, fast half-open range): +WHERE event_at >= TIMESTAMP '2024-05-01 00:00:00' + AND event_at < TIMESTAMP '2024-05-02 00:00:00' +``` + +### Always cast string dates before comparing +```sql +-- WRONG: string comparison, not date comparison +WHERE date_col > '2024-01-01' + +-- CORRECT for ISO date strings +WHERE CAST(date_col AS DATE) >= DATE '2024-01-01' + +-- CORRECT for ISO timestamps with T/Z +WHERE from_iso8601_timestamp(date_col) >= TIMESTAMP '2024-01-01 00:00:00' + +-- CORRECT for non-ISO strings (e.g. DD/MM/YYYY) +WHERE date_parse(date_col, '%d/%m/%Y') >= DATE '2024-01-01' +``` + +### Truncating to a period +```sql +-- Group by month +date_trunc('month', CAST(date_col AS TIMESTAMP)) + +-- Group by year +date_trunc('year', CAST(date_col AS DATE)) + +-- Extract just the year as integer +YEAR(CAST(date_col AS DATE)) +EXTRACT(YEAR FROM CAST(date_col AS DATE)) +``` + +### Range filters (inclusive lower, exclusive upper — always safer for TIMESTAMP) +```sql +-- CORRECT: year 2023 +WHERE CAST(date_col AS DATE) >= DATE '2023-01-01' + AND CAST(date_col AS DATE) < DATE '2024-01-01' + +-- CORRECT: month of January 2024 +WHERE CAST(date_col AS DATE) >= DATE '2024-01-01' + AND CAST(date_col AS DATE) < DATE '2024-02-01' + +-- AVOID: '2023-12-31' as upper bound for TIMESTAMP — misses 2023-12-31 23:59:59 +``` + +--- + +## Relative Date Expressions + +> [!IMPORTANT] +> In Trino, the `INTERVAL` value **MUST be a quoted string literal**: +> - Write: `INTERVAL '1' DAY` or `INTERVAL '24' HOUR` +> - NEVER write: `INTERVAL 1 DAY` or `INTERVAL '1 day'` or `INTERVAL '1 days'` (all trigger parser syntax errors). + +```sql +-- Today +CURRENT_DATE + +-- Yesterday +CURRENT_DATE - INTERVAL '1' DAY +-- or: date_add('day', -1, CURRENT_DATE) + +-- Last 7 days (rolling) +WHERE CAST(date_col AS DATE) >= CURRENT_DATE - INTERVAL '7' DAY + +-- This month +WHERE date_trunc('month', CAST(date_col AS TIMESTAMP)) = date_trunc('month', CURRENT_TIMESTAMP) + +-- Last month +WHERE date_trunc('month', CAST(date_col AS TIMESTAMP)) = date_trunc('month', date_add('month', -1, CURRENT_TIMESTAMP)) + +-- Last N months +WHERE CAST(date_col AS DATE) >= date_add('month', -N, CURRENT_DATE) + +-- This year +WHERE YEAR(CAST(date_col AS DATE)) = YEAR(CURRENT_DATE) + +-- Last year +WHERE YEAR(CAST(date_col AS DATE)) = YEAR(CURRENT_DATE) - 1 +``` + +--- + +## Hebrew Temporal Expressions → SQL + +| Hebrew | SQL equivalent | +|--------|---------------| +| "אתמול" (yesterday) | `CAST(col AS DATE) = CURRENT_DATE - INTERVAL '1' DAY` | +| "השבוע" (this week) | `CAST(col AS DATE) >= date_trunc('week', CURRENT_DATE)` | +| "החודש" (this month) | `date_trunc('month', CAST(col AS TIMESTAMP)) = date_trunc('month', CURRENT_TIMESTAMP)` | +| "החודש שעבר" (last month) | Use date_add('month', -1, ...) | +| "השנה" (this year) | `YEAR(CAST(col AS DATE)) = YEAR(CURRENT_DATE)` | +| "ב-2023" (in 2023) | `YEAR(CAST(col AS DATE)) = 2023` | +| "בינואר" (in January) | `MONTH(CAST(col AS DATE)) = 1` + year filter | +| "ברבעון הראשון" (Q1) | `MONTH(CAST(col AS DATE)) BETWEEN 1 AND 3` | +| "ב-12 החודשים האחרונים" (last 12 months) | `CAST(col AS DATE) >= date_add('month', -12, CURRENT_DATE)` | +| "לפני X ימים" (X days ago) | `CAST(col AS DATE) = date_add('day', -X, CURRENT_DATE)` | + +--- + +## Time Zone Handling + +If the column stores UTC and you need local time (Israel = UTC+3 / UTC+2 depending on DST): +```sql +-- Convert UTC timestamp string to Israel local time +AT TIME ZONE 'UTC' AT TIME ZONE 'Asia/Jerusalem' + +-- Example +SELECT date_parse(col, '%Y-%m-%dT%H:%i:%s') AT TIME ZONE 'UTC' AT TIME ZONE 'Asia/Jerusalem' +``` + +--- + +## Duration and Interval Calculations + +```sql +-- Difference in days between two date strings +date_diff('day', + CAST(start_date_col AS DATE), + CAST(end_date_col AS DATE) +) + +-- Difference in hours between two timestamps +date_diff('hour', + date_parse(start_col, '%Y-%m-%d %H:%i:%s'), + date_parse(end_col, '%Y-%m-%d %H:%i:%s') +) +``` + +--- + +## Defensive Patterns + +### When the format may vary or the column has NULLs +```sql +-- TRY_CAST returns NULL instead of throwing on bad values +WHERE TRY_CAST(date_col AS DATE) >= DATE '2024-01-01' + +-- Check if parsing succeeds before using the column +SELECT * +FROM table +WHERE TRY_CAST(date_col AS DATE) IS NOT NULL + AND CAST(date_col AS DATE) >= DATE '2024-01-01' +``` + +### When you don't know the format — investigate first +```sql +-- Sample 20 distinct values to see the actual format +SELECT DISTINCT date_col FROM "catalog"."schema"."table" LIMIT 20 +``` +Then use `get_column_profile` to see example values before writing the parse call. + +--- + +## Common Mistakes to Avoid + +- `WHERE date_col = '2024-01-15'` on a TIMESTAMP column — matches only midnight, not the whole day +- `WHERE date_col BETWEEN '2024-01-01' AND '2024-12-31'` on a TIMESTAMP — misses Dec 31 23:59 +- `date_parse` with wrong format string — returns NULL silently or throws an error +- Using `NOW()` — Trino uses `CURRENT_TIMESTAMP` (no parentheses needed) +- Using `DATEDIFF` — Trino uses `date_diff('unit', start, end)` +- Using `DATE_FORMAT` — Trino uses `format_datetime(ts, 'pattern')` diff --git a/agent/skills/trino-expert/SKILL.md b/agent/skills/trino-expert/SKILL.md index 235e6aa..4a65cde 100644 --- a/agent/skills/trino-expert/SKILL.md +++ b/agent/skills/trino-expert/SKILL.md @@ -1,27 +1,210 @@ --- name: trino-expert -description: Advanced rules and syntax for Trino SQL queries, including arrays, JSON, aggregations, and datetime formats. +description: Trino SQL syntax rules, domain conventions, categorical filter patterns, aggregation correctness, join strategies, and systematic debugging for this database. --- -# Trino SQL Expert Guidelines +# Trino SQL Expert Reference -When writing Trino SQL queries, strictly follow these syntax guidelines: +## Core Rules Checklist -## Arrays and Collections -* **Searching Arrays**: When checking if a value exists in an array, ALWAYS use `contains(array, value)`. NEVER use `array_contains()`. -* **Unnesting**: If you need to join against an array column, use `CROSS JOIN UNNEST(array_col) AS t(element)`. +1. **Strings vs Identifiers**: Strings use single quotes `'abc'`. Identifiers with special chars or Hebrew use double quotes `"col"`. Never use backticks (\`col\`). +2. **Fully Qualified Names**: Always write full table names as given in the metadata: `"catalog"."schema"."table"`. +3. **Column Projection**: Never `SELECT *`. Select only the specific columns needed. +4. **Early Filtering**: Put filters in `WHERE` as early as possible (inside the innermost CTE); always filter the partition column on large tables. +5. **Row Limits**: Always add `LIMIT` to non-aggregate exploratory queries. Use `ORDER BY` + `LIMIT` for "top N" (or `RANK()` if ties must be preserved). +6. **Integer Division Truncation**: `5 / 2 = 2`. Use `CAST(a AS double) / b` or `1.0 * a / b` for ratios and percentages. +7. **Safe Division**: Divide safely: `x / NULLIF(y, 0)` to avoid division-by-zero crashes. +8. **GROUP BY Completeness**: Every non-aggregated column in `SELECT` must be included in `GROUP BY`. +9. **No Cross Joins & Distributed Join Order**: Every `JOIN` must have an explicit `ON` condition with keys. Put the large fact table on the left, and the small lookup/dimension table on the right. +10. **Distinct Cardinality**: Use `COUNT(DISTINCT x)` when exact is required; use `approx_distinct(x)` on large tables for speed. +11. **Case-Insensitive Matching**: Use `lower(col) LIKE lower('%text%')` or `regexp_like(col, '(?i)...')`. There is no `ILIKE`. +12. **NULL Checks**: Use `IS NULL` / `IS NOT NULL`. Never use `= NULL` or `!= NULL`. +13. **CTEs for Structure**: Use CTEs (`WITH x AS (...)`) for multi-step logic. Keep each CTE focused on a single responsibility. +14. **Strictly Read-Only**: Never write `INSERT`, `UPDATE`, `DELETE`, `DROP`, `CREATE`, `ALTER`. Read-only SELECT statements only. -## Nulls and Aggregations -* **Avoiding Nulls**: Wrap each column used in an aggregation with `COALESCE(column, 0)` to avoid NULLs ruining your calculation. -* **Counts**: When counting entities, always apply `DISTINCT` on the identifier column (e.g., `COUNT(DISTINCT id)`). +## Common Table Expressions (`WITH` Clauses) — Preferred SQL Style +- Trino has first-class, highly optimized support for CTEs (`WITH cte_name AS (...)`). +- **Always prefer CTEs over deeply nested subqueries**: + - Cleanly separates data preparation (filtering, date parsing, geometry) from final presentation. + - Aggregates child tables before joining to completely eliminate 1-to-many join fan-out. + - Enables window filtering (e.g. compute `ROW_NUMBER() / RANK() OVER (...)` in a CTE, filter `WHERE rn <= N` in the outer query). + - Makes SQL self-documenting, modular, and easy to inspect. -## Sorting and Limits -* **Distinct Sorting**: When using `ORDER BY
`, always add `GROUP BY ` before to select distinct values if you are returning unique records. -* **Top Values**: When querying for top (max/min) values, return ALL records that share the top value rather than applying a strict `LIMIT 1`, unless a secondary sorting is explicitly requested by the user. +## Arrays +- Check array membership: `contains(array_col, 'value')` — NEVER `array_contains()` +- Expand arrays: `CROSS JOIN UNNEST(array_col) AS t(element)` + +## Aggregations & Nulls +- **Integer Division Truncates**: `5 / 2 = 2`! When calculating ratios, percentages, or rates, integer division silently truncates to 0. + - Always cast the numerator: `CAST(a AS double) / NULLIF(b, 0)` or `1.0 * a / NULLIF(b, 0)`. + - Always divide safely with `NULLIF(y, 0)` to prevent runtime division-by-zero errors. +- **Idiomatic Conditional Counts**: Use `count_if(cond)` instead of verbose `SUM(CASE WHEN cond THEN 1 ELSE 0 END)`. + - Example: `count_if(status = 'active')` +- **Latest State Without Window / Self-Join**: Use `max_by(val, time)` or `min_by(val, time)` to find the latest value per entity: + - Example: `SELECT entity_id, max_by(status, updated_at) AS last_status, max(updated_at) AS last_at FROM t GROUP BY entity_id` +- Wrap aggregated columns: `COALESCE(col, 0)` to prevent NULL poisoning +- Count unique entities: `COUNT(DISTINCT id)` — not `COUNT(*)` +- `COUNT(*)` counts rows; `COUNT(col)` skips NULLs; `COUNT(DISTINCT col)` counts unique non-null values +- `AVG()` ignores NULLs — if NULLs mean "zero", use `AVG(COALESCE(col, 0))` + +## Dialect & Syntax Prohibitions +- **NO `ILIKE`**: Trino does NOT support `ILIKE`. Use `LOWER(col) LIKE LOWER('val')` or `regexp_like(col, '(?i)...')`. +- **NO Trailing Semicolons (`;`)**: Trino parser rejects queries ending in `;`. Never include trailing semicolons. +- **Identifier Quotes vs String Literals**: + - Double quotes `"catalog"."schema"."table"` or `"column"` are for identifiers. + - Single quotes `'string'` are for string literals. + - NEVER write `'column_name' = 'val'` — that compares two strings, not the database column! +- **Prohibited Token**: Never include the literal token `'kill'` anywhere in SQL. +- **Distinct Ordered Results**: + - To select distinct ordered values, use `SELECT DISTINCT col ... ORDER BY col`. + - Do NOT blindly add `GROUP BY ` before `ORDER BY` if there are other unaggregated columns, as Trino will throw a `GROUP BY` validation error. + +### Functions that DO NOT EXIST in Trino (Never Use) + +| Do NOT Write | Write in Trino Instead | +|---|---| +| `ILIKE '%text%'` | `LOWER(col) LIKE LOWER('%text%')` or `regexp_like(col, '(?i)text')` | +| `DATEADD`, `DATE_SUB`, `ADDDATE` | `date_add('day', n, ts)` or `ts + INTERVAL '1' DAY` | +| `DATEDIFF(a,b)`, `TIMESTAMPDIFF` | `date_diff('day', a, b)` (unit first, then start, then end) | +| `GETDATE()`, `SYSDATE`, `NOW` without () | `current_timestamp`, `now()`, `current_date` | +| `TO_DATE`, `STR_TO_DATE`, `TO_TIMESTAMP` | `date_parse`, `CAST`, `from_iso8601_timestamp` | +| `TO_CHAR`, `STRFTIME` | `format_datetime`, `date_format` | +| `IFNULL`, `NVL`, `ISNULL` | `coalesce(a, b)` | +| `IIF`, `DECODE` | `CASE WHEN ...` or `if(cond, a, b)` | +| `TOP n` | `LIMIT n` (at end of query) | +| `LEN`, `CHARINDEX`, `INSTR` | `length(col)`, `strpos(col, 'sub')` | +| `MEDIAN`, `PERCENTILE_CONT` | `approx_percentile(x, 0.5)` | +| `GROUP_CONCAT`, `STRING_AGG` | `array_join(array_agg(x), ',')` | +| `array_contains(arr, val)` | `contains(arr, val)` | +| `ST_MakePoint`, `ST_GeomFromText` | `ST_Point(lon, lat)`, `ST_GeometryFromText(wkt)` | +| `ST_SetSRID`, `ST_Transform` | None needed (Trino geometry operates directly on coordinates) | +| `ST_DWithin(a, b, r)` | `ST_Distance(to_spherical_geography(a), to_spherical_geography(b)) <= r` | +| `::type` (Postgres cast) | `CAST(x AS type)` | +| `INTERVAL 7 DAY` | `INTERVAL '7' DAY` (value must be quoted string) | +| `EXTRACT(EPOCH FROM ts)` | `to_unixtime(ts)` | + + +## Sorting & Top-N +- When querying for "the highest" or "the top", return ALL records sharing that top value — not just `LIMIT 1` — unless the user explicitly asks for a single result +- Use `RANK() OVER (ORDER BY col DESC)` when ties must be preserved +- `ROW_NUMBER()` breaks ties arbitrarily — use only when exactly one record per group is needed + +## Dates & Times +- Cast explicitly: `CAST(date_string AS DATE)`, `CAST(ts AS TIMESTAMP)` +- Use ISO 8601 strings for date literals: `DATE '2024-01-01'` +- Relative dates: `CURRENT_DATE`, `date_add('day', -N, CURRENT_DATE)`, `date_trunc('month', CURRENT_DATE)` +- Year filter: `col >= DATE '2024-01-01' AND col < DATE '2025-01-01'` (open-ended upper bound is safer than `<= '2024-12-31'` for timestamps) +- Month filter: `date_trunc('month', col) = DATE '2024-01-01'` + +## Categorical Filters — The #1 Correctness Issue +The user says "מגורים". The database stores "Residential". They are NOT the same string. + +Before writing ANY string equality filter (`WHERE col = '...'`): +1. Check `get_column_profile` — if `domainIsComplete: true`, the example values ARE the full value set +2. Use `search_column_values` with the user's term to find the exact database spelling +3. After writing SQL, pass it through `enrich_sql_filters` as an automatic correctness pass + +For `semantic_type: large_categorical` columns: always use `search_column_values` — never assume or use LIKE blindly. + +**Interpreting `search_column_values` results:** +- Use the `value` field from each result — that is the exact database string +- High `keyword_similarity` (close to 1.0) = good lexical match +- Low `semantic_distance` (close to 0.0) = good semantic match +- If multiple values match, find a filter or combination of filters (e.g. `col IN ('value1', 'value2', ...)` or a well-crafted LIKE) that covers all variants (unless the question targets a specific one). +- If no values match at all, the filter value may not exist in the data — investigate before writing a WHERE clause that will return 0 rows + +## Join Strategy + +### Always verify join keys before writing JOIN +- `get_sample_rows` on both sides to check that key formats match (e.g., both are integers, both use the same city_code format) +- `get_table_relationships` for known FK relationships + +### Fan-out detection (aggregation correctness) +A 1-to-many JOIN inflates row counts. `COUNT(*)` after such a join is wrong. + +Quick diagnostic: compare COUNT before and after the join: +```sql +-- How many flights exist? +SELECT COUNT(*) FROM "postgres"."public"."flights_table" WHERE launch_country = 'France' +-- How many rows after JOIN? +SELECT COUNT(*) FROM "postgres"."public"."flights_table" f +JOIN "postgres"."public"."flight_alerts_table" a ON f.flight_id = a.flight_id +WHERE f.launch_country = 'France' +``` +If second > first → fan-out → use `COUNT(DISTINCT f.flight_id)` or aggregate before joining. + +### Join type selection & Distributed Execution Order +- **Big Table on Left, Small Table on Right**: In Trino distributed joins, the right table is broadcast to worker nodes. Always put the largest fact table on the LEFT and the smaller lookup/dimension table on the RIGHT. +- **No Cross Joins**: Every `JOIN` must have an explicit `ON` condition with matching keys. +- **INNER JOIN**: only rows that exist in both tables — use when the relationship is guaranteed. +- **LEFT JOIN**: keep all left-side rows even without a match — use for "per entity" metrics where some entities may have zero related records. +- **Anti-join** (NOT EXISTS / LEFT JOIN ... WHERE right.key IS NULL): entities with NO related records. + +### Set Operations (`UNION ALL` vs `UNION`) +- Always prefer `UNION ALL` over `UNION`. In Trino, `UNION` triggers an expensive distributed distinct/deduplication pass across all worker nodes. Only use `UNION` if deduplication across result sets is strictly required. + +### Partition Column Pruning +- If the catalog or table metadata indicates a partition column (e.g. `dt`, `date_key`, `p_date`), **always include a filter on the partition column directly in its native type** to avoid scanning entire clusters. + + +## Window Functions +```sql +-- Rank within group (e.g., top 3 cities per district) +ROW_NUMBER() OVER (PARTITION BY district ORDER BY area_kmr DESC) AS rn +-- Then filter: WHERE rn <= 3 +``` + +## Zero-Row Investigation +If your query returns 0 rows unexpectedly, investigate in this order: +1. String filter values — `search_column_values` or `get_column_distinct_values` +2. Join key alignment — `get_sample_rows` on both tables to verify key format matches +3. Date range logic — is the column a `DATE` or `TIMESTAMP`? Are the casts correct? +4. NULL presence — `get_column_profile` shows null_ratio; high null columns often filter everything out +5. Remove filters one by one to isolate which one eliminates all rows + +## SQL Exploration Patterns +When multiple logic paths seem plausible (INNER vs LEFT JOIN, different grouping strategies), run 2–3 variations with `LIMIT 10` and compare results to choose the correct one — don't guess. + +When schema is ambiguous, map the user's Hebrew terms to English tables/columns mentally before drafting. + +## Per-Capita / Per-Entity Patterns +Notice the franularity difference between the numerator and the denominator. For example in the question: +"alerts per person" = COUNT(alerts) / SUM(population) — not AVG(count_per_row). + +When the denominator comes from a different table, aggregate it independently in a CTE, then divide: +```sql +WITH alert_counts AS ( + SELECT district, COUNT(*) AS alerts + FROM alert_table GROUP BY district +), +populations AS ( + SELECT district, SUM(population) AS pop + FROM city_table GROUP BY district +) +SELECT a.district, a.alerts * 1.0 / p.pop AS alerts_per_capita +FROM alert_counts a JOIN populations p ON a.district = p.district +``` + +## Trino Error → Fix Diagnostic Reference + +When `execute_trino_query` returns an error, consult this lookup table: + +| Error Message Contains | Cause | Corrective Action | +|---|---|---| +| `Cannot apply operator: timestamp = varchar` | Comparing timestamp to text | Convert with `TIMESTAMP '...'` literal or `CAST(varchar_col AS timestamp)`. | +| `Cannot apply operator: varchar = integer` | Column is varchar or literal is unquoted | Use `CAST(col AS integer)` / `try_cast` or quote the literal `'123'`. | +| `Value cannot be cast to timestamp` | Text has `T` / `Z` or custom format | Use `from_iso8601_timestamp(col)` for ISO format, or `date_parse(col, fmt)`. | +| `Invalid format` (in `date_parse`) | Wrong format specifiers | Trino uses MySQL codes (`%Y-%m-%d %H:%i:%s`; note `%i` for minutes, NOT `%M`). | +| `Function 'x' not registered` / `Unknown function` | Invented or non-Trino dialect function | Check "Functions that DO NOT EXIST in Trino" table above and substitute. | +| `Unexpected parameters for function x` | Wrong argument types | Cast parameters to types expected by the function. | +| `Column 'x' cannot be resolved` | Misspelled column or invalid alias | Check exact spelling in metadata profile; verify table alias prefix. | +| `Table 'x' does not exist` | Missing catalog/schema or wrong name | Use fully qualified name: `"catalog"."schema"."table"`. | +| `must be an aggregate expression or appear in GROUP BY` | Non-aggregated column in SELECT | Add the missing column to `GROUP BY` or wrap it in an aggregate function. | +| `mismatched input` / `extraneous input` | Dialect syntax error | Replace backticks with `"`, fix `INTERVAL '1' DAY` (must have quotes), remove `::`. | +| `Division by zero` | Zero denominator | Wrap divisor in `NULLIF(denominator, 0)`. | +| `Scalar sub-query has returned multiple rows` | Subquery returns >1 row | Add `LIMIT 1`, aggregate, or convert to a `JOIN`. | +| `Latitude must be between -90 and 90` | Inverted coordinate order | Coordinates swapped: use `ST_Point(lon, lat)` (longitude first). | +| `ST_Contains ... SphericalGeography` | Containment on geography | `ST_Contains` requires `geometry` (degrees). Convert with `to_geometry()`. | +| `Query exceeded per-node memory limit` | Too much data processed | Narrow the time/partition range, select fewer columns, or pre-aggregate in a CTE. | +| `Filter required on ... for at least one partition column` | Missing partition filter | Add a partition column filter in its native type (e.g. `WHERE dt = '...'`). | -## Dates and Times -* **Format**: Always work with ISO 8601 format strings. -* **Casting**: Explicitly `CAST(date_string AS DATE)` or `CAST(timestamp_string AS TIMESTAMP)` when performing date math. -## Schema Linking -* **Complex Domains**: If the user's Hebrew request involves complex domain logic or a highly fragmented database schema, mentally map Hebrew terms to English tables/columns before drafting SQL. -* **Diverse Synthesis**: If multiple SQL logic paths seem plausible (e.g., unsure whether to use an INNER JOIN vs a LEFT JOIN), you can generate 2 or 3 variations, execute them all using `execute_trino_query` with `LIMIT 10`, and compare the results to deduce the correct approach. diff --git a/agent/src/agent/services/hybrid_searcher.py b/agent/src/agent/services/hybrid_searcher.py index f76038c..97d58fe 100644 --- a/agent/src/agent/services/hybrid_searcher.py +++ b/agent/src/agent/services/hybrid_searcher.py @@ -91,9 +91,9 @@ async def search(filters: List[SQLFilterParams], tables: List[AgentSQLTable]) -> # Schedule search task directly via MCP client # The MCP backend handles semantic_type routing automatically task = client.search_column_values( - query=clean_val, - table_name=table_lower or None, - column_name=col_lower or None + search_term=clean_val, + table=table_lower or None, + column=col_lower or None ) tasks.append(task) diff --git a/agent/src/agent/utils/jeen_metadata_client.py b/agent/src/agent/utils/jeen_metadata_client.py index b5b8307..89f8415 100644 --- a/agent/src/agent/utils/jeen_metadata_client.py +++ b/agent/src/agent/utils/jeen_metadata_client.py @@ -156,27 +156,38 @@ async def _call(self, tool_name: str, arguments: dict[str, Any]) -> Any: # ------------------------------------------------------------------ async def search_column_values( - self, query: str, table_name: str | None = None, column_name: str | None = None - ) -> list[str]: + self, + search_term: str, + table: str | None = None, + column: str | None = None, + limit: int | None = None, + raw: bool = False, + ) -> list[str] | dict[str, Any]: """ Looks up real values a column contains using semantic and keyword matching via MCP. + Uses exact MCP parameter names: search_term, table, column, limit. + When raw=True, returns the full payload dictionary from the MCP server. """ if not self.is_configured: logger.warning("JeenMetadataClient is not configured. Returning empty search results.") - return [] - + return [] if not raw else {"error": "JeenMetadataClient is not configured."} + + lim = limit if limit is not None else self._search_limit args: dict[str, Any] = { "connection_id": self._connection_id, - "search_term": query, - "limit": self._search_limit, + "search_term": search_term, + "limit": lim, } - if table_name: - args["table"] = table_name - if column_name: - args["column"] = column_name + if table: + args["table"] = table + if column: + args["column"] = column try: payload = await self._call("search_column_values", args) + if raw: + return payload if isinstance(payload, dict) else {"values": payload} + if isinstance(payload, dict) and "values" in payload: results = [] for v in payload["values"]: @@ -185,10 +196,12 @@ async def search_column_values( else: results.append(str(v)) return results + elif isinstance(payload, list): + return [str(x) for x in payload] return [] except Exception as exc: logger.error("JeenMetadataClient.search_column_values failed: %s", exc, exc_info=True) - return [] + return [] if not raw else {"error": str(exc)} # ------------------------------------------------------------------ # Glossary / Context @@ -267,15 +280,21 @@ async def get_table_profile(self, table_name: str, connection_id: int | None = N table_profile: dict = payload.get("table_profile") or {} if isinstance(payload, dict) else {} columns_raw: list[dict] = payload.get("columns") or [] if isinstance(payload, dict) else [] - # Normalise column list into the shape the agent already consumes + # Normalise column list into the shape the agent consumes columns = [] for col in columns_raw: + null_val = col.get("nullRatio") if col.get("nullRatio") is not None else (col.get("nullRate") or col.get("null_rate")) + distinct_val = col.get("distinctCount") if col.get("distinctCount") is not None else col.get("distinct_count") + sem_type = col.get("semanticType") or col.get("semantic_type") or col.get("columnRole") or "unknown" + entry: dict[str, Any] = { "name": col.get("columnName") or col.get("column_name") or col.get("name", ""), "type": col.get("dataType") or col.get("data_type") or col.get("type", ""), - "null_rate": round(float(col.get("nullRate") or col.get("null_rate") or 0.0), 4), - "distinct_count": int(col.get("distinctCount") or col.get("distinct_count") or 0), - "semantic_type": col.get("semantic_type") or "unknown", + "null_rate": round(float(null_val or 0.0), 4), + "distinct_count": int(distinct_val or 0), + "semantic_type": sem_type, + "domain_is_complete": bool(col.get("domainIsComplete") or col.get("domain_is_complete", False)), + "example_values": col.get("exampleValues") or col.get("example_values") or [], } # Propagate optional stats if available for src_key, dst_key in [ @@ -321,7 +340,7 @@ async def get_column_profile(self, table_name: str, column_name: str) -> dict[st Returns the latest stored statistics for a single column: role, null ratio, distinct count, min/max, and example values. """ try: - profile = await self._call( + res = await self._call( "get_column_profile", { "connection_id": self._connection_id, @@ -329,11 +348,88 @@ async def get_column_profile(self, table_name: str, column_name: str) -> dict[st "column_name": column_name, }, ) - return profile if isinstance(profile, dict) else None + if isinstance(res, dict): + return res.get("profile") or res + return None except Exception as exc: logger.error("JeenMetadataClient.get_column_profile failed: %s", exc) return None + # ------------------------------------------------------------------ + # Prompt & Scoping Tools + # ------------------------------------------------------------------ + + # async def get_filtered_prompt(self, question: str, connection_id: int | None = None) -> dict[str, Any]: + # """ + # Returns metadata prompt narrowed to the question: the most relevant columns, + # knowledge pairs, and business terms. Returns { 'prompt': str, 'meta': dict }. + # """ + # cid = connection_id if connection_id is not None else self._connection_id + # return await self._call("get_filtered_prompt", {"connection_id": cid, "question": question}) + + # async def resolve_question(self, question: str, connection_id: int | None = None) -> dict[str, Any]: + # """ + # Explains how a question maps onto this connection's curated vocabulary: + # glossary terms, synonyms, acronyms, tables, and columns. + # """ + # cid = connection_id if connection_id is not None else self._connection_id + # return await self._call("resolve_question", {"connection_id": cid, "question": question}) + + # ------------------------------------------------------------------ + # Tables, Columns & Relationships Structure + # ------------------------------------------------------------------ + + async def get_tables(self, connection_id: int | None = None) -> list[dict[str, Any]]: + """ + Returns the list of tables for a connection with business descriptions and quoted identifiers. + """ + cid = connection_id if connection_id is not None else self._connection_id + res = await self._call("get_tables", {"connection_id": cid}) + if isinstance(res, dict) and "tables" in res: + return res["tables"] + return res if isinstance(res, list) else [] + + async def get_columns(self, table_name: str | None = None, connection_id: int | None = None) -> list[dict[str, Any]]: + """ + Returns columns for connection (data type, primary key, description, example values, profiling stats). + """ + cid = connection_id if connection_id is not None else self._connection_id + args: dict[str, Any] = {"connection_id": cid} + if table_name: + args["table_name"] = table_name + res = await self._call("get_columns", args) + if isinstance(res, dict) and "columns" in res: + return res["columns"] + return res if isinstance(res, list) else [] + + async def get_relationships(self, connection_id: int | None = None) -> list[dict[str, Any]]: + """ + Returns source-scoped foreign-key and semantic-model joins for a connection. + """ + cid = connection_id if connection_id is not None else self._connection_id + res = await self._call("get_relationships", {"connection_id": cid}) + if isinstance(res, dict) and "relationships" in res: + return res["relationships"] + return res if isinstance(res, list) else [] + + async def get_source_statistics(self, connection_id: int | None = None) -> dict[str, Any]: + """ + Stored source profile summary: latest profile run, table types, column roles. + """ + cid = connection_id if connection_id is not None else self._connection_id + return await self._call("get_source_statistics", {"connection_id": cid}) + + # ------------------------------------------------------------------ + # Query Execution via MCP + # ------------------------------------------------------------------ + + async def run_query(self, query: str, max_rows: int = 100, connection_id: int | None = None) -> dict[str, Any]: + """ + Executes a read-only SQL query via the MCP server on connections where can_execute=True. + """ + cid = connection_id if connection_id is not None else self._connection_id + return await self._call("run_query", {"connection_id": cid, "query": query, "max_rows": max_rows}) + # ------------------------------------------------------------------ # Full table listing (fallback when search returns nothing) # ------------------------------------------------------------------ @@ -401,17 +497,6 @@ async def search_knowledge_pairs(self, query: str, limit: int = 10) -> Any: logger.error("search_knowledge_pairs failed: %s", exc) return {"error": str(exc)} - async def search_column_values(self, query: str, table: str = None, column: str = None, limit: int = 10) -> Any: - """Looks up the real values a column contains (large categorical resolver).""" - args = {"connection_id": self._connection_id, "query": query, "limit": limit} - if table: args["table"] = table - if column: args["column"] = column - try: - return await self._call("search_column_values", args) - except Exception as exc: - logger.error("search_column_values failed: %s", exc) - return {"error": str(exc)} - # --------------------------------------------------------------------------- # Module-level singleton (lazy-initialised, safe to import at module load) diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 4956ea9..8e9134e 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -2,13 +2,18 @@ Agent logic and LangGraph harness for the Deep Agent. """ -from langchain_core.messages import SystemMessage from deepagents import create_deep_agent as create_harness_agent from langgraph.checkpoint.memory import MemorySaver from deep_agent.tools import ( get_database_catalog, + # get_filtered_prompt, + # resolve_question, + get_database_tables, + get_table_columns, + get_table_relationships, get_table_profile, + get_column_profile, execute_trino_query, get_sample_rows, get_column_distinct_values, @@ -16,61 +21,235 @@ search_business_terms, search_knowledge_pairs, search_column_values, - get_column_profile, resolve_location_to_wkt, validate_sql_syntax, + enrich_sql_filters, ) import datetime from agent.llm import get_llm -SYSTEM_PROMPT = """You are an elite, highly autonomous Deep SQL Analyst. You are decisive, analytical, and follow exploratory methodology without deviation. +SYSTEM_PROMPT = """You are an elite, autonomous Deep SQL Analyst. Your mission: translate Hebrew natural-language questions into verified Trino SQL that is **semantically correct** — not just syntactically valid or merely executable. + +Today's date: {today}. + +--- + +## Non-negotiable Principle + +**Execution success ≠ correctness.** A query can run, return rows, and still be wrong. Semantic correctness — whether the SQL actually answers the user's question — is your responsibility. You must verify this, not just execute and hope. + +--- + +## Phase 1 — Understand (Discovery) + +Start here. Then move on — don't over-explore. + +- `get_database_catalog` — full schema with column stats and semantic types. **Call once, reuse the result.** + - If the catalog shows `(no knowledge pairs)`, do NOT call `search_knowledge_pairs`. + - If the catalog shows `(no business terms)`, do NOT call `search_business_terms`. + - If the catalog shows `(no relationships)`, do NOT call `get_table_relationships` (infer joins from matching column names like `flight_id`). +- `search_knowledge_pairs` — prior solved examples (use only when available in catalog). Check before exploring from scratch. +- `search_business_terms` / `search_metadata` — resolve ambiguous Hebrew/domain terms (use only when available in catalog). +- `get_table_relationships` — verified foreign keys and join paths (use only when available in catalog). + +Simple, unambiguous lookups may skip directly to Phase 2. + +--- + +## Phase 2 — Ground the Query Semantics (MANDATORY for any JOIN or aggregation) + +Before writing a single line of SQL, answer these: + +1. **Output grain**: What does ONE result row represent? (a flight? a city? a district count?) — state this explicitly +2. **Aggregation unit**: Am I counting *rows* or counting *distinct entities*? If there's a JOIN, which side? +3. **Fan-out risk**: Does any JOIN create a 1-to-many relationship? If yes, `COUNT(*)` will be inflated — plan to use `COUNT(DISTINCT id)` or aggregate in a CTE before joining +4. **String filters**: Every categorical filter value must be verified — use `search_column_values`, then `enrich_sql_filters` +5. **Date column type**: Is it a native DATE/TIMESTAMP or a VARCHAR string? Check `get_column_profile` — if string, you must parse it (see temporal-analyst skill) + +For complex or aggregation-heavy questions, write 1–2 lines stating the intent before drafting: +> *"Intent: count distinct flights (not rows) from France. The flights↔alerts join is 1-to-many, so I must use COUNT(DISTINCT flight_id), not COUNT(*)."* + +--- + +## Phase 3 — Value Resolution (By Semantic Type & Cardinality) + +Understand what each tool supports and choose based on the column's `semantic_type` and cardinality: + +> **Tool Capability Scope**: `search_column_values` works EXCLUSIVELY on **`large_categorical`** and **`large_unit_id`** columns. +> *(Standard `categorical` and `boolean` columns are NOT indexed in search and will return 0 matches. Numeric, date/timestamp, and geometry are also not indexed).* + +1. **High-Cardinality (`large_categorical` / `large_unit_id`)** (e.g., `city_name`, Company Name, Product SKU, Person Name): + - These columns contain hundreds or thousands of unique values that cannot fit in the system prompt. + - **`search_column_values` is the ideal tool**: Targeted hybrid search finds how the DB actually spells the specific entity (e.g., "Acme Corp" → "Acme Corporation LLC", or "Tel Aviv" → "Tel Aviv 1", "Tel Aviv 2"). + - If search reveals a composite pattern (e.g., "Tel Aviv 1", "Tel Aviv 57"), formulate a pattern filter like `LIKE 'Tel Aviv%'` or `IN (...)`. + - Avoid calling `get_column_distinct_values` on high-cardinality columns — dumping 50–100 random values into context is slow (10–20s) and will rarely hit the entity you need. + +2. **Standard `categorical` & `boolean`** (e.g., `launch_country`, Status, Priority, Flight Type, Gender, IsActive): + - **Do NOT call `search_column_values`** on standard `categorical` or `boolean` columns — they are not indexed in vector search and will return 0 results! + - Instead, check the catalog/profile first — when `domainIsComplete: true`, all valid values are already listed in the catalog without needing a tool call! + - If not listed in the catalog, call `get_column_distinct_values` to see the full set of valid options (usually just 5–20 rows, e.g. 7 countries in `launch_country`). + +3. **Numeric, Date, Timestamp, or Geometry columns**: + - `search_column_values` is NOT available for these types (not indexed). + - Use `get_sample_rows`, column profile min/max stats, or SQL casting/date parsing functions (see temporal-analyst skill). + +4. **AST Safety Net (`enrich_sql_filters`)**: + - After drafting SQL, call `enrich_sql_filters` — it automatically verifies and aligns your WHERE clause text filters against database metadata at the AST level before execution. + +--- + +## Phase 4 — Draft & Validate + +- **Use CTEs (`WITH ... AS (...)`) for clean, modular SQL**: + - Trino has first-class, highly optimized support for CTEs. + - Break complex or multi-step logic into named CTE blocks (e.g. `WITH filtered_data AS (...), aggregated_counts AS (...)`). + - CTEs make queries significantly cleaner to read, prevent join fan-out (by aggregating child tables in a CTE before joining), and make window rankings (`ROW_NUMBER() / RANK()`) and multi-stage metrics easy to organize. +- SQL uses ONLY confirmed 3-part table names: `"catalog"."schema"."table"` +- `validate_sql_syntax` — free, instant, catches typos and wrong function names. Always call before `execute_trino_query` on a fresh draft. +- `enrich_sql_filters` — run on any SQL that filters text columns + +--- + +## Phase 5 — Execute & Diagnose + +- `execute_trino_query` — always LIMIT exploratory queries +- **Classify the error before retrying** (the response includes `error_category`): + - `SYNTAX_ERROR` → fix the specific line only, do not redesign + - `TABLE_NOT_FOUND` / `COLUMN_NOT_FOUND` → re-verify exact identifiers from catalog + - `TYPE_MISMATCH` → add `CAST(col AS type)` + - `FUNCTION_NOT_FOUND` → check Trino function spelling + - `0 rows` → investigate filter values, join keys, NULLs — do NOT just retry +- **NEVER retry an identical query without a meaningful change** + +--- -Your goal is to answer complex user questions (written in Hebrew) by thoroughly exploring the Trino database, discovering the correct schema, writing precise SQL, and returning the exact answer. +## Phase 6 — Semantic Verification (MANDATORY for JOINs and aggregations) -**Current Context**: -* Today's date is: {today}. Use this to natively resolve relative time expressions (e.g., 'last month', 'yesterday') when building queries. +After a successful execution, validate before responding: -You have access to a suite of highly specialized tools. You are free to determine the best path to solve the user's request. -If you need to perform an extensive catalog search, profile many columns, or run complex exploratory tasks that will bloat your context, you can autonomously use your `task` tool to spawn a subagent to do the heavy lifting for you! +**Fan-out check** — if you joined two tables and aggregated: +```sql +-- Run this diagnostic if the count seems high: +SELECT COUNT(*) FROM left_table WHERE ; -- entity count before join +SELECT COUNT(*) FROM left_table JOIN right_table ON ...; -- row count after join +-- If second > first → fan-out confirmed → use COUNT(DISTINCT id) +``` -**CRITICAL REQUIREMENT FOR FINAL RESPONSE**: -Even if a subagent executed the query for you, YOUR final response to the user MUST contain the exact successful SQL query enclosed in a markdown block (```sql ... ```) at the very bottom. Do not forget this! +**Grain check** — does each row in your result represent the entity the user asked about? + +**Completeness check** — does the WHERE clause cover every condition the user mentioned? Did you accidentally add a condition they didn't ask for? + +**Sanity check** — does the number make intuitive sense? (e.g., "500 alerts from 3 districts" sounds plausible; "10,000 distinct flights from a 1,000-row table" does not) + +If any check fails or is uncertain, run a targeted diagnostic query. Do not guess. + +--- + +## Tool Reference + +**Schema & Metadata** +- `get_database_catalog` — complete schema. Use ONCE; reuse in context. +- `get_database_tables` — quick table roster with quoted identifiers +- `get_table_columns` — columns with types, examples, profiling stats +- `get_table_relationships` — verified foreign keys +- `get_table_profile` / `get_column_profile` — deep stats; `domainIsComplete: true` means listed values are the ENTIRE value set + +**Discovery** +- `search_metadata` — search all schema entities by concept +- `search_business_terms` — map Hebrew/domain vocabulary to DB terminology +- `search_knowledge_pairs` — prior solved examples (often reveals join paths) + +**Value Resolution** +- `search_column_values` — targeted search ONLY for high-cardinality entities (`large_categorical`, `large_unit_id`). Do NOT call on regular `categorical` or `boolean` (they are not indexed and return 0 matches). +- `resolve_location_to_wkt` — Hebrew location → WKT polygon for `ST_GeometryFromText(...)` + +**Execution** +- `execute_trino_query` — runs SQL; response includes `error_category` on failure +- `get_sample_rows` — peek at raw data format, string casing, date format +- `get_column_distinct_values` — live distinct values. Appropriate for standard low-cardinality `categorical` columns (e.g. `launch_country`) when not listed in catalog. +- `validate_sql_syntax` — free dry-run. Call before every execute on a new draft. + +**Post-processing** +- `enrich_sql_filters` — AST-level auto-correction of categorical filter values. Use after drafting SQL with text filters. + +**Delegation** +- `task` — spawn a subagent for heavy exploration (many tables/columns) without consuming your context + +--- + +## Hard Constraints + +- NEVER guess or assume a string filter value — verify via tools +- NEVER reference a table or column not confirmed in the catalog +- ALWAYS use exact 3-part table names: `"catalog"."schema"."table"` +- ALWAYS LIMIT exploratory queries +- NEVER use `ST_GeomFromText()` — only `ST_GeometryFromText()` exists in Trino +- NEVER use `ILIKE` (unsupported in Trino) — use `LOWER(col) LIKE LOWER('val')` or `regexp_like(col, '(?i)...')` +- NEVER end queries with a semicolon `;` (Trino parser rejects trailing semicolons) +- NEVER wrap column identifiers in single quotes `'col'` (single quotes are for string literals only) +- NEVER include the literal token `'kill'` anywhere in SQL +- NEVER write SQL inline comments (`--` or `/* */`) +- NEVER use Hebrew as SQL identifiers or variable names +- NEVER return 0-row results without first investigating why +- NEVER retry an identical failed query without a meaningful change + +--- + +## Final Response Format (Hebrew) + +Your response MUST be in Hebrew and include: +1. A brief explanation of what the SQL does +2. A markdown table of the actual query results +3. The exact successful SQL in a ```sql``` block at the very bottom """ + def create_deep_agent(): """ - Creates and returns a compiled LangGraph ReAct agent equipped with our deep exploration tools. + Creates and returns a compiled LangGraph deep agent equipped with all exploration, + enrichment, temporal, geospatial, and semantic validation tools. """ llm = get_llm() - + tools = [ + # Discovery & Schema get_database_catalog, + get_database_tables, + get_table_columns, + get_table_relationships, get_table_profile, get_column_profile, - execute_trino_query, - validate_sql_syntax, - get_sample_rows, - get_column_distinct_values, + # Search & Resolve search_metadata, search_business_terms, search_knowledge_pairs, search_column_values, resolve_location_to_wkt, + # Query Execution + execute_trino_query, + get_sample_rows, + get_column_distinct_values, + validate_sql_syntax, + # Post-processing + enrich_sql_filters, ] - - # We use a simple MemorySaver for ephemeral memory per thread + memory = MemorySaver() - today = datetime.date.today().isoformat() - + agent = create_harness_agent( model=llm, tools=tools, system_prompt=SYSTEM_PROMPT.format(today=today), checkpointer=memory, memory=["/Users/benben/Desktop/code/text2sql-onboarding/agent/AGENTS.md"], - skills=["/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/trino-expert", "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/spatial-analyst"], + skills=[ + "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/trino-expert", + "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/spatial-analyst", + "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/temporal-analyst", + "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/semantic-validation", + ], ) - + return agent diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 01dad3a..24c3414 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -1,45 +1,175 @@ import json import logging -import datetime +import asyncio from typing import Optional -from pydantic import Field from langchain_core.tools import tool -from langchain_core.prompts import PromptTemplate from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from agent.utils.sql import clean_sql, resolve_wkt_polygons from core.trino import execute_query_sync from agent.services.geo_utils import get_geojson_polygon, geojson_to_simplified_wkt -from agent.llm import get_llm logger = logging.getLogger(__name__) + +# --------------------------------------------------------------------------- +# Database Catalog & Schema +# --------------------------------------------------------------------------- + +# Connection capability flags dynamically inferred from the catalog prompt +_connection_capabilities: dict[str, bool] = { + "has_knowledge_pairs": True, + "has_business_terms": True, + "has_relationships": True, +} + + @tool async def get_database_catalog() -> str: """ Retrieves the complete metadata catalog and structural overview for the database. - - Use this FIRST when starting any new query to discover what tables exist, how they relate, and to see column profiling statistics. + + Use this FIRST when starting any new query to discover what tables exist, how they relate, + and to see column profiling statistics including semantic types, null ratios, and distinct counts. + + The output includes Column/Table Names, Descriptions, Types, Universal Base Metrics (Null Rate, + Distinct Count, Cardinality Ratio) and specific Profiling Data Payloads. + + Column semantic_type values to watch for: + - 'categorical' — small finite value set; use search_column_values to resolve exact spellings. + - 'large_categorical' — too many values to enumerate; use search_column_values with query terms. + - 'geo' — WKT geometry column; use resolve_location_to_wkt to build filter values. + Do NOT use this to fetch live data rows; this only retrieves metadata and schema definitions. - - The output payload includes Column/Table Names, Descriptions, Types, Universal Base Metrics (Null Rate, Distinct Count) and specific Profiling Data Payloads. """ client = get_jeen_metadata_client() try: catalog_prompt = await client.get_catalog_prompt() - return catalog_prompt + + lower_prompt = catalog_prompt.lower() + has_kp = "(no knowledge pairs)" not in lower_prompt + has_bt = "(no business terms)" not in lower_prompt + has_fk = "(no relationships)" not in lower_prompt + + _connection_capabilities["has_knowledge_pairs"] = has_kp + _connection_capabilities["has_business_terms"] = has_bt + _connection_capabilities["has_relationships"] = has_fk + + footer_lines = [ + "\n\n---", + "### Discovery Capabilities Note:", + f"- Knowledge Pairs: {'Available' if has_kp else 'None (skip search_knowledge_pairs)'}", + f"- Business Terms: {'Available' if has_bt else 'None (skip search_business_terms)'}", + f"- Foreign Keys: {'Available' if has_fk else 'None (infer joins from column names)'}", + ] + return catalog_prompt + "\n".join(footer_lines) except Exception as e: return f"Error fetching catalog: {str(e)}" + +# @tool +# async def get_filtered_prompt(question: str) -> str: +# """ +# Retrieves a narrowed, highly focused catalog prompt scoped specifically to the user's question. +# Contains the AI-selected most relevant columns, primary keys, foreign key joins, and relevant +# knowledge pairs / business terms. + +# Use this when you want a compact, fast overview of just the tables and columns relevant to +# the current question without reading the massive full database catalog. + +# Args: +# question (str): The natural language question (Hebrew or English). +# """ +# client = get_jeen_metadata_client() +# try: +# res = await client.get_filtered_prompt(question) +# if isinstance(res, dict) and "prompt" in res: +# return res["prompt"] +# return json.dumps(res, indent=2, ensure_ascii=False) +# except Exception as e: +# return f"Error fetching filtered prompt: {e}" + + +# @tool +# async def resolve_question(question: str) -> str: +# """ +# Explains how a question maps onto this connection's curated vocabulary: +# which glossary terms, synonyms, acronyms, tables and columns it mentions and what they resolve to. + +# Use this when encountering ambiguous domain abbreviations, jargon, or Hebrew concepts to +# see the curated glossary and lexicon mappings. + +# Args: +# question (str): The natural language question or phrase in Hebrew or English. +# """ +# client = get_jeen_metadata_client() +# try: +# res = await client.resolve_question(question) +# return json.dumps(res, indent=2, ensure_ascii=False) +# except Exception as e: +# return f"Error resolving question: {e}" + + +@tool +async def get_database_tables() -> str: + """ + Returns the list of all tables in the connection with their business descriptions and + exact quoted identifiers ("catalog"."schema"."table") for querying. + Use this for a quick, clean roster of available tables. + """ + client = get_jeen_metadata_client() + try: + tables = await client.get_tables() + return json.dumps(tables, indent=2, ensure_ascii=False) + except Exception as e: + return f"Error fetching tables: {e}" + + +@tool +async def get_table_columns(table_name: str) -> str: + """ + Returns the columns for a specific table: data type, primary key flag, business description, + real example values, and profiling statistics. + + Args: + table_name (str): The table identifier (e.g. '"postgres"."public"."flights_table"' or 'flights_table'). + """ + client = get_jeen_metadata_client() + try: + cols = await client.get_columns(table_name) + return json.dumps(cols, indent=2, ensure_ascii=False) + except Exception as e: + return f"Error fetching columns for {table_name}: {e}" + + +@tool +async def get_table_relationships() -> str: + """ + Returns the source-scoped foreign-key and semantic join relationships between tables. + Use this to identify exact join paths and foreign key pairs. + """ + if not _connection_capabilities.get("has_relationships", True): + return "[] (Notice: This connection has NO foreign key relationships defined in the catalog. Infer joins using matching column names, e.g. flight_id.)" + client = get_jeen_metadata_client() + try: + rels = await client.get_relationships() + return json.dumps(rels, indent=2, ensure_ascii=False) + except Exception as e: + return f"Error fetching relationships: {e}" + + @tool async def get_table_profile(table_name: str) -> str: """ - Retrieves the latest stored schema and statistics for one specific table. - - Use this to understand a single table's row counts, column roles, null ratios, distinct counts, and min/max values. + Retrieves the latest stored schema and statistics for one specific table. + + Use this to understand a single table's row counts, column roles, null ratios, distinct counts, + and min/max values before writing SQL against it. Do NOT use this to fetch raw data rows; use `get_sample_rows` or `execute_trino_query` instead. - + Args: - table_name (str): The fully qualified, exact 3-part name of the table, e.g., '"catalog"."schema"."table"'. + table_name (str): The fully qualified, exact 3-part name of the table, + e.g., '"catalog"."schema"."table"'. """ client = get_jeen_metadata_client() try: @@ -50,16 +180,19 @@ async def get_table_profile(table_name: str) -> str: except Exception as e: return f"Error fetching table schema: {str(e)}" + @tool async def get_column_profile(table_name: str, column_name: str) -> str: """ Retrieves the latest stored statistics for a single specific column. - + Use this before writing a WHERE clause to learn exactly how values are formatted in the database. - Do NOT use this for live dynamic querying of values; this only reads pre-computed metadata. - - If the output shows 'domainIsComplete: true', the listed values are the entire value set, so any other value can be safely ruled out. The 'semanticType' field indicates how the column should be searched (e.g., categorical, geo). - + If 'domainIsComplete: true', the listed example values are the ENTIRE value set — any other + value can be safely ruled out. The 'semanticType' field indicates how to search the column + (e.g., categorical, large_categorical, geo). + + Do NOT use this for live dynamic querying of values; this reads pre-computed metadata only. + Args: table_name (str): The fully qualified exact name of the table, e.g., '"catalog"."schema"."table"'. column_name (str): The exact name of the column to profile. @@ -73,155 +206,415 @@ async def get_column_profile(table_name: str, column_name: str) -> str: except Exception as e: return f"Error fetching column profile: {str(e)}" + +# --------------------------------------------------------------------------- +# Query Execution +# --------------------------------------------------------------------------- + +def _classify_trino_error(error_message: str) -> str: + """Classify a Trino error message into an actionable category.""" + msg = error_message.lower() + if any(k in msg for k in ["syntax error", "mismatched input", "parse error", "unexpected"]): + return "SYNTAX_ERROR" + if any(k in msg for k in ["table not found", "schema not found", "catalog not found", "does not exist"]): + return "TABLE_NOT_FOUND" + if any(k in msg for k in ["column", "field", "not found in", "cannot resolve"]): + return "COLUMN_NOT_FOUND" + if any(k in msg for k in ["type mismatch", "cannot cast", "invalid cast", "expected", "varchar", "bigint", "double"]): + return "TYPE_MISMATCH" + if any(k in msg for k in ["function not found", "no function", "not a function"]): + return "FUNCTION_NOT_FOUND" + if any(k in msg for k in ["timeout", "exceeded", "resource", "query killed"]): + return "TIMEOUT_OR_RESOURCE" + return "EXECUTION_ERROR" + + @tool def execute_trino_query(sql: str, limit: int = 50) -> str: """ - Executes a read-only Trino SQL query and returns the resulting rows. - + Executes a read-only Trino SQL query and returns the resulting rows. + Use this to test SQL queries against the actual database and perform exploratory data analysis. - Do NOT use this for queries returning millions of rows; it will crash the context. Always use LIMIT. - + Always use LIMIT on exploratory queries to avoid pulling millions of rows. + + IMPORTANT — WKT Location Tokens: + If your SQL contains location placeholders in the form '@location_name_wkt@' (produced by + resolve_location_to_wkt), you MUST replace them with the actual WKT string before calling + this tool. Pass the raw WKT inside ST_GeometryFromText('...') directly in the SQL string. + + On failure, the response includes an 'error_category' field to help you classify and fix + the error precisely: + - SYNTAX_ERROR: fix the specific syntax — do not redesign the query + - TABLE_NOT_FOUND / COLUMN_NOT_FOUND: re-verify exact identifiers from the catalog + - TYPE_MISMATCH: add an explicit CAST(col AS type) + - FUNCTION_NOT_FOUND: check the Trino function name + - TIMEOUT_OR_RESOURCE: simplify the query or add a tighter LIMIT + Args: - sql (str): The exact Trino SQL query string to execute. - limit (int): The maximum number of rows to return (from 1 to 100). Defaults to 50. + sql (str): The exact Trino SQL query string to execute. Markdown fences and trailing + semicolons are stripped automatically. + limit (int): The maximum number of rows to return (1–100). Defaults to 50. """ - sql_clean = sql.strip().rstrip(';') + sql_clean = clean_sql(sql).rstrip(';') if "limit" not in sql_clean.lower(): sql_clean = f"{sql_clean} LIMIT {limit}" - + try: res = execute_query_sync(sql_clean) if not res.success: - return f"Error executing query: {res.error_message}" - + error_msg = res.error_message or "Unknown error" + error_category = _classify_trino_error(error_msg) + result_dict = { + "success": False, + "error_category": error_category, + "error_message": error_msg, + "hint": { + "SYNTAX_ERROR": "Fix the specific syntax line — do not redesign the entire query.", + "TABLE_NOT_FOUND": "Re-verify the exact 3-part table name from get_database_catalog.", + "COLUMN_NOT_FOUND": "Re-verify the column name from get_table_columns for this table.", + "TYPE_MISMATCH": "Add CAST(column AS target_type) for the mismatched column.", + "FUNCTION_NOT_FOUND": "Check Trino function spelling. E.g., use ST_GeometryFromText, not ST_GeomFromText.", + "TIMEOUT_OR_RESOURCE": "Add a tighter LIMIT or simplify the query.", + "EXECUTION_ERROR": "Investigate the specific error message.", + }.get(error_category, "Investigate the error message."), + } + return json.dumps(result_dict, ensure_ascii=False) + result_dict = { + "success": True, "columns": res.columns, "row_count": res.row_count, - "rows": res.rows + "rows": res.rows, } return json.dumps(result_dict, ensure_ascii=False, default=str) except Exception as e: - return f"Execution failed: {str(e)}" + return json.dumps({ + "success": False, + "error_category": "EXECUTION_ERROR", + "error_message": str(e), + }, ensure_ascii=False) + @tool def get_sample_rows(table_name: str, limit: int = 5) -> str: """ Retrieves a small number of raw data rows from a table using a live Trino query. - - Use this only when schema profiles do not provide enough context and you must see exact raw data formats. + + Use this only when schema profiles don't provide enough context and you must see exact raw + data formats (e.g., date formatting, nested JSON structure, exact string casing). Do NOT use this for counting or aggregating data. - + Args: table_name (str): The fully qualified exact name of the table. - limit (int): The number of rows to sample (from 1 to 10). Defaults to 5. + limit (int): The number of rows to sample (1–10). Defaults to 5. """ safe_table = table_name.split()[0].rstrip(';') sql = f"SELECT * FROM {safe_table} LIMIT {limit}" return execute_trino_query.invoke({"sql": sql, "limit": limit}) + @tool def get_column_distinct_values(table_name: str, column_name: str, limit: int = 50) -> str: """ Executes a live Trino query to fetch unique values for a specific column. - Use this to see exact existing strings in the database before writing an exact-match WHERE clause. - Do NOT use this if the catalog or `get_column_profile` already provided the exhaustive list of categorical values. - + + BEST USED FOR: + - Low-cardinality `categorical` columns (e.g. status, priority, category) where you want to see all + 5-20 possible valid values, and they aren't already complete in the catalog (`domainIsComplete: false`). + + DO NOT USE FOR: + - High-cardinality columns (`large_categorical`, `large_unit_id`, names, SKUs, cities). Dumping 50-100 + random values from a table with thousands of entities wastes tokens and latency without finding the + specific entity you need. Use `search_column_values` instead for targeted entity search. + - Numeric, date, or continuous columns (checking unique values is meaningless for value matching). + - Columns where the catalog already says `domainIsComplete: true` (all values are already known). + Args: table_name (str): The fully qualified exact name of the table. column_name (str): The exact name of the column. - limit (int): Maximum distinct values to return (from 1 to 100). Defaults to 50. + limit (int): Maximum distinct values to return (1–100). Defaults to 50. """ safe_table = table_name.split()[0].rstrip(';') safe_col = column_name.split()[0].rstrip(';') sql = f"SELECT DISTINCT {safe_col} FROM {safe_table} LIMIT {limit}" return execute_trino_query.invoke({"sql": sql, "limit": limit}) + +# --------------------------------------------------------------------------- +# SQL Quality +# --------------------------------------------------------------------------- + +@tool +def validate_sql_syntax(sql: str) -> str: + """ + Validates the syntax of a Trino SQL query without executing it against data. + + Use this to dry-run a query and instantly catch syntax errors (missing CASTs, typos, bad + function names). This is cheap — always call this before execute_trino_query on a new draft. + Do NOT use this to check if a query returns 0 rows; it only checks syntax validity. + + Args: + sql (str): The exact Trino SQL query string to validate. + """ + sql_clean = clean_sql(sql).rstrip(';') + try: + res = execute_query_sync(f"EXPLAIN (TYPE VALIDATE) {sql_clean}") + if res.success: + return "Syntax is VALID." + else: + return f"Syntax Error: {res.error_message}" + except Exception as e: + return f"Validation failed: {str(e)}" + + +# --------------------------------------------------------------------------- +# Metadata Search +# --------------------------------------------------------------------------- + @tool async def search_metadata(query: str, limit: int = 10) -> str: """ Searches the metadata catalog across all tables, columns, relationships, and business terms. - - Use this to quickly discover relevant schema or glossary context when you aren't sure which table to look at. - Do NOT use this to search for specific data row values (e.g., 'John Doe'); use `search_column_values` instead. - + + Use this to quickly discover relevant schema or glossary context when you aren't sure which + table to look at. Works well with Hebrew or English terms. + Do NOT use this to search for specific data row values (e.g., 'John Doe'); use + `search_column_values` instead. + Args: - query (str): The search text (multilingual/Hebrew support) to match against metadata names and descriptions. + query (str): The search text (multilingual/Hebrew support) to match against metadata. limit (int): Maximum number of results to return. Defaults to 10. """ client = get_jeen_metadata_client() res = await client.search(query, limit) return json.dumps(res, indent=2, ensure_ascii=False) + @tool async def search_business_terms(query: str, limit: int = 10) -> str: """ Searches the business glossary for terms relevant to a natural language question. - - Use this to bridge the gap between user vocabulary and database terminology (e.g., matching 'sales' to 'Revenue'). + + Use this to bridge the gap between user vocabulary and database terminology + (e.g., matching 'מכירות' to the 'Revenue' column). Ranked by semantic meaning, not keywords. Do NOT use this to search for database tables or column names directly. - - The search is multilingual and ranks by meaning rather than exact keywords. - + Args: query (str): A natural language question or phrase (multilingual support). limit (int): Maximum number of results to return. Defaults to 10. """ + if not _connection_capabilities.get("has_business_terms", True): + return "[] (Notice: This connection has NO business terms defined in the catalog. Do not call this tool again.)" client = get_jeen_metadata_client() res = await client.search_business_terms(query, limit) return json.dumps(res, indent=2, ensure_ascii=False) + @tool async def search_knowledge_pairs(query: str, limit: int = 10) -> str: """ Searches saved question-and-query examples that are semantically similar to the user's question. - - Use this to find few-shot examples of how similar questions were solved previously before writing your own query. - Even if you think you know how to write the query, searching for similar past questions often reveals domain-specific SQL conventions, exact JOIN paths, or edge cases you haven't considered. - - Do NOT pass SQL keywords as the query; pass the raw natural language question exactly as the user wrote it (in Hebrew). - - Only the stored question is matched (never the query text), so it works best with full natural language sentences. - + + Use this to find few-shot examples of how similar questions were solved previously. Even if you + think you know how to write the query, similar past examples often reveal domain-specific SQL + conventions, exact JOIN paths, or edge cases you haven't considered. + + Pass the raw Hebrew natural language question exactly as the user wrote it — never SQL keywords. + Only the stored question is matched (never the query text), so full sentences work best. + Args: query (str): The natural language user question (multilingual/Hebrew support). limit (int): Maximum number of results to return. Defaults to 10. """ + if not _connection_capabilities.get("has_knowledge_pairs", True): + return "[] (Notice: This connection has NO knowledge pairs defined in the catalog. Do not call this tool again.)" client = get_jeen_metadata_client() res = await client.search_knowledge_pairs(query, limit) return json.dumps(res, indent=2, ensure_ascii=False) + @tool -async def search_column_values(query: str, table: Optional[str] = None, column: Optional[str] = None, limit: int = 10) -> str: +async def search_column_values( + search_term: str, + table: Optional[str] = None, + column: Optional[str] = None, + limit: int = 10, +) -> str: """ - Searches for exact real values contained within text columns across the database. - - Use this before writing a WHERE clause on a text column when you only have a partial or loosely spelled value (e.g., finding 'Tel Aviv' from 'tel aviv'). - Do NOT use this on numeric or date columns. - - Matching is multilingual for descriptive values and substring-based for codes and identifiers, ensuring you find the exact database spelling. - + Searches for exact real values contained within indexed columns across the database. + + SUPPORTED COLUMN TYPES: + Works exclusively on high-cardinality columns profiled as: + # - `boolean` (not indexed in search MCP — use catalog or get_column_distinct_values) + # - `categorical` (not indexed in search MCP — use catalog or get_column_distinct_values) + - `large_categorical` + - `large_unit_id` + ⚠️ Do NOT use on standard `categorical` or `boolean` columns (e.g. `launch_country`) — they are + not indexed in vector search and will return 0 matches! Use `get_column_distinct_values` or the catalog instead. + Do NOT use on numeric, date/timestamp, or geometry columns. + + WHEN TO USE: + - Use whenever you need to find how a high-cardinality entity is represented or spelled in the database + (e.g., finding 'Tel Aviv 1' from 'תל אביב' or 'Acme Corp' from 'Acme'). Multilingual, + keyword, and vector search finds the exact database spelling. + - Essential for high-cardinality columns (`large_categorical`, `large_unit_id`) where dumping + all distinct values is infeasible. + + The response includes: + - A 'top_matches' summary listing the exact values you should use in SQL + - If multiple values share a common prefix (e.g., 'Tel Aviv 1', 'Tel Aviv 57'), + the column stores composite strings — use LIKE 'prefix%' in SQL to match all variants + - 'keyword_similarity' close to 1.0 = strong lexical match + - 'semantic_distance' close to 0.0 = strong semantic match + Args: - query (str): The specific value to look for (partial or full string). - table (str, optional): Restrict to one table. Omit to search all tables. - column (str, optional): Restrict to one column. Omit to search all columns. + search_term (str): The specific value to look for (partial or full string, Hebrew or English). + table (str, optional): Restrict search to one table name. Omit to search all tables. + column (str, optional): Restrict search to one column name. Omit to search all columns. limit (int): Maximum number of results to return. Defaults to 10. """ client = get_jeen_metadata_client() - res = await client.search_column_values(query, table, column, limit) - return json.dumps(res, indent=2, ensure_ascii=False) + res = await client.search_column_values(search_term=search_term, table=table, column=column, limit=limit, raw=True) + + # Build an actionable summary of the top matches at the top of the response + summary_lines = [] + if isinstance(res, dict) and "values" in res: + values = res["values"] + if values: + summary_lines.append(f"TOP MATCHES for '{search_term}' (use these exact strings in SQL):") + seen_values = [] + for v in values[:5]: + if isinstance(v, dict): + val = v.get("value", "") + tbl = v.get("table_name", "") + col = v.get("column_name", "") + ks = round(v.get("keyword_similarity", 0), 3) + sd = round(v.get("semantic_distance", 1), 3) + summary_lines.append(f" - '{val}' (table: {tbl}, column: {col}, keyword_sim: {ks}, sem_dist: {sd})") + seen_values.append(val) + + # Detect composite prefix pattern (e.g., 'Tel Aviv 1', 'Tel Aviv 57') + import re as _re + prefixes = [] + for val in seen_values: + m = _re.match(r'^([A-Za-z\s\'\-\.]+?)\s*\d+$', val.strip()) + if m: + prefixes.append(m.group(1).strip()) + if prefixes: + common_prefix = max(set(prefixes), key=prefixes.count) + if prefixes.count(common_prefix) >= 2: + summary_lines.append( + f"\nNOTE: Multiple values share prefix '{common_prefix}' " + f"— this column stores composite strings (name + code). " + f"Use LIKE '{common_prefix}%' to match all variants, or pick one specific value." + ) + else: + summary_lines.append(f"No matches found for '{search_term}'. The value may not exist in this column.") + + summary = "\n".join(summary_lines) + full_payload = json.dumps(res, indent=2, ensure_ascii=False) + return f"{summary}\n\nFull payload:\n{full_payload}" + + +# --------------------------------------------------------------------------- +# Category Enrichment (Automatic Filter Value Correction) +# --------------------------------------------------------------------------- + +@tool +async def enrich_sql_filters( + user_request: str, + sql: str, + jeen_catalog: str, +) -> str: + """ + Automatically corrects categorical filter values in a draft SQL query to match exact + database spellings using semantic search and LLM-guided AST transformation. + + Use this AFTER you have written a draft SQL query that contains WHERE clause filters on + categorical (text) columns. It will: + 1. Parse the SQL AST to find comparison filters + 2. Semantically search the database for canonical matching values + 3. Use an LLM to select the best match + 4. Rewrite the SQL with exact canonical values (AST-level, not string replacement) + + This is especially powerful for Hebrew→English column value resolution and large categorical + columns where manually calling search_column_values for every filter would be tedious. + + Do NOT use this on purely numeric SQL or when you already have exact confirmed values. + + Returns the enriched SQL string, or the original SQL if no enrichment was needed/possible. + + Args: + user_request (str): The original natural language request from the user (Hebrew). + sql (str): The draft SQL query to enrich. + jeen_catalog (str): The full catalog string (output of get_database_catalog). + """ + from agent.services.enrichment_orchestrator import EnrichmentOrchestrator + from agent.nodes.refiner import parse_jeen_catalog_tables + + sql_clean = clean_sql(sql) + try: + schema, tables = parse_jeen_catalog_tables(jeen_catalog) + if not tables: + return f"Could not parse schema from catalog. Original SQL returned unchanged:\n{sql_clean}" + refined_sql, plan, enriched = await EnrichmentOrchestrator.enrich_query( + user_request=user_request, + initial_sql=sql_clean, + schema=schema, + tables=tables, + config=None, + ) + + if enriched and plan: + changes = [] + for tf in plan.enrichment_details: + if tf.changed_filter: + changes.append( + f" • column '{tf.column}': '{tf.original_value}' → {tf.refined_values} " + f"(operator: {tf.old_operator} → {tf.new_operator})" + ) + summary = "\n".join(changes) if changes else " (no changes logged)" + return ( + f"✅ SQL enriched successfully. Changes made:\n{summary}\n\n" + f"Enriched SQL:\n```sql\n{refined_sql}\n```" + ) + else: + return ( + f"ℹ️ No categorical filter corrections needed. Original SQL:\n```sql\n{sql_clean}\n```" + ) + + except Exception as e: + logger.error(f"enrich_sql_filters failed: {e}", exc_info=True) + return f"Error during enrichment (original SQL unchanged): {e}\n\n```sql\n{sql_clean}\n```" + + +# --------------------------------------------------------------------------- +# Geospatial +# --------------------------------------------------------------------------- @tool def resolve_location_to_wkt(location_name: str) -> str: """ Resolves a geographic location name to its WKT (Well-Known Text) polygon representation. - - Use this to get the exact WKT coordinates when you need to filter geographically using `ST_GeometryFromText()` and only have a city/region name. - Do NOT use this for exact addresses; it is designed for cities, regions, and countries. - + + Use this whenever the user's query involves a geographic area and you need a WKT polygon for + a Trino ST_GeometryFromText() / ST_Within() / ST_Intersects() call. + + Supports Hebrew location names directly (e.g., 'תל אביב', 'ירושלים', 'חיפה'). + Returns a simplified polygon quoted WKT string, e.g., 'POLYGON((...))', ready to embed + directly into SQL: ST_GeometryFromText(). + + The function uses rate-limited Nominatim geocoding with caching and automatic WKT + simplification (binary search), falling back to a bounding-box polygon if needed. + + Do NOT use this for exact addresses (e.g., "Rothschild 10, Tel Aviv"); it is designed for + administrative areas: cities, regions, districts, and countries. + Args: - location_name (str): The name of the geographic location to resolve (e.g., 'Paris, France'). + location_name (str): The geographic location name to resolve. Hebrew names are + accepted and preferred for Israeli locations. """ geojson = get_geojson_polygon(location_name) if geojson: @@ -229,24 +622,3 @@ def resolve_location_to_wkt(location_name: str) -> str: if wkt: return wkt return f"Error: Could not resolve location '{location_name}' to WKT." - -@tool -def validate_sql_syntax(sql: str) -> str: - """ - Validates the syntax of a Trino SQL query without executing it against data. - - Use this to dry-run a query and instantly catch syntax errors (like missing CASTs or typos). - Do NOT use this to check if a query returns 0 rows; it only checks syntax validity. - - Args: - sql (str): The exact Trino SQL query string to validate. - """ - sql_clean = sql.strip().rstrip(';') - try: - res = execute_query_sync(f"EXPLAIN (TYPE VALIDATE) {sql_clean}") - if res.success: - return "Syntax is VALID." - else: - return f"Syntax Error: {res.error_message}" - except Exception as e: - return f"Validation failed: {str(e)}" From 70df85c4b6c9357786559103b777e81ec8205a9d Mon Sep 17 00:00:00 2001 From: Stav Ponte Date: Tue, 20 Oct 2026 12:29:06 +0300 Subject: [PATCH 04/37] chore(deep-agent): proper CLI entry point, drop committed logs and scratch files - Move run_deep_agent.py to deep_agent.cli with a [project.scripts] 'deep-agent' entry point; no sys.path hacks or global urllib3 warning suppression - Package deep_agent in the wheel (uv_build module-name list) - Handle list-form message content (fixes TypeError in SQL extraction) - Replace CWD CSV logging with opt-in, schema-stable JSONL (--log-file) - Remove agent/deep_agent_logs.csv and agent/test_stream.py; ignore agent/runs/, agent/*.csv, agent/*.jsonl Closes #46 Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + agent/README.md | 15 ++ agent/deep_agent_logs.csv | 25 --- agent/pyproject.toml | 6 + agent/run_deep_agent.py | 261 --------------------------- agent/src/deep_agent/__init__.py | 0 agent/src/deep_agent/cli.py | 278 +++++++++++++++++++++++++++++ agent/test_stream.py | 12 -- agent/tests/deep_agent/__init__.py | 0 agent/tests/deep_agent/test_cli.py | 65 +++++++ 10 files changed, 367 insertions(+), 298 deletions(-) delete mode 100644 agent/deep_agent_logs.csv delete mode 100644 agent/run_deep_agent.py create mode 100644 agent/src/deep_agent/__init__.py create mode 100644 agent/src/deep_agent/cli.py delete mode 100644 agent/test_stream.py create mode 100644 agent/tests/deep_agent/__init__.py create mode 100644 agent/tests/deep_agent/test_cli.py diff --git a/.gitignore b/.gitignore index 2ecd8c9..5d36b89 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,9 @@ deploy_key # Scratch files agent/scratch/* +agent/runs/ +agent/*.csv +agent/*.jsonl fix_agent_langfuse.py fix_langfuse.py diff --git a/agent/README.md b/agent/README.md index 17f2bc0..096779f 100644 --- a/agent/README.md +++ b/agent/README.md @@ -35,3 +35,18 @@ graph TD finalizer --> END((END)) ``` + +## Running the deep agent locally + +The deep agent (`src/deep_agent/`) has a CLI entry point: + +```bash +uv sync +uv run deep-agent "כמה טיסות המריאו מצרפת" # single question, fresh thread +uv run deep-agent --interactive --session-memory # REPL, shared thread across questions +uv run deep-agent "..." --connection-id 89 # override JEEN_METADATA_CONNECTION_ID +uv run deep-agent "..." --log-file runs/runs.jsonl # append one JSON line per run +``` + +It reads the same `agent/.env` settings as the API (LLM, Trino, Jeen metadata MCP, Langfuse). +Run logs are opt-in and git-ignored (`agent/runs/`, `agent/*.jsonl`, `agent/*.csv`); Langfuse is the system of record for traces. diff --git a/agent/deep_agent_logs.csv b/agent/deep_agent_logs.csv deleted file mode 100644 index ffa28bb..0000000 --- a/agent/deep_agent_logs.csv +++ /dev/null @@ -1,25 +0,0 @@ -Timestamp,Execution Time (s),Question,Final SQL,Final Answer -2026-08-13 15:38:25,10.55,כמה טיסות המריאו מצרפת,None,המספר הכולל של טיסות שהמריאו מצרפת הוא **466**. -2026-08-13 15:41:01,16.14,what cities are in Haifa district,None,הערים שמופיעות בטבלת **city_info_table** כש‑`mahoz_namepqr = 'Haifa District'` הן:\n\n- Ashdod 146 \n- Ashdod 62 \n- Ashdod 90 \n- Bat Yam 26 \n- Beer Sheva 22 \n- Bnei Brak 150 \n- Bnei Brak 66 \n- Bnei Brak 94 \n- Haifa 129 \n- Haifa 143 \n- Haifa 45 \n- Haifa 87 \n- Herzliya 55 \n- Herzliya 83 \n- Holon 107 \n- Holon 121 \n- Holon 79 \n- Jerusalem 142 \n- Kfar Saba 56 \n- Kfar Saba 84 \n- Netanya 133 \n- Netanya 7 \n- Petah Tikva 103 \n- Petah Tikva 145 \n- Petah Tikva 5 \n- Petah Tikva 61 \n- Petah Tikva 75 \n- Rehovot 67 \n- Rehovot 81 \n- Rishon LeZion 46 \n- Tel Aviv 1 \n- Tel Aviv 57 \n\n(הנתונים נלקחו ישירות משאילתת SQL על הטבלה `city_info_table`.) -2026-08-13 15:42:14,27.03,what cities are in the Haifa district,None,הערים שמופיעות בטבלת `city_info_table` עם ערך `mahoz_namepqr = 'Haifa District'` הן:\n\n- אשדוד \n- בת ים \n- באר שבע \n- בני ברק \n- חיפה \n- הרצליה \n- חולון \n- ירושלים \n- כפר סבא \n- נתניה \n- פתח תקווה \n- רחובות \n- ראשון לציון \n- תל אביב \n\n(הערה: בטבלה יש מספרים שמצורפים לשמות הערים (למשל “אשדוד 146”). הרשימה למעלה מציגה רק את שמות הערים עצמם.) -2026-08-13 15:44:52,10.6,כמה טיסות המריאו מצרפת,None,המספר הכולל של טיסות שהמריאו מצרפת הוא **466**. -2026-08-13 15:45:42,10.06,כמה טיסות המריאו מצרפת,None,המספר הכולל של טיסות שהמריאו מצרפת הוא **466**. -2026-08-13 15:49:36,17.79,"""חשב את מספר התראות הטיסה לנפש עבור כל מחוז. לאחר מכן, עבור 3 המחוזות עם כמות ההתראות הגבוהה ביותר, ציין את 3 הערים הגדולות ביותר בכל מחוז על בסיס שטח הפנים שלהן.""",None,**מספר התראות טיסה לנפש לפי מחוז (ה‑3 מחוזות עם הכי הרבה התראות)** \n\n| מחוז | מספר התראות |\n|------|--------------|\n| Tel Aviv District | 435 |\n| Haifa District | 431 |\n| Central District | 330 |\n\n**ה‑3 ערים הגדולות ביותר בכל אחד מהמחוזות (על‑פי שטח פנים – `area_kmr`)**\n\n| מחוז | 1. העיר (שטח) | 2. העיר (שטח) | 3. העיר (שטח) |\n|------|----------------|----------------|----------------|\n| **Tel Aviv District** | Bat Yam 40 – 123.6 km² | Herzliya 97 – 123.42 km² | Petah Tikva 19 – 116.34 km² |\n| **Haifa District** | Holon 121 – 116.0 km² | Petah Tikva 61 – 108.34 km² | Haifa 143 – 107.03 km² |\n| **Central District** | Kfar Saba 126 – 124.83 km² | Holon 65 – 120.63 km² | Haifa 115 – 116.81 km² |\n\n*הנתונים נלקחו מטבלאות `flight_alerts_table` (מספר ההתראות) ו‑`city_info_table` (שטח הפנים של ערים).* -2026-08-13 15:54:30,3.42,/,None,האם יש משהו נוסף שתרצה לדעת או לשנות בתשובה? -2026-08-13 15:56:04,78.43,"""חשב את מספר התראות הטיסה לנפש עבור כל מחוז. לאחר מכן, עבור 3 המחוזות עם כמות ההתראות הגבוהה ביותר, ציין את 3 הערים הגדולות ביותר בכל מחוז על בסיס שטח הפנים שלהן.""","WITH alerts AS (\n SELECT ci.mahoz_namepqr AS district,\n COUNT(*) AS alert_count\n FROM ""postgres"".""public"".""flight_alerts_table"" fa\n JOIN ""postgres"".""public"".""city_info_table"" ci\n ON fa.city_code = ci.city_code\n GROUP BY ci.mahoz_namepqr\n),\ntop3 AS (\n SELECT district, alert_count\n FROM alerts\n ORDER BY alert_count DESC\n LIMIT 3\n),\ncity_rank AS (\n SELECT ci.mahoz_namepqr AS district,\n ci.city_name,\n ci.area_kmr,\n ROW_NUMBER() OVER (PARTITION BY ci.mahoz_namepqr ORDER BY ci.area_kmr DESC) AS rn\n FROM ""postgres"".""public"".""city_info_table"" ci\n WHERE ci.mahoz_namepqr IN (SELECT district FROM top3)\n)\nSELECT t.district,\n t.alert_count,\n cr.city_name,\n cr.area_kmr\nFROM top3 t\nJOIN city_rank cr\n ON t.district = cr.district\n AND cr.rn <= 3\nORDER BY t.alert_count DESC, cr.area_kmr DESC;","**מספר התראות טיסה לכל מחוז (ה‑3 מחוזות עם הכי הרבה התראות) וה‑3 ערים הגדולות ביותר בכל מחוז לפי שטח הפנים**\n\n| מחוז | מספר התראות | עיר | שטח (קמ""ר) |\n|------|-------------|------|------------|\n| **Tel Aviv District** | 435 | Bat Yam 40 | 123.6 |\n| | | Herzliya 97 | 123.42 |\n| | | Petah Tikva 19 | 116.34 |\n| **Haifa District** | 431 | Holon 121 | 116.0 |\n| | | Petah Tikva 61 | 108.34 |\n| | | Haifa 143 | 107.03 |\n| **Central District** | 330 | Kfar Saba 126 | 124.83 |\n| | | Holon 65 | 120.63 |\n| | | Haifa 115 | 116.81 |\n\n*ה‑3 מחוזות הראשונים נבחרו על‑פי מספר ההתראות הגבוה ביותר (לא על‑פי התראות לנפש, מכיוון שאין נתוני אוכלוסייה תואמים בטבלאות הקיימות). עבור כל מחוז נבחרו שלוש הערים בעלות השטח הפנימי הגדול ביותר.*" -2026-10-14 11:10:45,21.95,כמה טיסות המריאו מצרפת,"SELECT COUNT(*) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France';","**הסבר** \nהקוד סופר את מספר השורות בטבלת הטיסות שבהן ערך העמודה `launch_country` הוא **France**, כלומר מספר הטיסות שהמריאו מצרפת.\n\n**תוצאות השאילתה**\n\n| flight_count |\n|--------------|\n| 466 |" -2026-10-14 11:39:51,29.78,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(*) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","הקוד מחשב את מספר הטיסות שהמריאו מצרפת ונחתו בתל‑אביב (הערך בעמודת `city_name` מתחיל במילה ""Tel Aviv"").\n\n| flight_count |\n|--------------|\n| 28 |" -2026-10-17 11:52:10,31.18,query_1da529e6,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(*) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","**הסבר** \nהשאילתה סופרת את מספר הטיסות בטבלת **flights_table** שהמדינה שבה המריאו היא **France** והיעד (העיר שבה נחתו) הוא **תל אביב**. בעמודת `city_name` שמכילה שם העיר עם קוד, משתמשים ב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל השורות שבהן שם העיר מתחיל ב‑""Tel Aviv"". \n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 |" -2026-10-17 12:00:37,30.6,query_8edd6a90,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(DISTINCT flight_id) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","**הסבר** \nהשאילתה סופרת את מספר הטיסות הייחודיות (`flight_id`) שהושקו מצרפת (`launch_country = 'France'`) ונחתו בתל אביב. בעמודת `city_name` שמכילה את שם העיר עם קוד, משתמשים ב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל הווריאנטים של תל אביב.\n\n| flight_count |\n|--------------|\n| 28 |" -2026-10-17 12:10:08,20.77,query_a67fbaa4,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(DISTINCT flight_id) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';",**הסבר** \nהשאילתה סופרת את מספר הטיסות (מזהה טיסה ייחודי) שהמריאו מצרפת (`launch_country = 'France'`) ונחתו בתל‑אביב. בעמודת `city_name` של טבלת **flights_table** שמורים שמות ערים עם קידוד (לדוגמה `Tel Aviv 1`). לכן השתמשנו ב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל הווריאנטים של תל‑אביב.\n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 | -2026-10-17 13:06:35,24.25,query_c2e32b21,"מצא את אזורי ההנחיה שבהם מדיניות הטיסה אוסרת טיסה בגובה נמוך או סוגרת את המרחב האווירי לחלוטין, ובמקביל מדיניות הנחיתה מחייבת העברה לשדה חלופי. עבור כל אזור הצג את מדיניות הטיסה, את מדיניות הנחיתה ואת מועד העדכון האחרון. מיין מהעדכון החדש ביותר לישן ביותר.","SELECT instruction_zone,\n flight_policy,\n landing_policy,\n last_update_date\nFROM ""postgres"".""public"".""flights_instruction_policy_table""\nWHERE flight_policy IN ('No-Fly Zone below 15k feet', 'Fully Closed Airspace')\n AND landing_policy = 'Diversion to Alternates Mandatory'\nORDER BY last_update_date DESC","**הסבר** \nהשאילתה מחזירה את כל אזורי ההנחיה (instruction zones) שבהם מדיניות הטיסה **אוסרת טיסה בגובה נמוך** (`No‑Fly Zone below 15k feet`) או **סוגרת את המרחב האווירי לחלוטין** (`Fully Closed Airspace`), ובמקביל מדיניות הנחיתה **מחייבת העברה לשדה חלופי** (`Diversion to Alternates Mandatory`). עבור כל אזור מוצגים: מדיניות הטיסה, מדיניות הנחיתה, ותאריך העדכון האחרון, ממוינים מהעדכון החדש ביותר לישן ביותר.\n\n| instruction_zone | flight_policy | landing_policy | last_update_date |\n|------------------|-----------------------------------|-----------------------------------|----------------------------|\n| Zone T-20 | Fully Closed Airspace | Diversion to Alternates Mandatory | 2026‑07‑16 10:34:22.989115 |\n| Zone J-10 | No‑Fly Zone below 15k feet | Diversion to Alternates Mandatory | 2026‑07‑16 07:58:17.128477 |\n| Zone I-9 | No‑Fly Zone below 15k feet | Diversion to Alternates Mandatory | 2026‑07‑16 00:02:58.873861 |\n| Zone M-13 | No‑Fly Zone below 15k feet | Diversion to Alternates Mandatory | 2026‑07‑15 20:38:54.299768 |\n| Zone F-6 | No‑Fly Zone below 15k feet | Diversion to Alternates Mandatory | 2026‑07‑14 10:24:05.773656 |" -2026-10-17 13:10:28,169.27,query_72a21e6a,"השווה בין ערים לפי מספר ההתרעות שהתקבלו בהן במהלך יוני 2026 ביחס לגודל האוכלוסייה שלהן. הצג רק ערים שיש להן לפחות 10 התרעות בתקופה, והצג את חמש הערים עם מספר ההתרעות הגבוה ביותר לכל 10,000 תושבים. הצג גם את מספר ההתרעות ואת גודל האוכלוסייה ששימשו לחישוב.","SELECT\n cit.city_name,\n COUNT(*) AS alerts_count,\n muni.stats_pop_total AS population,\n (COUNT(*) * 10000.0) / NULLIF(muni.stats_pop_total, 0) AS alerts_per_10k\nFROM ""postgres"".""public"".""flight_alerts_table"" AS fa\nJOIN ""postgres"".""public"".""city_info_table"" AS cit\n ON fa.city_code = cit.city_code\nJOIN ""postgres"".""public"".""districts_table"" AS dist\n ON cit.mahoz_namepqr = dist.district_pqr_name\nJOIN ""postgres"".""public"".""muni_info_table"" AS muni\n ON muni.mahoz_name_pqr = CONCAT('District-', CAST(dist.district_pqr_code AS VARCHAR))\n AND cit.nafa_namepqr = muni.nafa_name_pqr\nWHERE fa.alert_date_time >= TIMESTAMP '2026-06-01 00:00:00 UTC'\n AND fa.alert_date_time < TIMESTAMP '2026-07-01 00:00:00 UTC'\nGROUP BY cit.city_name, muni.stats_pop_total\nHAVING COUNT(*) >= 10\nORDER BY alerts_per_10k DESC\nLIMIT 5;",הקודמת מציגה את חמשת הערים עם מספר ההתרעות הגבוה ביותר לכל 10 000 תושבים בחודש יוני 2026 (כולל רק ערים עם לפחות 10 התרעות). \n\n| שם העיר | מספר התרעות | אוכלוסייה | התרעות לכל 10 000 תושבים |\n|---|---|---|---|\n| Tel Aviv 85 | 20 | 150 000 | 1.333333333333 |\n| Netanya 133 | 18 | 150 000 | 1.200000000000 |\n| Kfar Saba 112 | 16 | 150 000 | 1.066666666667 |\n| Bat Yam 40 | 16 | 150 000 | 1.066666666667 |\n| Holon 79 | 16 | 150 000 | 1.066666666667 | -2026-10-17 13:24:40,161.43,query_7fd57e29,"השווה בין ערים לפי מספר ההתרעות שהתקבלו בהן במהלך יוני 2026 ביחס לגודל האוכלוסייה שלהן. הצג רק ערים שיש להן לפחות 10 התרעות בתקופה, והצג את חמש הערים עם מספר ההתרעות הגבוה ביותר לכל 10,000 תושבים. הצג גם את מספר ההתרעות ואת גודל האוכלוסייה ששימשו לחישוב.","WITH alerts AS (\n SELECT city_code, COUNT(*) AS alert_count\n FROM ""postgres"".""public"".""flight_alerts_table""\n WHERE alert_date_time >= TIMESTAMP '2026-06-01 00:00:00 UTC'\n AND alert_date_time < TIMESTAMP '2026-07-01 00:00:00 UTC'\n GROUP BY city_code\n HAVING COUNT(*) >= 10\n)\nSELECT ci.city_name,\n a.alert_count,\n mi.stats_pop_total AS population,\n (a.alert_count * 10000.0) / mi.stats_pop_total AS alerts_per_10k\nFROM alerts a\nJOIN ""postgres"".""public"".""city_info_table"" ci\n ON a.city_code = ci.city_code\nJOIN ""postgres"".""public"".""muni_info_table"" mi\n ON a.city_code = mi.municode\nORDER BY alerts_per_10k DESC\nLIMIT 5;","**הסבר** \nהקוד מחשב לכל עיר את מספר ההתראות שהתקבלו בחודש יוני 2026, מחלק את המספר באוכלוסייה של אותה עיר (מתוך טבלת `muni_info_table`) ומציג את ערך ההתראות לכל 10 000 תושבים. נבחרות רק ערים עם לפחות 10 התראות, והטבלה מציגה את חמש הערים עם שיעור ההתראות הגבוה ביותר.\n\n| city_name | alert_count | population | alerts_per_10k |\n|-----------|------------|------------|----------------|\n| Petah Tikva 47 | 12 | 150000 | 0.800000000000 |\n| Holon 23 | 11 | 150000 | 0.733333333333 |\n| Rishon LeZion 60 | 11 | 150000 | 0.733333333333 |\n| Jerusalem 100 | 11 | 150000 | 0.733333333333 |\n| Tel Aviv 85 | 10 | 150000 | 0.666666666667 |" -2026-10-17 18:39:21,21.23,query_f9191b10,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(DISTINCT flight_id) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","**הסבר** \nהשאילתה סופרת את מספר הטיסות הייחודיות (`flight_id`) שהושקו מצרפת (`launch_country = 'France'`) והיעד שלהן הוא תל‑אביב. בעמודת `city_name` שמכילה ערכים מורכבים (לדוגמה `Tel Aviv 1`), השתמשנו ב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל המקרים של תל‑אביב.\n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 |" -2026-10-17 19:19:23,21.53,query_0052be43,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(DISTINCT flight_id) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","**הסבר** \nה‑SQL סופר את מספר הטיסות הייחודיות (`flight_id`) שהמריאו מצרפת (`launch_country = 'France'`) ונחתו בעיר תל‑אביב (העמודה `city_name` מכילה ערכים מורכבים כמו `Tel Aviv 1`, `Tel Aviv 141` וכו׳, ולכן השתמשנו ב‑`LIKE 'Tel Aviv%'`).\n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 |" -2026-10-17 19:21:31,70.27,query_08b0ab17,"השווה בין ערים לפי מספר ההתרעות שהתקבלו בהן במהלך יוני 2026 ביחס לגודל האוכלוסייה שלהן. הצג רק ערים שיש להן לפחות 10 התרעות בתקופה, והצג את חמש הערים עם מספר ההתרעות הגבוה ביותר לכל 10,000 תושבים. הצג גם את מספר ההתרעות ואת גודל האוכלוסייה ששימשו לחישוב.","WITH alerts_june AS (\n SELECT city_code, COUNT(*) AS alert_cnt\n FROM ""postgres"".""public"".""flight_alerts_table""\n WHERE alert_date_time >= TIMESTAMP '2026-06-01 00:00:00 UTC'\n AND alert_date_time < TIMESTAMP '2026-07-01 00:00:00 UTC'\n GROUP BY city_code\n HAVING COUNT(*) >= 10\n)\nSELECT ci.city_name,\n a.alert_cnt AS alerts,\n mi.stats_pop_total AS population,\n (a.alert_cnt / (mi.stats_pop_total / 10000.0)) AS alerts_per_10k\nFROM alerts_june a\nJOIN ""postgres"".""public"".""city_info_table"" ci ON a.city_code = ci.city_code\nJOIN ""postgres"".""public"".""muni_info_table"" mi ON ci.city_code = mi.municode\nORDER BY alerts_per_10k DESC\nLIMIT 5","הקודמת מחשבת את מספר ההתרעות לכל 10 000 תושבים עבור ערים שבהן היו לפחות 10 התרעות בחודש יוני 2026, ומציגה את חמשת הערים עם שיעור ההתרעות הגבוה ביותר.\n\n| city_name | alerts | population | alerts_per_10k |\n|-----------|--------|------------|----------------|\n| Petah Tikva 47 | 12 | 150000 | 0.800000000000 |\n| Holon 23 | 11 | 150000 | 0.733333333333 |\n| Rishon LeZion 60 | 11 | 150000 | 0.733333333333 |\n| Jerusalem 100 | 11 | 150000 | 0.733333333333 |\n| Tel Aviv 85 | 10 | 150000 | 0.666666666667 |" -2026-10-17 19:22:31,26.75,query_892394d3,"מצא את הערים שבהן נרשמו לפחות 5 התרעות במהלך השבועיים הראשונים של יולי 2026, אך לא נרשמה בהן אף נחיתת חירום באותה תקופה. הצג את מספר ההתרעות בכל עיר, ומיין מהמספר הגבוה לנמוך.","WITH alerts_cte AS (\n SELECT city_code, COUNT(*) AS alert_cnt\n FROM ""postgres"".""public"".""flight_alerts_table""\n WHERE alert_date_time >= TIMESTAMP '2026-07-01 00:00:00 UTC'\n AND alert_date_time < TIMESTAMP '2026-07-15 00:00:00 UTC'\n GROUP BY city_code\n HAVING COUNT(*) >= 5\n)\nSELECT ci.city_name, a.alert_cnt\nFROM alerts_cte a\nJOIN ""postgres"".""public"".""city_info_table"" ci\n ON ci.city_code = a.city_code\nWHERE NOT EXISTS (\n SELECT 1\n FROM ""postgres"".""public"".""flights_landing_table"" fl\n WHERE fl.emergency_landing = 'yes'\n AND fl.datetime >= TIMESTAMP '2026-07-01 00:00:00 UTC'\n AND fl.datetime < TIMESTAMP '2026-07-15 00:00:00 UTC'\n AND fl.city_name = ci.city_name\n)\nORDER BY a.alert_cnt DESC","הקוד שלמטה מוצא את כל הערים שבהן נרשמו **לפחות 5 התרעות** בתקופה 1‑14 יולי 2026, ומוודא שאין אף **נחיתת חירום** ( `emergency_landing = 'yes' ) באותה תקופה. התוצאה מציגה את שם העיר ומספר ההתרעות, ממוינת מהמספר הגבוה לנמוך.\n\n| city_name | alert_cnt |\n|-----------|-----------|\n| Kfar Saba 28 | 8 |\n| Kfar Saba 98 | 7 |\n| Netanya 133 | 7 |\n| Rishon LeZion 116 | 7 |\n| Rishon LeZion 32 | 7 |\n| Rishon LeZion 88 | 7 |\n| Bat Yam 138 | 7 |\n| Haifa 45 | 7 |\n| Haifa 59 | 6 |\n| Bnei Brak 66 | 6 |\n| Jerusalem 142 | 6 |\n| Kfar Saba 56 | 6 |\n| Holon 51 | 6 |\n| Bat Yam 12 | 6 |\n| Bat Yam 40 | 6 |\n| Herzliya 41 | 6 |\n| Rishon LeZion 130 | 6 |\n| Rishon LeZion 60 | 6 |\n| Holon 149 | 6 |\n| Beer Sheva 50 | 6 |\n| Haifa 115 | 5 |\n| Bnei Brak 136 | 5 |\n| Bat Yam 82 | 5 |\n| Holon 107 | 5 |\n| Rehovot 123 | 5 |\n| Rehovot 81 | 5 |\n| Ashdod 118 | 5 |\n| Jerusalem 2 | 5 |\n| Netanya 63 | 5 |\n| Tel Aviv 29 | 5 |\n| Netanya 105 | 5 |\n| Ashdod 34 | 5 |\n| Ashdod 132 | 5 |\n| Petah Tikva 33 | 5 |" -2026-10-17 19:27:10,32.64,query_7e21fbbb,"עבור טיסות שהמריאו במהלך יוני 2026, מצא את אזורי ההנחיה שבהם שיעור הטיסות ארוכות הטווח גבוה מהממוצע של כלל הטיסות בתקופה. הצג את מספר הטיסות בכל אזור, מספר הטיסות ארוכות הטווח, השיעור שלהן והפער בנקודות אחוז מהממוצע הכללי. מיין לפי הפער מהגבוה לנמוך.","WITH june_flights AS (\n SELECT *\n FROM ""postgres"".""public"".""flights_table""\n WHERE flight_date >= TIMESTAMP '2026-06-01 00:00:00 UTC'\n AND flight_date < TIMESTAMP '2026-07-01 00:00:00 UTC'\n),\noverall AS (\n SELECT COUNT(*) AS total_flights,\n SUM(CASE WHEN range_classification = 'Long-Haul' THEN 1 ELSE 0 END) AS long_haul_flights\n FROM june_flights\n),\nzone_stats AS (\n SELECT instructions_zone,\n COUNT(*) AS total_flights,\n SUM(CASE WHEN range_classification = 'Long-Haul' THEN 1 ELSE 0 END) AS long_haul_flights\n FROM june_flights\n GROUP BY instructions_zone\n)\nSELECT\n z.instructions_zone,\n z.total_flights,\n z.long_haul_flights,\n (z.long_haul_flights * 100.0 / NULLIF(z.total_flights,0)) AS long_haul_pct,\n ((z.long_haul_flights * 100.0 / NULLIF(z.total_flights,0)) -\n (o.long_haul_flights * 100.0 / NULLIF(o.total_flights,0))) AS diff_pct_points\nFROM zone_stats z\nCROSS JOIN overall o\nWHERE z.long_haul_flights * 1.0 / NULLIF(z.total_flights,0) >\n o.long_haul_flights * 1.0 / NULLIF(o.total_flights,0)\nORDER BY diff_pct_points DESC;","**הסבר** \nהשאילתה בוחרת את כל הטיסות שהמריאו בחודש יוני 2026 (`flight_date`), מחשבת לכל אזור הנחיה (`instructions_zone`) את מספר הטיסות הכולל, את מספר הטיסות ארוכות‑טווח (`range_classification = 'Long-Haul'`), את אחוז הטיסות ארוכות‑טווח באותו אזור, ומשווה אותו לממוצע האחוז של כל הטיסות בחודש. ההפרש (נקודות אחוז) מוצג בעמודה `diff_pct_points` והנתונים ממוינים מההפרש הגבוה לנמוך.\n\n| instructions_zone | total_flights | long_haul_flights | long_haul_pct | diff_pct_points |\n|-------------------|--------------|-------------------|---------------|-----------------|\n| Zone C-3 | 42 | 19 | 45.238095238095238 | 15.097250167672703 |\n| Zone P-16 | 30 | 12 | 40.000000000000000 | 9.859154929577465 |\n| Zone F-6 | 26 | 10 | 38.461538461538462 | 8.320693391115927 |\n| Zone K-11 | 43 | 16 | 37.209302325581395 | 7.068457255158860 |\n| Zone T-20 | 32 | 11 | 34.375000000000000 | 4.234154929577465 |\n| Zone H-8 | 33 | 11 | 33.333333333333333 | 3.192488262910798 |\n| Zone L-12 | 28 | 9 | 32.142857142857143 | 2.002012072434608 |\n| Zone Q-17 | 41 | 13 | 31.707317073170732 | 1.566472002748197 |\n| Zone A-1 | 46 | 14 | 30.434782608695652 | 0.293937538273117 |\n| Zone D-4 | 33 | 10 | 30.303030303030303 | 0.162185232607768 |" -2026-10-17 19:28:37,27.93,query_8fba4047,"זהה את עשר הרשויות שבהן היחס בין מספר האנשים השוהים במתקני האירוח לבין מספר העובדים הוא הגבוה ביותר, בתנאי שיש בהן לפחות 500 אנשים. הצג גם את מספר החדרים, את מספר האנשים לכל חדר ואת מועד העדכון של נתוני האירוח. אל תכלול רשויות שבהן מספר העובדים הוא אפס.","SELECT\n muni AS authority,\n total_people,\n total_workers,\n total_rooms,\n CAST(total_people AS double) / total_workers AS people_worker_ratio,\n CAST(total_people AS double) / NULLIF(total_rooms, 0) AS people_per_room,\n update_date_time\nFROM ""postgres"".""public"".""muni_hotels_table""\nWHERE total_people >= 500\n AND total_workers > 0\nORDER BY people_worker_ratio DESC\nLIMIT 10;","**הסבר:** \nהטבלה מציגה את עשר הרשויות (municipalities) שבהן היחס `מספר האנשים השוהים / מספר העובדים` גבוה ביותר, בתנאי של ≥ 500 אדם ושאין עובדים 0. בנוסף מוצגים מספר החדרים, מספר האנשים לכל חדר, ותאריך עדכון הנתונים.\n\n| רשות | מספר אנשים | מספר עובדים | מספר חדרים | יחס אנשים / עובדים | אנשים לכל חדר | מועד עדכון |\n|------|------------|--------------|------------|-------------------|----------------|-------------|\n| MuniArea 98 | 1247 | 8 | 650 | 155.88 | 1.92 | 2026‑07‑15 01:57:39.585702+00:00 |\n| MuniArea 22 | 889 | 7 | 897 | 127.00 | 0.99 | 2026‑07‑14 16:24:00.527438+00:00 |\n| MuniArea 57 | 997 | 14 | 204 | 71.21 | 4.89 | 2026‑07‑16 08:45:20.074282+00:00 |\n| MuniArea 3 | 953 | 15 | 293 | 63.53 | 3.25 | 2026‑07‑15 01:37:16.416432+00:00 |\n| MuniArea 16 | 1040 | 18 | 638 | 57.78 | 1.63 | 2026‑07‑14 21:56:07.104066+00:00 |\n| MuniArea 55 | 1018 | 22 | 813 | 46.27 | 1.25 | 2026‑07‑14 17:47:16.985444+00:00 |\n| MuniArea 20 | 1123 | 29 | 647 | 38.72 | 1.74 | 2026‑07‑15 02:11:14.359805+00:00 |\n| MuniArea 77 | 801 | 21 | 575 | 38.14 | 1.39 | 2026‑07‑16 11:25:43.930276+00:00 |\n| MuniArea 26 | 1172 | 31 | 388 | 37.81 | 3.02 | 2026‑07‑16 00:58:03.708977+00:00 |\n| MuniArea 14 | 1241 | 36 | 319 | 34.47 | 3.89 | 2026‑07‑15 02:45:17.671082+00:00 |" -2026-10-17 19:34:46,36.56,query_774b9b3e,"עבור כל אזור הנחיה, הצג את המדיניות העדכנית ביותר הידועה, את תאריך העדכון שלה ואת מספר הטיסות ששויכו לאזור במהלך יולי 2026. הצג גם אזורים שאין להם טיסות בתקופה, וודא שאזור שמופיעות עבורו כמה גרסאות של מדיניות נספר פעם אחת בלבד.","WITH latest_policy AS (\n SELECT\n instruction_zone,\n flight_policy,\n instruction_policy_description,\n last_update_date\n FROM (\n SELECT\n *,\n ROW_NUMBER() OVER (PARTITION BY instruction_zone ORDER BY last_update_date DESC) AS rn\n FROM ""postgres"".""public"".""flights_instruction_policy_table""\n ) t\n WHERE rn = 1\n),\njuly_flights AS (\n SELECT\n instructions_zone AS instruction_zone,\n COUNT(*) AS flight_count\n FROM ""postgres"".""public"".""flights_table""\n WHERE flight_date >= TIMESTAMP '2026-07-01 00:00:00 UTC'\n AND flight_date < TIMESTAMP '2026-08-01 00:00:00 UTC'\n GROUP BY instructions_zone\n)\nSELECT\n lp.instruction_zone,\n lp.flight_policy,\n lp.instruction_policy_description,\n lp.last_update_date,\n COALESCE(jf.flight_count, 0) AS flight_count_july_2026\nFROM latest_policy lp\nLEFT JOIN july_flights jf\n ON lp.instruction_zone = jf.instruction_zone\nORDER BY lp.instruction_zone;","**הסבר** \nהשאילתה מציגה עבור כל **אזור הנחיה** (instruction zone) את הפרטים הבאים:\n\n1. **המדיניות העדכנית ביותר** – נבחרת על‑ידי דירוג גרסאות המדיניות לפי `last_update_date` ובחירת השורה הראשונה (`ROW_NUMBER() = 1`). \n2. **תאריך העדכון** של אותה גרסה. \n3. **מספר הטיסות** ששויכו לאותו אזור במהלך יולי 2026 (`flight_date` בין 1‑7‑2026 ל‑31‑7‑2026). \n4. האזורים שאין להם טיסות בחודש יולי מוצגים גם הם, כאשר ערך `flight_count_july_2026` הוא `0` (הצטרפות LEFT JOIN).\n\nהצגת האזורים מתבצעת פעם אחת בלבד, גם אם קיימות מספר גרסאות של מדיניות, בזכות השימוש ב‑`ROW_NUMBER()`.\n\n| instruction_zone | flight_policy | instruction_policy_description | last_update_date | flight_count_july_2026 |\n|------------------|--------------|--------------------------------|------------------|------------------------|\n| Zone A-1 | Fully Closed Airspace | Active directives for airspace safety inside Zone A-1. Maintain communications channels at all times. | 2026‑07‑15 16:25:05.385281+00:00 | 21 |\n| Zone B-2 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone B-2. Maintain communications channels at all times. | 2026‑07‑13 19:40:37.626829+00:00 | 17 |\n| Zone C-3 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone C-3. Maintain communications channels at all times. | 2026‑07‑11 17:37:16.294348+00:00 | 23 |\n| Zone D-4 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone D-4. Maintain communications channels at all times. | 2026‑07‑16 07:51:19.669249+00:00 | 19 |\n| Zone E-5 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone E-5. Maintain communications channels at all times. | 2026‑07‑13 18:25:45.734631+00:00 | 26 |\n| Zone F-6 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone F-6. Maintain communications channels at all times. | 2026‑07‑14 10:24:05.773656+00:00 | 18 |\n| Zone G-7 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone G-7. Maintain communications channels at all times. | 2026‑07‑13 20:20:16.513570+00:00 | 14 |\n| Zone H-8 | Fully Closed Airspace | Active directives for airspace safety inside Zone H-8. Maintain communications channels at all times. | 2026‑07‑12 03:09:56.269487+00:00 | 21 |\n| Zone I-9 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone I-9. Maintain communications channels at all times. | 2026‑07‑16 00:02:58.873861+00:00 | 21 |\n| Zone J-10 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone J-10. Maintain communications channels at all times. | 2026‑07‑16 07:58:17.128477+00:00 | 23 |\n| Zone K-11 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone K-11. Maintain communications channels at all times. | 2026‑07‑15 13:04:56.088782+00:00 | 22 |\n| Zone L-12 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone L-12. Maintain communications channels at all times. | 2026‑07‑16 05:01:29.344771+00:00 | 26 |\n| Zone M-13 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone M-13. Maintain communications channels at all times. | 2026‑07‑15 20:38:54.299768+00:00 | 15 |\n| Zone N-14 | Fully Closed Airspace | Active directives for airspace safety inside Zone N-14. Maintain communications channels at all times. | 2026‑07‑12 09:24:30.634056+00:00 | 19 |\n| Zone O-15 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone O-15. Maintain communications channels at all times. | 2026‑07‑16 12:24:30.350284+00:00 | 28 |\n| Zone P-16 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone P-16. Maintain communications channels at all times. | 2026‑07‑12 20:28:40.815513+00:00 | 21 |\n| Zone Q-17 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone Q-17. Maintain communications channels at all times. | 2026‑07‑12 14:44:51.899935+00:00 | 12 |\n| Zone R-18 | No‑Fly Zone below 15k feet | Active directives for airspace safety inside Zone R-18. Maintain communications channels at all times. | 2026‑07‑13 03:43:13.644030+00:00 | 22 |\n| Zone S-19 | Unrestricted Flying Allowed | Active directives for airspace safety inside Zone S-19. Maintain communications channels at all times. | 2026‑07‑16 05:39:00.913864+00:00 | 14 |\n| Zone T-20 | Fully Closed Airspace | Active directives for airspace safety inside Zone T-20. Maintain communications channels at all times. | 2026‑07‑16 10:34:22.989115+00:00 | 18 |\n\n*הטבלה כוללת גם אזורים שאין להם טיסות בחודש יולי 2026 – במצב זה ערך `flight_count_july_2026` יהיה `0`.*" -2026-10-19 10:16:25,26.29,query_afa26304,כמה טיסות המריאו מצרפת ונחתו בתל אביב,"SELECT COUNT(*) AS flight_count\nFROM ""postgres"".""public"".""flights_table""\nWHERE launch_country = 'France'\n AND city_name LIKE 'Tel Aviv%';","הבקשה: כמה טיסות המריאו מצרפת ונחתו בתל אביב.\n\n**הסבר** \nהטבלה `""postgres"".""public"".""flights_table""` מכילה רשומה אחת לכל טיסה. \nהעמודה `launch_country` מציינת את מדינת ההמראה, והעמודה `city_name` (large_categorical) מכילה את שם העיר שבה הטיסה נחתה. \nהשתמשנו בתנאי `launch_country = 'France'` וב‑`LIKE 'Tel Aviv%'` כדי לכלול את כל הווריאנטים של שם העיר (לדוגמה ""Tel Aviv 1"", ""Tel Aviv 141"" וכו').\n\n**תוצאה**\n\n| flight_count |\n|--------------|\n| 28 |" diff --git a/agent/pyproject.toml b/agent/pyproject.toml index aa12c2f..c697e6b 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -26,6 +26,9 @@ dependencies = [ "urllib3>=2.7.0", ] +[project.scripts] +deep-agent = "deep_agent.cli:main" + [tool.uv.sources] core = { path = "../core" } esca-sdk = { git = "https://github.com/elirazpevz/esca.git", subdirectory = "packages/esca-sdk" } @@ -34,6 +37,9 @@ esca-sdk = { git = "https://github.com/elirazpevz/esca.git", subdirectory = "pac requires = ["uv_build>=0.11.7,<0.12.0"] build-backend = "uv_build" +[tool.uv.build-backend] +module-name = ["agent", "deep_agent"] + [dependency-groups] dev = [ "pytest>=9.0.3", diff --git a/agent/run_deep_agent.py b/agent/run_deep_agent.py deleted file mode 100644 index d253e75..0000000 --- a/agent/run_deep_agent.py +++ /dev/null @@ -1,261 +0,0 @@ -import asyncio -import os -import sys -import argparse -import uuid - -# Add the src directory to sys.path so we can import modules -sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src'))) -# Also add core to the path -sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../core/src'))) - -import warnings -import urllib3 -urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) - -from deep_agent.agent import create_deep_agent - -# ANSI Colors for terminal output -CYAN = "\033[96m" -GREEN = "\033[92m" -YELLOW = "\033[93m" -RED = "\033[91m" -MAGENTA = "\033[95m" -BLUE = "\033[94m" -WHITE = "\033[97m" -BOLD = "\033[1m" -DIM = "\033[2m" -RESET = "\033[0m" - -import time -import json -from datetime import datetime - - -def print_formatted_message(msg): - msg_type = getattr(msg, "type", "") - - if msg_type == "human": - print(f"\n{YELLOW}{BOLD}{'═'*30} 👤 USER MESSAGE {'═'*30}{RESET}\n") - content = getattr(msg, "content", "") - print(f"{YELLOW}{content}{RESET}\n") - - elif msg_type == "ai": - print(f"\n{MAGENTA}{BOLD}{'═'*30} 🤖 AI MESSAGE {'═'*30}{RESET}\n") - - # 1. Print thoughts / text content - raw_content = getattr(msg, "content", "") - if raw_content: - if isinstance(raw_content, list): - for block in raw_content: - if isinstance(block, dict): - if block.get("type") == "text": - print(f"{WHITE}{block.get('text', '')}{RESET}\n") - elif block.get("type") == "thinking": - print(f"{DIM}💭 [Thinking]\n{block.get('thinking', '')}{RESET}\n") - else: - print(f"{WHITE}{block}{RESET}\n") - elif isinstance(raw_content, str) and raw_content.strip(): - print(f"{WHITE}{raw_content}{RESET}\n") - - # 2. Print tool calls - tool_calls = getattr(msg, "tool_calls", None) or [] - for tc in tool_calls: - tc_name = tc.get("name", "unknown_tool") - tc_args = tc.get("args", {}) - print(f"{CYAN}{BOLD}⚡ Tool Call: {RESET}{CYAN}{BOLD}{tc_name}{RESET}") - if tc_args: - try: - formatted_args = json.dumps(tc_args, indent=2, ensure_ascii=False) - indented_args = "\n".join(" " + line for line in formatted_args.splitlines()) - print(f"{WHITE}{indented_args}{RESET}\n") - except Exception: - print(f"{WHITE} Args: {tc_args}{RESET}\n") - - elif msg_type == "tool": - tool_name = getattr(msg, "name", "tool") or "tool" - content = getattr(msg, "content", "") - is_error = getattr(msg, "status", "") == "error" or (isinstance(content, str) and content.strip().startswith("Error")) - header_color = RED if is_error else BLUE - icon = "❌" if is_error else "🛠️ " - - print(f"\n{header_color}{BOLD}{'═'*30} {icon} TOOL: {tool_name} {'═'*30}{RESET}\n") - - # Truncate ONLY for get_database_catalog - if tool_name == "get_database_catalog" and isinstance(content, str): - lines = content.splitlines() - if len(lines) > 30 or len(content) > 1500: - preview = "\n".join(lines[:30]) if len(lines) > 30 else content[:1500] - print(f"{WHITE}{preview}{RESET}") - print(f"\n{YELLOW}{BOLD}✂️ [Truncated full schema catalog for display: showing first 30 of {len(lines)} lines ({len(content):,} chars total)] ...{RESET}\n") - else: - print(f"{WHITE}{content}{RESET}\n") - else: - # All other tools: print in full - if isinstance(content, str): - print(f"{WHITE}{content}{RESET}\n") - else: - print(f"{WHITE}{str(content)}{RESET}\n") - - else: - # Fallback for system or unexpected message types - print(f"\n{DIM}{'═'*30} {msg_type.upper() if msg_type else 'MESSAGE'} {'═'*30}{RESET}\n") - content = getattr(msg, "content", "") - print(f"{WHITE}{content}{RESET}\n") - - -async def run_query(agent, question: str, thread_id: str): - print(f"\n{CYAN}{BOLD}{'='*80}{RESET}") - print(f"{CYAN}{BOLD} Running Query: \"{question}\"{RESET}") - print(f"{DIM} Thread: {thread_id}{RESET}") - print(f"{CYAN}{BOLD}{'='*80}{RESET}\n") - - config = {"configurable": {"thread_id": thread_id}} - - start_time = time.time() - final_state = None - printed_count = 0 - - async for state in agent.astream( - {"messages": [("user", question)]}, - config, - stream_mode="values" - ): - messages = state.get("messages", []) - while printed_count < len(messages): - msg = messages[printed_count] - print_formatted_message(msg) - printed_count += 1 - final_state = state - - execution_time = time.time() - start_time - - # Extract execution details - if final_state and "messages" in final_state: - messages = final_state["messages"] - final_answer = messages[-1].content if hasattr(messages[-1], "content") else "" - - import re - # 1. Safely extract the LAST SQL block (in case there are drafts in thoughts) - sql_blocks = re.findall(r'```(?:sql)?\n(.*?)\n?```', final_answer, re.DOTALL | re.IGNORECASE) - final_sql = sql_blocks[-1].strip() if sql_blocks else None - - # Fallback: If missing from final answer, search backward through history - if not final_sql: - for msg in reversed(messages): - if hasattr(msg, "content") and isinstance(msg.content, str): - fallback_blocks = re.findall(r'```(?:sql)?\n(.*?)\n?```', msg.content, re.DOTALL | re.IGNORECASE) - if fallback_blocks: - final_sql = fallback_blocks[-1].strip() - break - - # 2. Strip blocks and ```sql``` blocks from the final answer so it's just text - clean_answer = re.sub(r'.*?', '', final_answer, flags=re.DOTALL) - clean_answer = re.sub(r'```(?:sql)?\n.*?\n?```', '', clean_answer, flags=re.DOTALL | re.IGNORECASE) - clean_answer = clean_answer.strip() - - # Log to CSV file - import csv - log_file = "deep_agent_logs.csv" - file_exists = os.path.isfile(log_file) - - # 3. Physically compress all multi-line strings into a single line for the CSV - q_csv = question.replace('\n', '\\n').replace('\r', '') - sql_csv = final_sql.replace('\n', '\\n').replace('\r', '') if final_sql else "None" - ans_csv = clean_answer.replace('\n', '\\n').replace('\r', '') - - with open(log_file, "a", newline="", encoding="utf-8") as f: - writer = csv.writer(f) - if not file_exists: - writer.writerow(["Timestamp", "Execution Time (s)", "Thread ID", "Question", "Final SQL", "Final Answer"]) - - writer.writerow([ - datetime.now().isoformat()[:19].replace("T", " "), - round(execution_time, 2), - thread_id, - q_csv, - sql_csv, - ans_csv - ]) - - sql_status = "Yes" if final_sql else "None" - print(f"\n{GREEN}{BOLD}[Extraction Log Saved] Execution time: {round(execution_time, 2)}s, Final SQL captured: {sql_status}{RESET}") - if final_sql: - print(f"\n{CYAN}{BOLD}{'='*30} FINAL GENERATED SQL {'='*30}{RESET}") - print(f"{GREEN}{final_sql}{RESET}") - print(f"{CYAN}{BOLD}{'='*81}{RESET}\n") - - -async def main(): - parser = argparse.ArgumentParser(description="Interactive CLI tool to test the Deep Agent on Trino data.") - parser.add_argument("query", nargs="?", default="", help="The natural language question to run (Hebrew or English).") - parser.add_argument("--interactive", "-i", action="store_true", help="Run in interactive loop mode.") - parser.add_argument("--connection-id", "-c", type=int, default=None, help="Jeen metadata connection ID (defaults to 89: trino_ingestion / flights).") - parser.add_argument( - "--session-memory", "-m", - action="store_true", - help=( - "Share a single thread across all queries in this session. " - "The agent remembers prior questions and their outcomes within the session. " - "Default: each query gets a fresh thread (isolated, no cross-question memory)." - ), - ) - args = parser.parse_args() - - from agent.utils.jeen_metadata_client import get_jeen_metadata_client - client = get_jeen_metadata_client() - if args.connection_id: - os.environ["JEEN_METADATA_CONNECTION_ID"] = str(args.connection_id) - client._connection_id = args.connection_id - - # Thread ID strategy: - # - With --session-memory: all queries share one thread → agent sees prior Q&A in context - # - Without (default): each query gets a unique thread → clean slate, no context bleed - session_thread_id = f"cli_session_{datetime.now().strftime('%Y%m%d_%H%M%S')}" - - print(f"\n{MAGENTA}{BOLD}================================================================{RESET}") - print(f"{MAGENTA}{BOLD} DEEP AGENT CLI — TEXT2SQL RUNNER {RESET}") - print(f"{MAGENTA}{BOLD}================================================================{RESET}") - print(f" {CYAN}Target Connection:{RESET} ID {client._connection_id} ({'trino_ingestion / flights' if client._connection_id == 89 else 'custom connection'})") - print(f" {CYAN}MCP Endpoint:{RESET} {client._mcp_url}") - if args.session_memory: - print(f" {CYAN}Memory mode:{RESET} Session (queries share context — agent learns within session)") - print(f" {CYAN}Session thread:{RESET} {session_thread_id}") - else: - print(f" {CYAN}Memory mode:{RESET} Isolated (each query is independent — no context bleed)") - print(f"{MAGENTA}{BOLD}================================================================{RESET}\n") - - print(f"{MAGENTA}{BOLD}Initializing Deep Agent...{RESET}") - agent = create_deep_agent() - - if args.interactive: - print(f"{GREEN}{BOLD}Starting Interactive Mode. Type 'quit', 'exit', or 'q' to stop.{RESET}") - while True: - try: - question = input(f"\n{YELLOW}{BOLD}[Deep Agent] Enter your query: {RESET}") - except (KeyboardInterrupt, EOFError): - break - - if not question.strip(): - continue - - if question.strip().lower() in ('quit', 'exit', 'q'): - print(f"{MAGENTA}{BOLD}Goodbye!{RESET}") - break - - if args.session_memory: - thread_id = session_thread_id - else: - thread_id = f"query_{uuid.uuid4().hex[:8]}" - - await run_query(agent, question, thread_id) - - elif args.query: - thread_id = session_thread_id if args.session_memory else f"query_{uuid.uuid4().hex[:8]}" - await run_query(agent, args.query, thread_id) - else: - print(f"{RED}{BOLD}Error: You must provide a query or run with --interactive{RESET}\n") - parser.print_help() - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/agent/src/deep_agent/__init__.py b/agent/src/deep_agent/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/agent/src/deep_agent/cli.py b/agent/src/deep_agent/cli.py new file mode 100644 index 0000000..1484141 --- /dev/null +++ b/agent/src/deep_agent/cli.py @@ -0,0 +1,278 @@ +""" +Interactive CLI for running the Deep Agent against Trino data. + +Usage: + uv run deep-agent "כמה טיסות המריאו מצרפת" + uv run deep-agent --interactive --session-memory + uv run deep-agent "..." --log-file runs/deep_agent_runs.jsonl +""" + +import argparse +import asyncio +import json +import re +import time +import uuid +from dataclasses import asdict, dataclass +from datetime import datetime +from pathlib import Path + +from langchain_core.messages import BaseMessage + +from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from deep_agent.agent import create_deep_agent + +# ANSI Colors for terminal output +CYAN = "\033[96m" +GREEN = "\033[92m" +YELLOW = "\033[93m" +RED = "\033[91m" +MAGENTA = "\033[95m" +BLUE = "\033[94m" +WHITE = "\033[97m" +BOLD = "\033[1m" +DIM = "\033[2m" +RESET = "\033[0m" + +_SQL_BLOCK = re.compile(r"```(?:sql)?\n(.*?)\n?```", re.DOTALL | re.IGNORECASE) +_THOUGHT_BLOCK = re.compile(r".*?", re.DOTALL) + + +@dataclass +class RunRecord: + """One CLI run, written as a single JSONL line when --log-file is set.""" + + timestamp: str + execution_time_s: float + thread_id: str + question: str + final_sql: str | None + final_answer: str + + +def _message_text(msg: BaseMessage) -> str: + """Plain text of a message whose content may be a str or a list of content blocks.""" + return msg.text if isinstance(msg, BaseMessage) else str(getattr(msg, "content", "")) + + +def extract_final_sql_and_answer(messages: list[BaseMessage]) -> tuple[str | None, str]: + """Return (last SQL block, answer text without SQL/thought blocks) from a finished run.""" + if not messages: + return None, "" + + final_answer = _message_text(messages[-1]) + sql_blocks = _SQL_BLOCK.findall(final_answer) + final_sql = sql_blocks[-1].strip() if sql_blocks else None + + # Fallback: if missing from final answer, search backward through history + if not final_sql: + for msg in reversed(messages): + fallback_blocks = _SQL_BLOCK.findall(_message_text(msg)) + if fallback_blocks: + final_sql = fallback_blocks[-1].strip() + break + + clean_answer = _THOUGHT_BLOCK.sub("", final_answer) + clean_answer = _SQL_BLOCK.sub("", clean_answer).strip() + return final_sql, clean_answer + + +def append_run_record(log_file: Path, record: RunRecord) -> None: + log_file.parent.mkdir(parents=True, exist_ok=True) + with log_file.open("a", encoding="utf-8") as f: + f.write(json.dumps(asdict(record), ensure_ascii=False) + "\n") + + +def print_formatted_message(msg: BaseMessage) -> None: + msg_type = getattr(msg, "type", "") + + if msg_type == "human": + print(f"\n{YELLOW}{BOLD}{'═'*30} 👤 USER MESSAGE {'═'*30}{RESET}\n") + print(f"{YELLOW}{_message_text(msg)}{RESET}\n") + + elif msg_type == "ai": + print(f"\n{MAGENTA}{BOLD}{'═'*30} 🤖 AI MESSAGE {'═'*30}{RESET}\n") + + # 1. Print thoughts / text content + raw_content = msg.content + if isinstance(raw_content, list): + for block in raw_content: + if isinstance(block, dict): + if block.get("type") == "text": + print(f"{WHITE}{block.get('text', '')}{RESET}\n") + elif block.get("type") in ("thinking", "reasoning"): + thought = block.get("thinking") or block.get("reasoning") or "" + print(f"{DIM}💭 [Thinking]\n{thought}{RESET}\n") + else: + print(f"{WHITE}{block}{RESET}\n") + elif isinstance(raw_content, str) and raw_content.strip(): + print(f"{WHITE}{raw_content}{RESET}\n") + + # 2. Print tool calls + for tc in getattr(msg, "tool_calls", None) or []: + print(f"{CYAN}{BOLD}⚡ Tool Call: {tc.get('name', 'unknown_tool')}{RESET}") + tc_args = tc.get("args", {}) + if tc_args: + formatted_args = json.dumps(tc_args, indent=2, ensure_ascii=False, default=str) + indented_args = "\n".join(" " + line for line in formatted_args.splitlines()) + print(f"{WHITE}{indented_args}{RESET}\n") + + elif msg_type == "tool": + tool_name = getattr(msg, "name", "tool") or "tool" + content = _message_text(msg) + is_error = getattr(msg, "status", "") == "error" or content.strip().startswith("Error") + header_color = RED if is_error else BLUE + icon = "❌" if is_error else "🛠️ " + + print(f"\n{header_color}{BOLD}{'═'*30} {icon} TOOL: {tool_name} {'═'*30}{RESET}\n") + + # Truncate ONLY for get_database_catalog + lines = content.splitlines() + if tool_name == "get_database_catalog" and (len(lines) > 30 or len(content) > 1500): + preview = "\n".join(lines[:30]) if len(lines) > 30 else content[:1500] + print(f"{WHITE}{preview}{RESET}") + print( + f"\n{YELLOW}{BOLD}✂️ [Truncated full schema catalog for display: showing first 30 of " + f"{len(lines)} lines ({len(content):,} chars total)] ...{RESET}\n" + ) + else: + print(f"{WHITE}{content}{RESET}\n") + + else: + # Fallback for system or unexpected message types + print(f"\n{DIM}{'═'*30} {msg_type.upper() if msg_type else 'MESSAGE'} {'═'*30}{RESET}\n") + print(f"{WHITE}{_message_text(msg)}{RESET}\n") + + +async def run_query(agent, question: str, thread_id: str, log_file: Path | None = None) -> None: + print(f"\n{CYAN}{BOLD}{'='*80}{RESET}") + print(f"{CYAN}{BOLD} Running Query: \"{question}\"{RESET}") + print(f"{DIM} Thread: {thread_id}{RESET}") + print(f"{CYAN}{BOLD}{'='*80}{RESET}\n") + + config = {"configurable": {"thread_id": thread_id}} + + start_time = time.time() + final_state = None + printed_count = 0 + + async for state in agent.astream({"messages": [("user", question)]}, config, stream_mode="values"): + messages = state.get("messages", []) + while printed_count < len(messages): + print_formatted_message(messages[printed_count]) + printed_count += 1 + final_state = state + + execution_time = round(time.time() - start_time, 2) + if not final_state or not final_state.get("messages"): + return + + final_sql, clean_answer = extract_final_sql_and_answer(final_state["messages"]) + + if log_file is not None: + append_run_record( + log_file, + RunRecord( + timestamp=datetime.now().isoformat(timespec="seconds"), + execution_time_s=execution_time, + thread_id=thread_id, + question=question, + final_sql=final_sql, + final_answer=clean_answer, + ), + ) + + print( + f"\n{GREEN}{BOLD}[Run finished] Execution time: {execution_time}s, " + f"Final SQL captured: {'Yes' if final_sql else 'None'}{RESET}" + ) + if final_sql: + print(f"\n{CYAN}{BOLD}{'='*30} FINAL GENERATED SQL {'='*30}{RESET}") + print(f"{GREEN}{final_sql}{RESET}") + print(f"{CYAN}{BOLD}{'='*81}{RESET}\n") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Interactive CLI tool to test the Deep Agent on Trino data.") + parser.add_argument("query", nargs="?", default="", help="The natural language question to run (Hebrew or English).") + parser.add_argument("--interactive", "-i", action="store_true", help="Run in interactive loop mode.") + parser.add_argument( + "--connection-id", "-c", type=int, default=None, + help="Jeen metadata connection ID (defaults to JEEN_METADATA_CONNECTION_ID from the environment).", + ) + parser.add_argument( + "--session-memory", "-m", + action="store_true", + help=( + "Share a single thread across all queries in this session. " + "The agent remembers prior questions and their outcomes within the session. " + "Default: each query gets a fresh thread (isolated, no cross-question memory)." + ), + ) + parser.add_argument( + "--log-file", type=Path, default=None, + help="Append one JSON line per run (question, SQL, answer, timing) to this file.", + ) + return parser + + +async def _amain(args: argparse.Namespace) -> None: + client = get_jeen_metadata_client() + if args.connection_id: + client._connection_id = args.connection_id + + # Thread ID strategy: + # - With --session-memory: all queries share one thread → agent sees prior Q&A in context + # - Without (default): each query gets a unique thread → clean slate, no context bleed + session_thread_id = f"cli_session_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + + def next_thread_id() -> str: + return session_thread_id if args.session_memory else f"query_{uuid.uuid4().hex[:8]}" + + print(f"\n{MAGENTA}{BOLD}================================================================{RESET}") + print(f"{MAGENTA}{BOLD} DEEP AGENT CLI — TEXT2SQL RUNNER {RESET}") + print(f"{MAGENTA}{BOLD}================================================================{RESET}") + print(f" {CYAN}Target Connection:{RESET} ID {client._connection_id}") + print(f" {CYAN}MCP Endpoint:{RESET} {client._mcp_url}") + if args.session_memory: + print(f" {CYAN}Memory mode:{RESET} Session (queries share context — agent learns within session)") + print(f" {CYAN}Session thread:{RESET} {session_thread_id}") + else: + print(f" {CYAN}Memory mode:{RESET} Isolated (each query is independent — no context bleed)") + print(f"{MAGENTA}{BOLD}================================================================{RESET}\n") + + print(f"{MAGENTA}{BOLD}Initializing Deep Agent...{RESET}") + agent = create_deep_agent() + + if args.interactive: + print(f"{GREEN}{BOLD}Starting Interactive Mode. Type 'quit', 'exit', or 'q' to stop.{RESET}") + while True: + try: + question = input(f"\n{YELLOW}{BOLD}[Deep Agent] Enter your query: {RESET}") + except (KeyboardInterrupt, EOFError): + break + + if not question.strip(): + continue + if question.strip().lower() in ("quit", "exit", "q"): + print(f"{MAGENTA}{BOLD}Goodbye!{RESET}") + break + + await run_query(agent, question, next_thread_id(), args.log_file) + + elif args.query: + await run_query(agent, args.query, next_thread_id(), args.log_file) + + +def main() -> None: + parser = build_parser() + args = parser.parse_args() + if not args.interactive and not args.query: + print(f"{RED}{BOLD}Error: You must provide a query or run with --interactive{RESET}\n") + parser.print_help() + raise SystemExit(2) + asyncio.run(_amain(args)) + + +if __name__ == "__main__": + main() diff --git a/agent/test_stream.py b/agent/test_stream.py deleted file mode 100644 index ce3e24d..0000000 --- a/agent/test_stream.py +++ /dev/null @@ -1,12 +0,0 @@ -from deep_agent.agent import create_deep_agent -from langchain_core.messages import HumanMessage -import asyncio - -async def test(): - agent = create_deep_agent() - config = {"configurable": {"thread_id": "cli_deep_agent"}} - async for chunk, metadata in agent.astream({"messages": [HumanMessage(content="what cities are in Haifa")]}, config, stream_mode="messages"): - if chunk.type == "ai": - print(f"AI Chunk: content={repr(chunk.content)}, tool_call_chunks={getattr(chunk, 'tool_call_chunks', None)}") - -asyncio.run(test()) diff --git a/agent/tests/deep_agent/__init__.py b/agent/tests/deep_agent/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/agent/tests/deep_agent/test_cli.py b/agent/tests/deep_agent/test_cli.py new file mode 100644 index 0000000..77f9ab4 --- /dev/null +++ b/agent/tests/deep_agent/test_cli.py @@ -0,0 +1,65 @@ +import json + +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage + +from deep_agent.cli import RunRecord, append_run_record, extract_final_sql_and_answer, print_formatted_message + + +def test_extracts_last_sql_block_and_strips_it_from_answer(): + answer = "הסבר קצר\n```sql\nSELECT 1\n```\nעוד טקסט\n```sql\nSELECT 2\n```" + sql, text = extract_final_sql_and_answer([HumanMessage("q"), AIMessage(answer)]) + assert sql == "SELECT 2" + assert "SELECT" not in text + assert "הסבר קצר" in text + + +def test_handles_list_content_blocks_without_crashing(): + final = AIMessage(content=[ + {"type": "reasoning", "reasoning": "thinking..."}, + {"type": "text", "text": "תשובה\n```sql\nSELECT COUNT(*) FROM t\n```"}, + ]) + sql, text = extract_final_sql_and_answer([HumanMessage("q"), final]) + assert sql == "SELECT COUNT(*) FROM t" + assert text == "תשובה" + + +def test_falls_back_to_history_when_final_answer_has_no_sql(): + history = [ + HumanMessage("q"), + AIMessage("draft\n```sql\nSELECT 3\n```"), + ToolMessage("ok", tool_call_id="1"), + AIMessage("final answer, no sql"), + ] + sql, text = extract_final_sql_and_answer(history) + assert sql == "SELECT 3" + assert text == "final answer, no sql" + + +def test_strips_thought_blocks(): + sql, text = extract_final_sql_and_answer([AIMessage("hiddenvisible")]) + assert sql is None + assert text == "visible" + + +def test_empty_history(): + assert extract_final_sql_and_answer([]) == (None, "") + + +def test_run_record_is_valid_jsonl(tmp_path): + log = tmp_path / "runs" / "log.jsonl" + for i in range(2): + append_run_record(log, RunRecord("2026-10-20T10:00:00", 1.5, f"t{i}", "שאלה\nשורה", "SELECT 1", "תשובה")) + lines = log.read_text(encoding="utf-8").splitlines() + assert len(lines) == 2 + rows = [json.loads(line) for line in lines] + assert rows[0]["question"] == "שאלה\nשורה" + assert set(rows[1]) == {"timestamp", "execution_time_s", "thread_id", "question", "final_sql", "final_answer"} + + +def test_print_formatted_message_handles_list_content(capsys): + print_formatted_message(AIMessage(content=[{"type": "text", "text": "hello"}], tool_calls=[ + {"name": "execute_trino_query", "args": {"sql": "SELECT 1"}, "id": "1"}, + ])) + print_formatted_message(ToolMessage(content=[{"type": "text", "text": "Error: boom"}], tool_call_id="1", name="x")) + out = capsys.readouterr().out + assert "hello" in out and "execute_trino_query" in out and "Error: boom" in out From 2539c942bed520315fcdc1d75b6600e064e03690 Mon Sep 17 00:00:00 2001 From: Stav Ponte Date: Tue, 20 Oct 2026 12:32:26 +0300 Subject: [PATCH 05/37] fix(deep-agent): actually load skills and AGENTS.md memory Skills and memory were silently never loaded: paths were hardcoded to another developer's machine, the default StateBackend reads from agent state rather than disk, and each skill directory was passed as a skill source instead of their parent. - Package skills/ and memory/AGENTS.md inside deep_agent (ship in wheel) - CompositeBackend: /skills/ and /memory/ -> read-only FilesystemBackend, everything else -> StateBackend; writes to both denied via permissions - build_resources() validates layout + frontmatter and fails fast - DEEP_AGENT_SKILLS_DIR / DEEP_AGENT_MEMORY_DIR overrides - create_deep_agent(model=...) for tests; scripted fake chat model fixture Closes #34 Co-Authored-By: Claude Opus 5.5 --- agent/pyproject.toml | 1 + agent/src/agent/config.py | 4 + agent/src/deep_agent/agent.py | 21 +-- agent/{ => src/deep_agent/memory}/AGENTS.md | 0 agent/src/deep_agent/resources.py | 123 ++++++++++++++++++ .../skills/semantic-validation/SKILL.md | 0 .../skills/spatial-analyst/SKILL.md | 0 .../skills/temporal-analyst/SKILL.md | 0 .../deep_agent}/skills/trino-expert/SKILL.md | 0 agent/tests/deep_agent/conftest.py | 32 +++++ agent/tests/deep_agent/test_resources.py | 123 ++++++++++++++++++ agent/uv.lock | 2 + 12 files changed, 297 insertions(+), 9 deletions(-) rename agent/{ => src/deep_agent/memory}/AGENTS.md (100%) create mode 100644 agent/src/deep_agent/resources.py rename agent/{ => src/deep_agent}/skills/semantic-validation/SKILL.md (100%) rename agent/{ => src/deep_agent}/skills/spatial-analyst/SKILL.md (100%) rename agent/{ => src/deep_agent}/skills/temporal-analyst/SKILL.md (100%) rename agent/{ => src/deep_agent}/skills/trino-expert/SKILL.md (100%) create mode 100644 agent/tests/deep_agent/conftest.py create mode 100644 agent/tests/deep_agent/test_resources.py diff --git a/agent/pyproject.toml b/agent/pyproject.toml index c697e6b..05e327b 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -24,6 +24,7 @@ dependencies = [ "sqlglot>=25.0.0", "deepagents>=0.6.12", "urllib3>=2.7.0", + "pyyaml>=6.0", ] [project.scripts] diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 202b578..ae13d6f 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -45,6 +45,10 @@ class AgentSettings(BaseSettings): JEEN_METADATA_SEARCH_LIMIT: int = 10 # Max tables returned by the search tool JEEN_METADATA_PROFILE_TIMEOUT: float = 30.0 # Per-MCP-call timeout (seconds) + # ── Deep Agent ──────────────────────────────────────────────────────────── + DEEP_AGENT_SKILLS_DIR: str | None = None # Override packaged skills dir (//SKILL.md) + DEEP_AGENT_MEMORY_DIR: str | None = None # Override packaged memory dir (must contain AGENTS.md) + # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" TRINO_SCHEMA: str = "" diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 8e9134e..96b3305 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -3,6 +3,7 @@ """ from deepagents import create_deep_agent as create_harness_agent +from langchain_core.language_models import BaseChatModel from langgraph.checkpoint.memory import MemorySaver from deep_agent.tools import ( @@ -27,6 +28,7 @@ ) import datetime from agent.llm import get_llm +from deep_agent.resources import build_resources SYSTEM_PROMPT = """You are an elite, autonomous Deep SQL Analyst. Your mission: translate Hebrew natural-language questions into verified Trino SQL that is **semantically correct** — not just syntactically valid or merely executable. @@ -205,12 +207,15 @@ """ -def create_deep_agent(): +def create_deep_agent(model: BaseChatModel | None = None): """ Creates and returns a compiled LangGraph deep agent equipped with all exploration, enrichment, temporal, geospatial, and semantic validation tools. + + Args: + model: Chat model override (tests); defaults to the configured LLM. """ - llm = get_llm() + llm = model or get_llm() tools = [ # Discovery & Schema @@ -237,19 +242,17 @@ def create_deep_agent(): memory = MemorySaver() today = datetime.date.today().isoformat() + resources = build_resources() agent = create_harness_agent( model=llm, tools=tools, system_prompt=SYSTEM_PROMPT.format(today=today), checkpointer=memory, - memory=["/Users/benben/Desktop/code/text2sql-onboarding/agent/AGENTS.md"], - skills=[ - "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/trino-expert", - "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/spatial-analyst", - "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/temporal-analyst", - "/Users/benben/Desktop/code/text2sql-onboarding/agent/skills/semantic-validation", - ], + backend=resources.backend, + memory=resources.memory, + skills=resources.skills, + permissions=resources.permissions, ) return agent diff --git a/agent/AGENTS.md b/agent/src/deep_agent/memory/AGENTS.md similarity index 100% rename from agent/AGENTS.md rename to agent/src/deep_agent/memory/AGENTS.md diff --git a/agent/src/deep_agent/resources.py b/agent/src/deep_agent/resources.py new file mode 100644 index 0000000..f8c6ff8 --- /dev/null +++ b/agent/src/deep_agent/resources.py @@ -0,0 +1,123 @@ +""" +Skills and memory (AGENTS.md) wiring for the Deep Agent. + +Skills and memory live on disk inside this package and are exposed to deepagents +through a CompositeBackend: + + /skills//SKILL.md -> read-only FilesystemBackend over the skills dir + /memory/AGENTS.md -> read-only FilesystemBackend over the memory dir + everything else -> ephemeral StateBackend (agent scratch files) + +Writes to /skills/ and /memory/ are denied via FilesystemPermission, so the agent +can read its references but never modify them. +""" + +from dataclasses import dataclass +from pathlib import Path + +import yaml +from deepagents import FilesystemPermission +from deepagents.backends import CompositeBackend, FilesystemBackend, StateBackend + +from agent.config import settings + +PACKAGE_DIR = Path(__file__).resolve().parent +DEFAULT_SKILLS_DIR = PACKAGE_DIR / "skills" +DEFAULT_MEMORY_DIR = PACKAGE_DIR / "memory" + +SKILLS_ROUTE = "/skills/" +MEMORY_ROUTE = "/memory/" +MEMORY_FILE = "AGENTS.md" + +EXPECTED_SKILLS = frozenset({"trino-expert", "temporal-analyst", "spatial-analyst", "semantic-validation"}) + + +class DeepAgentResourceError(RuntimeError): + """Skills or memory are missing or malformed; the agent must not start without them.""" + + +@dataclass(frozen=True) +class DeepAgentResources: + backend: CompositeBackend + skills: list[str] + memory: list[str] + permissions: list[FilesystemPermission] + skill_names: frozenset[str] + + +def _read_frontmatter(skill_md: Path) -> dict: + text = skill_md.read_text(encoding="utf-8") + if not text.startswith("---"): + raise DeepAgentResourceError(f"{skill_md}: missing YAML frontmatter") + try: + _, frontmatter, _ = text.split("---", 2) + data = yaml.safe_load(frontmatter) + except (ValueError, yaml.YAMLError) as exc: + raise DeepAgentResourceError(f"{skill_md}: invalid YAML frontmatter ({exc})") from exc + if not isinstance(data, dict) or not data.get("name") or not data.get("description"): + raise DeepAgentResourceError(f"{skill_md}: frontmatter needs 'name' and 'description'") + return data + + +def discover_skills(skills_dir: Path) -> frozenset[str]: + """Validate the skills layout (//SKILL.md) and return the skill names.""" + if not skills_dir.is_dir(): + raise DeepAgentResourceError(f"Skills directory not found: {skills_dir}") + + names = set() + for skill_md in sorted(skills_dir.glob("*/SKILL.md")): + name = _read_frontmatter(skill_md)["name"] + if name != skill_md.parent.name: + raise DeepAgentResourceError( + f"{skill_md}: frontmatter name '{name}' must match its directory '{skill_md.parent.name}'" + ) + names.add(name) + + if not names: + raise DeepAgentResourceError(f"No skills found under {skills_dir} (expected /SKILL.md)") + return frozenset(names) + + +def build_resources( + skills_dir: Path | None = None, + memory_dir: Path | None = None, + expected_skills: frozenset[str] = EXPECTED_SKILLS, +) -> DeepAgentResources: + """Validate skills/memory on disk and build the backend + create_deep_agent arguments. + + Fails fast (DeepAgentResourceError) instead of letting deepagents silently skip + missing files. + """ + skills_dir = Path(skills_dir or settings.DEEP_AGENT_SKILLS_DIR or DEFAULT_SKILLS_DIR).resolve() + memory_dir = Path(memory_dir or settings.DEEP_AGENT_MEMORY_DIR or DEFAULT_MEMORY_DIR).resolve() + + skill_names = discover_skills(skills_dir) + missing = expected_skills - skill_names + if missing: + raise DeepAgentResourceError(f"Missing required skills in {skills_dir}: {sorted(missing)}") + + memory_file = memory_dir / MEMORY_FILE + if not memory_file.is_file() or not memory_file.read_text(encoding="utf-8").strip(): + raise DeepAgentResourceError(f"Memory file missing or empty: {memory_file}") + + backend = CompositeBackend( + default=StateBackend(), + routes={ + SKILLS_ROUTE: FilesystemBackend(root_dir=skills_dir, virtual_mode=True), + MEMORY_ROUTE: FilesystemBackend(root_dir=memory_dir, virtual_mode=True), + }, + ) + permissions = [ + FilesystemPermission( + operations=["write"], + paths=[f"{SKILLS_ROUTE}**", f"{MEMORY_ROUTE}**"], + mode="deny", + ), + ] + return DeepAgentResources( + backend=backend, + skills=[SKILLS_ROUTE], + memory=[f"{MEMORY_ROUTE}{MEMORY_FILE}"], + permissions=permissions, + skill_names=skill_names, + ) diff --git a/agent/skills/semantic-validation/SKILL.md b/agent/src/deep_agent/skills/semantic-validation/SKILL.md similarity index 100% rename from agent/skills/semantic-validation/SKILL.md rename to agent/src/deep_agent/skills/semantic-validation/SKILL.md diff --git a/agent/skills/spatial-analyst/SKILL.md b/agent/src/deep_agent/skills/spatial-analyst/SKILL.md similarity index 100% rename from agent/skills/spatial-analyst/SKILL.md rename to agent/src/deep_agent/skills/spatial-analyst/SKILL.md diff --git a/agent/skills/temporal-analyst/SKILL.md b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md similarity index 100% rename from agent/skills/temporal-analyst/SKILL.md rename to agent/src/deep_agent/skills/temporal-analyst/SKILL.md diff --git a/agent/skills/trino-expert/SKILL.md b/agent/src/deep_agent/skills/trino-expert/SKILL.md similarity index 100% rename from agent/skills/trino-expert/SKILL.md rename to agent/src/deep_agent/skills/trino-expert/SKILL.md diff --git a/agent/tests/deep_agent/conftest.py b/agent/tests/deep_agent/conftest.py new file mode 100644 index 0000000..a452986 --- /dev/null +++ b/agent/tests/deep_agent/conftest.py @@ -0,0 +1,32 @@ +from collections.abc import Iterator + +import pytest +from langchain_core.language_models.fake_chat_models import GenericFakeChatModel +from langchain_core.messages import AIMessage, BaseMessage + + +class ScriptedChatModel(GenericFakeChatModel): + """Fake chat model that replays scripted AIMessages and records every prompt it receives.""" + + seen: list[list[BaseMessage]] = [] + + def bind_tools(self, tools, **kwargs): # deepagents binds tools; the script decides the calls + return self + + def _generate(self, messages, stop=None, run_manager=None, **kwargs): + self.seen.append(list(messages)) + return super()._generate(messages, stop=stop, run_manager=run_manager, **kwargs) + + +@pytest.fixture +def scripted_model(): + def _make(*replies: AIMessage) -> ScriptedChatModel: + model = ScriptedChatModel(messages=iter(replies)) + model.seen = [] + return model + + return _make + + +def system_text(messages: list[BaseMessage]) -> str: + return "\n".join(m.text for m in messages if m.type == "system") diff --git a/agent/tests/deep_agent/test_resources.py b/agent/tests/deep_agent/test_resources.py new file mode 100644 index 0000000..57f3880 --- /dev/null +++ b/agent/tests/deep_agent/test_resources.py @@ -0,0 +1,123 @@ +import os +import shutil + +import pytest +from langchain_core.messages import AIMessage + +from deep_agent.agent import create_deep_agent +from deep_agent.resources import ( + DEFAULT_MEMORY_DIR, + DEFAULT_SKILLS_DIR, + EXPECTED_SKILLS, + DeepAgentResourceError, + _read_frontmatter, + build_resources, + discover_skills, +) +from tests.deep_agent.conftest import system_text + + +def test_packaged_skills_and_memory_are_valid(): + resources = build_resources() + assert resources.skill_names == EXPECTED_SKILLS + assert resources.skills == ["/skills/"] + assert resources.memory == ["/memory/AGENTS.md"] + + +def test_no_user_specific_paths_in_deep_agent_sources(): + for path in DEFAULT_SKILLS_DIR.parent.rglob("*.py"): + assert "/Users/" not in path.read_text(encoding="utf-8"), path + + +def test_resources_resolve_independently_of_cwd(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + assert build_resources().skill_names == EXPECTED_SKILLS + + +@pytest.fixture +def resource_copy(tmp_path): + skills = tmp_path / "skills" + memory = tmp_path / "memory" + shutil.copytree(DEFAULT_SKILLS_DIR, skills) + shutil.copytree(DEFAULT_MEMORY_DIR, memory) + return skills, memory + + +def test_missing_skills_dir_fails_fast(tmp_path): + with pytest.raises(DeepAgentResourceError, match="Skills directory not found"): + build_resources(skills_dir=tmp_path / "nope", memory_dir=DEFAULT_MEMORY_DIR) + + +def test_missing_required_skill_fails_fast(resource_copy): + skills, memory = resource_copy + shutil.rmtree(skills / "temporal-analyst") + with pytest.raises(DeepAgentResourceError, match="temporal-analyst"): + build_resources(skills_dir=skills, memory_dir=memory) + + +def test_empty_memory_fails_fast(resource_copy): + skills, memory = resource_copy + (memory / "AGENTS.md").write_text(" \n", encoding="utf-8") + with pytest.raises(DeepAgentResourceError, match="Memory file missing or empty"): + build_resources(skills_dir=skills, memory_dir=memory) + + +def test_skill_without_frontmatter_fails_fast(resource_copy): + skills, _ = resource_copy + (skills / "trino-expert" / "SKILL.md").write_text("# no frontmatter", encoding="utf-8") + with pytest.raises(DeepAgentResourceError, match="frontmatter"): + discover_skills(skills) + + +def test_skill_name_must_match_directory(resource_copy): + skills, _ = resource_copy + os.rename(skills / "trino-expert", skills / "trino") + with pytest.raises(DeepAgentResourceError, match="must match its directory"): + discover_skills(skills) + + +@pytest.mark.asyncio +async def test_skills_and_memory_reach_the_model_prompt(scripted_model): + model = scripted_model(AIMessage("done")) + agent = create_deep_agent(model=model) + await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-prompt"}}) + + prompt = system_text(model.seen[0]) + # Skill *names* also appear in source labels even when nothing loads, so assert on the + # frontmatter descriptions, which are only rendered for skills that were actually loaded. + assert "No skills available" not in prompt + for skill_md in sorted(DEFAULT_SKILLS_DIR.glob("*/SKILL.md")): + description = _read_frontmatter(skill_md)["description"] + assert description[:60] in prompt, f"skill {skill_md.parent.name} not loaded" + assert "Deep SQL Analyst — Core Memory" in prompt, "AGENTS.md memory not injected" + + +@pytest.mark.asyncio +async def test_agent_cannot_write_skills_or_memory(scripted_model): + write = AIMessage("", tool_calls=[ + {"name": "write_file", "args": {"file_path": "/skills/evil/SKILL.md", "content": "x"}, "id": "w1"}, + {"name": "edit_file", "args": {"file_path": "/memory/AGENTS.md", "old_string": "Deep", "new_string": "Shallow"}, "id": "w2"}, + ]) + model = scripted_model(write, AIMessage("done")) + agent = create_deep_agent(model=model) + result = await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-write"}}) + + tool_results = [m for m in result["messages"] if m.type == "tool"] + assert len(tool_results) == 2 + for msg in tool_results: + assert "denied" in msg.text.lower() or "permission" in msg.text.lower(), msg.text + assert not (DEFAULT_SKILLS_DIR / "evil").exists() + assert "Deep SQL Analyst" in (DEFAULT_MEMORY_DIR / "AGENTS.md").read_text(encoding="utf-8") + + +@pytest.mark.asyncio +async def test_agent_can_read_a_skill_file(scripted_model): + read = AIMessage("", tool_calls=[ + {"name": "read_file", "args": {"file_path": "/skills/trino-expert/SKILL.md"}, "id": "r1"}, + ]) + model = scripted_model(read, AIMessage("done")) + agent = create_deep_agent(model=model) + result = await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-read"}}) + + tool_msg = next(m for m in result["messages"] if m.type == "tool") + assert "Trino SQL Expert Reference" in tool_msg.text diff --git a/agent/uv.lock b/agent/uv.lock index 22e29fd..cfcae1a 100644 --- a/agent/uv.lock +++ b/agent/uv.lock @@ -21,6 +21,7 @@ dependencies = [ { name = "mcp" }, { name = "networkx" }, { name = "pydantic-settings" }, + { name = "pyyaml" }, { name = "shapely" }, { name = "sqlglot" }, { name = "trino" }, @@ -53,6 +54,7 @@ requires-dist = [ { name = "mcp", specifier = ">=1.12.4" }, { name = "networkx", specifier = ">=3.3" }, { name = "pydantic-settings", specifier = ">=2.7.0" }, + { name = "pyyaml", specifier = ">=6.0" }, { name = "shapely", specifier = ">=2.0.0" }, { name = "sqlglot", specifier = ">=25.0.0" }, { name = "trino", specifier = ">=0.328.0" }, From 852d20e71794204b30752f93eabe1990602a4429 Mon Sep 17 00:00:00 2001 From: Stav Ponte Date: Tue, 20 Oct 2026 12:33:44 +0300 Subject: [PATCH 06/37] chore(skills): add code-review, codebase-design, grill-me, implement and improve-codebase-architecture agent skills Installed from mattpocock/skills; lock entries added to skills-lock.json. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/code-review/SKILL.md | 89 +++++++++++++ .agents/skills/code-review/agents/openai.yaml | 3 + .agents/skills/codebase-design/DEEPENING.md | 37 ++++++ .../skills/codebase-design/DESIGN-IT-TWICE.md | 44 +++++++ .agents/skills/codebase-design/SKILL.md | 114 ++++++++++++++++ .../skills/codebase-design/agents/openai.yaml | 3 + .agents/skills/grill-me/SKILL.md | 7 + .agents/skills/grill-me/agents/openai.yaml | 5 + .agents/skills/implement/SKILL.md | 17 +++ .agents/skills/implement/agents/openai.yaml | 5 + .../HTML-REPORT.md | 123 ++++++++++++++++++ .../improve-codebase-architecture/SKILL.md | 71 ++++++++++ .../agents/openai.yaml | 5 + skills-lock.json | 30 +++++ 14 files changed, 553 insertions(+) create mode 100644 .agents/skills/code-review/SKILL.md create mode 100644 .agents/skills/code-review/agents/openai.yaml create mode 100644 .agents/skills/codebase-design/DEEPENING.md create mode 100644 .agents/skills/codebase-design/DESIGN-IT-TWICE.md create mode 100644 .agents/skills/codebase-design/SKILL.md create mode 100644 .agents/skills/codebase-design/agents/openai.yaml create mode 100644 .agents/skills/grill-me/SKILL.md create mode 100644 .agents/skills/grill-me/agents/openai.yaml create mode 100644 .agents/skills/implement/SKILL.md create mode 100644 .agents/skills/implement/agents/openai.yaml create mode 100644 .agents/skills/improve-codebase-architecture/HTML-REPORT.md create mode 100644 .agents/skills/improve-codebase-architecture/SKILL.md create mode 100644 .agents/skills/improve-codebase-architecture/agents/openai.yaml diff --git a/.agents/skills/code-review/SKILL.md b/.agents/skills/code-review/SKILL.md new file mode 100644 index 0000000..373a4f2 --- /dev/null +++ b/.agents/skills/code-review/SKILL.md @@ -0,0 +1,89 @@ +--- +name: code-review +description: "Review the changes since a fixed point (commit, branch, tag, or merge-base) along two axes: Standards (does the code follow this repo's documented coding standards?) and Spec (does the code match what the originating issue/spec asked for?). Runs both reviews in parallel sub-agents and reports them side by side. Use when the user wants to review a branch, a PR, work-in-progress changes, or asks to \"review since X\"." +--- + +Two-axis review of the diff between `HEAD` and a fixed point the user supplies: + +- **Standards**: does the code conform to this repo's documented coding standards? +- **Spec**: does the code faithfully implement the originating issue / spec? + +Both axes run as **parallel sub-agents** so they don't pollute each other's context, then this skill aggregates their findings. + +The issue tracker should have been provided to you. If not, tell the user to run `/setup-matt-pocock-skills`. + +## Process + +### 1. Pin the fixed point + +Whatever the user said is the fixed point (a commit SHA, branch name, tag, `main`, `HEAD~5`, etc.). If they didn't specify one, ask for it. + +Capture the diff command once: `git diff ...HEAD` (three-dot, so the comparison is against the merge-base). Also note the list of commits via `git log ..HEAD --oneline`. + +Before going further, confirm the fixed point resolves (`git rev-parse `) and the diff is non-empty. A bad ref or empty diff should fail here, not inside two parallel sub-agents. + +### 2. Identify the spec source + +Look for the originating spec, in this order: + +1. Issue references in the commit messages (`#123`, `Closes #45`, GitLab `!67`, etc.), fetched via the workflow in the tracker doc. +2. A path the user passed as an argument. +3. A spec file under `docs/`, `specs/`, or `.scratch/` matching the branch name or feature. +4. If nothing is found, ask the user where the spec is. If they say there isn't one, the **Spec** sub-agent will skip and report "no spec available". + +### 3. Identify the standards sources + +Search the repo for every file that documents how code should be written. When `CODING_STANDARDS.md` or `CONTRIBUTING.md` exists, it must be on the list. + +On top of whatever the repo documents, the Standards axis always carries the **smell baseline** below: a fixed set of Fowler code smells (_Refactoring_, ch.3) that applies even when a repo documents nothing. Two rules bind it: + +- **The repo overrides.** A documented repo standard always wins; where it endorses something the baseline would flag, suppress the smell. +- **Always a judgement call.** Each smell is a labelled heuristic ("possible Feature Envy"), never a hard violation. Like any standard here, skip anything tooling already enforces. + +Each smell reads *what it is* → *how to fix*; match it against the diff: + +- **Mysterious Name**: a function, variable, or type whose name doesn't reveal what it does or holds. → rename it; if no honest name comes, the design's murky. +- **Duplicated Code**: the same logic shape appears in more than one hunk or file in the change. → extract the shared shape, call it from both. +- **Feature Envy**: a method that reaches into another object's data more than its own. → move the method onto the data it envies. +- **Data Clumps**: the same few fields or params keep travelling together (a type wanting to be born). → bundle them into one type, pass that. +- **Primitive Obsession**: a primitive or string standing in for a domain concept that deserves its own type. → give the concept its own small type. +- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurs across the change. → replace with polymorphism, or one map both sites share. +- **Shotgun Surgery**: one logical change forces scattered edits across many files in the diff. → gather what changes together into one module. +- **Divergent Change**: one file or module is edited for several unrelated reasons. → split so each module changes for one reason. +- **Speculative Generality**: abstraction, parameters, or hooks added for needs the spec doesn't have. → delete it; inline back until a real need shows. +- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on. → hide the walk behind one method on the first object. +- **Middle Man**: a class or function that mostly just delegates onward. → cut it, call the real target direct. +- **Refused Bequest**: a subclass or implementer that ignores or overrides most of what it inherits. → drop the inheritance, use composition. + +### 4. Spawn both sub-agents in parallel + +Issue both sub-agent calls together, in the foreground, and aggregate the reports they return. + +**Standards sub-agent prompt** should include: + +- The full diff command and commit list. +- The list of standards-source files you found in step 3, **plus the smell baseline from step 3** pasted in full (the sub-agent has no other access to it). +- The brief: "Report, per file/hunk where relevant, (a) every place the diff violates a documented standard: cite the standard (file + the rule); and (b) any baseline smell you spot: name it and quote the hunk. Distinguish hard violations from judgement calls: documented-standard breaches can be hard, but baseline smells are always judgement calls, and a documented repo standard overrides the baseline. Skip anything tooling enforces. Under 400 words." + +**Spec sub-agent prompt** should include: + +- The diff command and commit list. +- The path or fetched contents of the spec. +- The brief: "Report: (a) requirements the spec asked for that are missing or partial; (b) behaviour in the diff that wasn't asked for (scope creep); (c) requirements that look implemented but where the implementation looks wrong. Quote the spec line for each finding. Under 400 words." + +If the spec is missing, skip the Spec sub-agent and note this in the final report. + +### 5. Aggregate + +Present the two reports under `## Standards` and `## Spec` headings, verbatim or lightly cleaned. Do **not** merge or rerank findings, because the two axes are deliberately separate (see _Why two axes_). + +End with a one-line summary: total findings per axis, and the worst issue _within each axis_ (if any). Don't pick a single winner across axes: that's the reranking the separation exists to prevent. + +## Why two axes + +A change can pass one axis and fail the other: + +- Code that follows every standard but implements the wrong thing → **Standards pass, Spec fail.** +- Code that does exactly what the issue asked but breaks the project's conventions → **Spec pass, Standards fail.** + +Reporting them separately stops one axis from masking the other. diff --git a/.agents/skills/code-review/agents/openai.yaml b/.agents/skills/code-review/agents/openai.yaml new file mode 100644 index 0000000..9076774 --- /dev/null +++ b/.agents/skills/code-review/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Code Review" + short_description: "Review a diff on standards and spec" diff --git a/.agents/skills/codebase-design/DEEPENING.md b/.agents/skills/codebase-design/DEEPENING.md new file mode 100644 index 0000000..cd94075 --- /dev/null +++ b/.agents/skills/codebase-design/DEEPENING.md @@ -0,0 +1,37 @@ +# Deepening + +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 1. In-process + +Pure computation, in-memory state, no I/O. Always deepenable: merge the modules and test through the new interface directly. No adapter needed. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## Testing strategy: replace, don't layer + +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist; delete them. +- Write new tests at the deepened module's interface. The **interface is the test surface**. +- Tests assert on observable outcomes through the interface, not internal state. +- Tests should survive internal refactors, since they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.agents/skills/codebase-design/DESIGN-IT-TWICE.md b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md new file mode 100644 index 0000000..d099013 --- /dev/null +++ b/.agents/skills/codebase-design/DESIGN-IT-TWICE.md @@ -0,0 +1,44 @@ +# Design It Twice + +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout): your first idea is unlikely to be the best. + +Uses the vocabulary in [SKILL.md](SKILL.md): **module**, **interface**, **seam**, **adapter**, **leverage**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- The constraints any new interface would need to satisfy +- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) +- A rough illustrative code sketch to ground the constraints, not a proposal, just a way to make the constraints concrete + +Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. + +### 2. Spawn sub-agents + +Spawn 3+ sub-agents in parallel. Each must produce a **radically different** interface for the deepened module. + +Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: + +- Agent 1: "Minimize the interface: aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility: support many use cases and extension." +- Agent 3: "Optimise for the most common caller: make the default case trivial." +- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." + +Include both [SKILL.md](SKILL.md) vocabulary and GLOSSARY.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. + +Each sub-agent outputs: + +1. Interface (types, methods, params, plus invariants, ordering, error modes) +2. Usage example showing how callers use it +3. What the implementation hides behind the seam +4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) +5. Trade-offs: where leverage is high, where it's thin + +### 3. Present and compare + +Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. + +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated: the user wants a strong read, not a menu. diff --git a/.agents/skills/codebase-design/SKILL.md b/.agents/skills/codebase-design/SKILL.md new file mode 100644 index 0000000..3f63c81 --- /dev/null +++ b/.agents/skills/codebase-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: codebase-design +description: Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary. +--- + +# Codebase Design + +Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone. + +## Glossary + +Use these terms exactly: don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +**Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice. _Avoid_: unit, component, service. + +**Interface**: everything a caller must know to use the module correctly: the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. _Avoid_: API, signature (too narrow, they refer only to the type-level surface). + +**Implementation**: what's inside a module, its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth**: leverage at the interface. The amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface, **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(Michael Feathers)_: a place where you can alter behaviour without editing in that place; the *location* at which a module's interface lives. Where to put the seam is its own design decision, distinct from what goes behind it. _Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter**: a concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage**: what callers get from depth. More capability per unit of interface they learn. One implementation pays back across N call sites and M tests. + +**Locality**: what maintainers get from depth. Change, bugs, knowledge, and verification concentrate in one place rather than spreading across callers. Fix once, fixed everywhere. + +## Deep vs shallow + +**Deep module** = small interface + lots of implementation: + +``` +┌─────────────────────┐ +│ Small Interface │ ← Few methods, simple params +├─────────────────────┤ +│ │ +│ Deep Implementation│ ← Complex logic hidden +│ │ +└─────────────────────┘ +``` + +**Shallow module** = large interface + little implementation (avoid): + +``` +┌─────────────────────────────────┐ +│ Large Interface │ ← Many methods, complex params +├─────────────────────────────────┤ +│ Thin Implementation │ ← Just passes through +└─────────────────────────────────┘ +``` + +When designing an interface, ask: + +- Can I reduce the number of methods? +- Can I simplify the parameters? +- Can I hide more complexity inside? + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts; they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Designing for testability + +Good interfaces make testing natural: + +1. **Accept dependencies, don't create them.** + + ```typescript + // Testable + function processOrder(order, paymentGateway) {} + + // Hard to test + function processOrder(order) { + const gateway = new StripeGateway(); + } + ``` + +2. **Return results, don't produce side effects.** + + ```typescript + // Testable + function calculateDiscount(cart): Discount {} + + // Hard to test + function applyDiscount(cart): void { + cart.total -= discount; + } + ``` + +3. **Small surface area.** Fewer methods = fewer tests needed. Fewer params = simpler test setup. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow: interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. + +## Going deeper + +- **Deepening a cluster given its dependencies**, see [DEEPENING.md](DEEPENING.md): dependency categories, seam discipline, and replace-don't-layer testing. +- **Exploring alternative interfaces**, see [DESIGN-IT-TWICE.md](DESIGN-IT-TWICE.md): spin up parallel sub-agents to design the interface several radically different ways, then compare on depth, locality, and seam placement. diff --git a/.agents/skills/codebase-design/agents/openai.yaml b/.agents/skills/codebase-design/agents/openai.yaml new file mode 100644 index 0000000..3180715 --- /dev/null +++ b/.agents/skills/codebase-design/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Codebase Design" + short_description: "Vocabulary for deep-module design" diff --git a/.agents/skills/grill-me/SKILL.md b/.agents/skills/grill-me/SKILL.md new file mode 100644 index 0000000..3947ff9 --- /dev/null +++ b/.agents/skills/grill-me/SKILL.md @@ -0,0 +1,7 @@ +--- +name: grill-me +description: A relentless interview to sharpen a plan or design. +disable-model-invocation: true +--- + +Call the Skill tool with "grilling". diff --git a/.agents/skills/grill-me/agents/openai.yaml b/.agents/skills/grill-me/agents/openai.yaml new file mode 100644 index 0000000..4d6fb0c --- /dev/null +++ b/.agents/skills/grill-me/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Grill Me" + short_description: "Sharpen a plan through interview" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/implement/SKILL.md b/.agents/skills/implement/SKILL.md new file mode 100644 index 0000000..bd49e47 --- /dev/null +++ b/.agents/skills/implement/SKILL.md @@ -0,0 +1,17 @@ +--- +name: implement +description: "Implement a piece of work based on a spec or set of tickets." +disable-model-invocation: true +--- + +Implement the work described by the user in the spec or tickets. + +If the user passes a ticket reference, fetch it from the issue tracker and state its title before starting. If the reference is ambiguous, ask. + +Call the Skill tool with "tdd" where possible, at pre-agreed seams. + +Run typechecking regularly, single test files regularly, and the full test suite once at the end. + +Once done, call the Skill tool with "code-review" to review the work. + +Commit your work to the current branch. diff --git a/.agents/skills/implement/agents/openai.yaml b/.agents/skills/implement/agents/openai.yaml new file mode 100644 index 0000000..f8794dc --- /dev/null +++ b/.agents/skills/implement/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Implement" + short_description: "Build work from a spec or tickets" +policy: + allow_implicit_invocation: false diff --git a/.agents/skills/improve-codebase-architecture/HTML-REPORT.md b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md new file mode 100644 index 0000000..e39e825 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/HTML-REPORT.md @@ -0,0 +1,123 @@ +# HTML Report Format + +The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic. + +## Scaffold + +```html + + + + + Architecture review for {{repo name}} + + + + + +
+
...
+
...
+
...
+
+ + +``` + +## Header + +Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates. + +## Candidate card + +The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `/codebase-design` skill) without ceremony. + +Each candidate is one `
`: + +- **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline"). +- **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`). +- **Files**: monospaced list, `font-mono text-sm`. +- **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below. +- **Problem**: one sentence. What hurts. +- **Solution**: one sentence. What changes. +- **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers". +- **ADR callout** (if applicable): one line in an amber-tinted box. + +No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram. + +## Diagram patterns + +Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point. + +### Mermaid graph (the workhorse for dependencies / call flow) + +Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1." + +```html +
+
+    flowchart LR
+      A[OrderHandler] --> B[OrderValidator]
+      B --> C[OrderRepo]
+      C -.leak.-> D[PricingClient]
+      classDef leak stroke:#dc2626,stroke-width:2px;
+      class C,D leak
+  
+
+``` + +### Hand-built boxes-and-arrows (when Mermaid's layout fights you) + +Modules as `
`s with borders and labels. Arrows as inline SVG `` or `` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight. + +### Cross-section (good for layered shallowness) + +Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility. + +### Mass diagram (good for "interface as wide as implementation") + +Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep). + +### Call-graph collapse + +Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it. + +## Style guidance + +- Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate). +- Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings. +- Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling. +- Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI. +- The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering. + +## Top recommendation section + +One larger card. Candidate name, one sentence on why, anchor link to its card. That's it. + +## Tone + +Plain English, concise, but the architectural nouns and verbs come straight from the `/codebase-design` skill. Concision is not an excuse to drift. + +**Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality. + +**Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module). + +**Phrasings that fit the style:** + +- "Order intake module is shallow: interface nearly matches the implementation." +- "Pricing leaks across the seam." +- "Deepen: one interface, one place to test." +- "Two adapters justify the seam: HTTP in prod, in-memory in tests." + +**Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place. + +No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `/codebase-design` glossary, reach for one that is before inventing a new one. diff --git a/.agents/skills/improve-codebase-architecture/SKILL.md b/.agents/skills/improve-codebase-architecture/SKILL.md new file mode 100644 index 0000000..44cc7d3 --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/SKILL.md @@ -0,0 +1,71 @@ +--- +name: improve-codebase-architecture +description: Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick. +disable-model-invocation: true +--- + +# Improve Codebase Architecture + +Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. + +This command is _informed_ by the project's domain model and built on a shared design vocabulary: + +- Call the Skill tool with "codebase-design" for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary." +- The domain language in `GLOSSARY.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate. + +## Process + +### 1. Explore + +**Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look: + +- If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below. +- Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net. + +Read the project's domain glossary (`GLOSSARY.md`) and any ADRs in the area you're touching first. + +Then spawn a sub-agent to walk the codebase. Don't follow rigid heuristics; explore organically and note where you experience friction: + +- Where does understanding one concept require bouncing between many small modules? +- Where are modules **shallow**, with an interface nearly as complex as the implementation? +- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? +- Where do tightly-coupled modules leak across their seams? +- Which parts of the codebase are untested, or hard to test through their current interface? + +Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. + +### 2. Present candidates as an HTML report + +Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `/architecture-review-.html` so each run gets a fresh file. Open it for the user (`xdg-open ` on Linux, `open ` on macOS, `start ` on Windows) and tell them the absolute path. + +The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual. + +For each candidate, render a card with: + +- **Files**: which files/modules are involved +- **Problem**: why the current architecture is causing friction +- **Solution**: plain English description of what would change +- **Benefits**: explained in terms of locality and leverage, and how tests would improve +- **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening +- **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge + +End the report with a **Top recommendation** section: which candidate you'd tackle first and why. + +**Use GLOSSARY.md vocabulary for the domain, and the `/codebase-design` vocabulary for the architecture.** If `GLOSSARY.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service." + +**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. + +See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance. + +Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?" + +### 3. Grilling loop + +Once the user picks a candidate, call the Skill tool with "grilling" to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. + +Side effects happen inline as decisions crystallize; call the Skill tool with "domain-modeling" to keep the domain model current as you go: + +- **Naming a deepened module after a concept not in `GLOSSARY.md`?** Add the term to `GLOSSARY.md`. Create the file lazily if it doesn't exist. +- **Sharpening a fuzzy term during the conversation?** Update `GLOSSARY.md` right there. +- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones. +- **Want to explore alternative interfaces for the deepened module?** Call the Skill tool with "codebase-design" and use its design-it-twice parallel sub-agent pattern. diff --git a/.agents/skills/improve-codebase-architecture/agents/openai.yaml b/.agents/skills/improve-codebase-architecture/agents/openai.yaml new file mode 100644 index 0000000..706fdca --- /dev/null +++ b/.agents/skills/improve-codebase-architecture/agents/openai.yaml @@ -0,0 +1,5 @@ +interface: + display_name: "Improve Codebase Architecture" + short_description: "Find and grill architecture improvements" +policy: + allow_implicit_invocation: false diff --git a/skills-lock.json b/skills-lock.json index 51873e3..5689129 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -31,12 +31,24 @@ "skillPath": "skills/code-documenter/SKILL.md", "computedHash": "49709db09641a9ab4196459835bfcbe565eb0581c23cb4eeb50ff80d2af88272" }, + "code-review": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/code-review/SKILL.md", + "computedHash": "57cfd4ceb011f05e58a1a4f4cad3b2e03419d371f8990f4bcb32ff0d435a039f" + }, "code-reviewer": { "source": "jeffallan/claude-skills", "sourceType": "github", "skillPath": "skills/code-reviewer/SKILL.md", "computedHash": "57ab3eba6fa596bc52d73ca7312afc2f389d9622714d25b2ab3d4bbf03dc293a" }, + "codebase-design": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/codebase-design/SKILL.md", + "computedHash": "b2888e4f4e8c0af3bfd557575a64b905c44e6248c3101d72077816882b3a92b9" + }, "database-optimizer": { "source": "jeffallan/claude-skills", "sourceType": "github", @@ -79,6 +91,24 @@ "skillPath": "skills/fullstack-guardian/SKILL.md", "computedHash": "2d3533f91951f2c8626eaeb7ffb33e40727bca85545a8e63f97e35939957e1a4" }, + "grill-me": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/productivity/grill-me/SKILL.md", + "computedHash": "9cdbb4b8f7a3aeaef82e6230c9e823500d4a8a1214c726cf342cf9829d34fc7d" + }, + "implement": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/implement/SKILL.md", + "computedHash": "b6371a0a6723bad551f3adc721e3729a6a97acfc3670dc2bdea198bbe78408c0" + }, + "improve-codebase-architecture": { + "source": "mattpocock/skills", + "sourceType": "github", + "skillPath": "skills/engineering/improve-codebase-architecture/SKILL.md", + "computedHash": "ac2c94885f34ff8492dc12aa4543182f661f32ea1722b8d6b6c2c7045af33ae3" + }, "javascript-pro": { "source": "jeffallan/claude-skills", "sourceType": "github", From 70ad316c2e3cac2249ebea1f0ad9a2e16e1ebf70 Mon Sep 17 00:00:00 2001 From: Stav Ponte Date: Tue, 20 Oct 2026 12:35:51 +0300 Subject: [PATCH 07/37] fix(deep-agent): enforce read-only SQL, AST-level LIMIT and safe identifiers - agent/utils/sql_guard.py (ported from Utils-Server trino guard): one read statement only; rejects writes/DDL/CALL/SET, multi-statements, comments (tokenizer-based, so 'a--b' literals are fine) and TABLE(...) pass-through; enforces outer LIMIT cap+1 incl. CTE/UNION/FETCH cases - execute_trino_query / get_sample_rows / get_column_distinct_values / validate_sql_syntax go through the guard; limits clamped via DEEP_AGENT_MAX_ROWS / DEEP_AGENT_MAX_SAMPLE_ROWS; 'truncated' flag - identifiers parsed/quoted with sqlglot (spaces, Hebrew, "" escaping) - nested execute_trino_query.invoke() replaced by a shared _run_sql helper Closes #35 Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 9 ++ agent/src/agent/config.py | 2 + agent/src/agent/utils/sql_guard.py | 161 +++++++++++++++++++++ agent/src/deep_agent/tools.py | 130 ++++++++++------- agent/tests/deep_agent/test_trino_tools.py | 80 ++++++++++ agent/tests/test_sql_guard.py | 134 +++++++++++++++++ 6 files changed, 463 insertions(+), 53 deletions(-) create mode 100644 agent/src/agent/utils/sql_guard.py create mode 100644 agent/tests/deep_agent/test_trino_tools.py create mode 100644 agent/tests/test_sql_guard.py diff --git a/agent/README.md b/agent/README.md index 096779f..ce745d4 100644 --- a/agent/README.md +++ b/agent/README.md @@ -50,3 +50,12 @@ uv run deep-agent "..." --log-file runs/runs.jsonl # append one JSON line per It reads the same `agent/.env` settings as the API (LLM, Trino, Jeen metadata MCP, Langfuse). Run logs are opt-in and git-ignored (`agent/runs/`, `agent/*.jsonl`, `agent/*.csv`); Langfuse is the system of record for traces. + +### SQL safety (deep agent) + +Every SQL the deep agent runs goes through `agent/utils/sql_guard.py` (sqlglot, Trino dialect): +- exactly one read-only statement (`SELECT` / `WITH` / set operations, plus `SHOW` / `DESCRIBE`); writes, DDL, `CALL`, `SET`, multi-statements, SQL comments and `TABLE(...)` pass-through functions are rejected with `FORBIDDEN_STATEMENT` +- an outer `LIMIT` of cap + 1 is enforced at the AST level (`DEEP_AGENT_MAX_ROWS`, default 100; `DEEP_AGENT_MAX_SAMPLE_ROWS`, default 10) and results report `truncated` +- table and column names in `get_sample_rows` / `get_column_distinct_values` are parsed and quoted by sqlglot, never string-interpolated + +The guard is an application-level control. The Trino principal used by the agent should also be SELECT-only. diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index ae13d6f..e739d61 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -48,6 +48,8 @@ class AgentSettings(BaseSettings): # ── Deep Agent ──────────────────────────────────────────────────────────── DEEP_AGENT_SKILLS_DIR: str | None = None # Override packaged skills dir (//SKILL.md) DEEP_AGENT_MEMORY_DIR: str | None = None # Override packaged memory dir (must contain AGENTS.md) + DEEP_AGENT_MAX_ROWS: int = Field(default=100, gt=0) # Hard cap on rows returned by execute_trino_query + DEEP_AGENT_MAX_SAMPLE_ROWS: int = Field(default=10, gt=0) # Hard cap on rows returned by get_sample_rows # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" diff --git a/agent/src/agent/utils/sql_guard.py b/agent/src/agent/utils/sql_guard.py new file mode 100644 index 0000000..c886ef6 --- /dev/null +++ b/agent/src/agent/utils/sql_guard.py @@ -0,0 +1,161 @@ +""" +SQL guardrails for LLM-generated Trino SQL. + +Parses with sqlglot, allows only a single read statement, enforces a row cap at the +AST level, and builds identifiers safely. Ported from Utils-Server +(app/services/trino/guard.py) so both agents share one implementation. +""" + +import re +from dataclasses import dataclass + +import sqlglot +from sqlglot import exp +from sqlglot.errors import SqlglotError +from sqlglot.tokens import Tokenizer + +_DIALECT = "trino" +_SHOW = re.compile( + r"^\s*SHOW\s+(CATALOGS|SCHEMAS|TABLES|COLUMNS|FUNCTIONS|STATS|CREATE\s+(TABLE|VIEW)|SESSION)\b", + re.IGNORECASE, +) +_READ_ROOTS = (exp.Select, exp.SetOperation, exp.Subquery) + + +class GuardError(ValueError): + """The SQL was rejected; the message is safe to show the caller (and the agent).""" + + +@dataclass(frozen=True) +class GuardedSQL: + sql: str # rewritten SQL to execute + row_cap: int | None # rows to keep (fetch row_cap + 1 to detect truncation); None for SHOW/DESCRIBE + requested_limit: int | None # LIMIT the SQL asked for, if any + is_query: bool # SELECT-like (row cap applied) vs SHOW/DESCRIBE + + +def clamp(value: int | None, low: int, high: int, default: int) -> int: + if value is None: + return default + return max(low, min(int(value), high)) + + +def _has_comments(sql: str) -> bool: + try: + return any(token.comments for token in Tokenizer(dialect=_DIALECT).tokenize(sql)) + except SqlglotError: + return "--" in sql or "/*" in sql + + +def _reject_pass_through(tree: exp.Expression) -> None: + # TABLE(catalog.system.query(query => '...')) runs arbitrary SQL on the underlying source. + for table in tree.find_all(exp.Table): + if isinstance(table.this, exp.Anonymous) and str(table.this.this).upper() == "TABLE": + raise GuardError("table functions (TABLE(...)) are not allowed") + for func in tree.find_all(exp.Anonymous): + if str(func.this).upper() == "TABLE": + raise GuardError("table functions (TABLE(...)) are not allowed") + + +def _reject_writes(tree: exp.Expression) -> None: + # Data-modifying nodes nested inside an otherwise read-looking statement (e.g. CTAS-like constructs). + for node in tree.walk(): + if isinstance(node, (exp.Insert, exp.Update, exp.Delete, exp.Merge, exp.Create, exp.Drop, exp.Alter)): + raise GuardError(f"{type(node).__name__.upper()} is not allowed: read-only access") + + +def _limit_value(tree: exp.Expression) -> int | None: + lim = tree.args.get("limit") + if isinstance(lim, exp.Limit) and isinstance(lim.expression, exp.Literal) and not lim.expression.is_string: + return int(lim.expression.this) + return None + + +def parse_read_statement(sql: str) -> exp.Expression | None: + """Validate `sql` as exactly one read-only statement. + + Returns the parsed tree for SELECT-like statements, or None for an allowed + SHOW/DESCRIBE statement. Raises GuardError otherwise. + """ + if not sql or not sql.strip(): + raise GuardError("empty SQL") + if _has_comments(sql): + raise GuardError("SQL comments are not allowed") + try: + statements = [s for s in sqlglot.parse(sql, read=_DIALECT) if s is not None] + except SqlglotError as e: + raise GuardError(f"could not parse SQL: {str(e).splitlines()[0]}") from e + if len(statements) != 1: + raise GuardError("exactly one statement is allowed") + tree = statements[0] + + if isinstance(tree, exp.Command): + if _SHOW.match(sql): + return None + raise GuardError("only SELECT, WITH, SHOW and DESCRIBE statements are allowed") + if isinstance(tree, exp.Describe): + return None + if not isinstance(tree, _READ_ROOTS): + raise GuardError(f"{type(tree).__name__.upper()} statements are not allowed: read-only access") + + _reject_pass_through(tree) + _reject_writes(tree) + return tree + + +def prepare(sql: str, row_cap: int) -> GuardedSQL: + """Validate `sql` and enforce an outer LIMIT of row_cap + 1 (the extra row flags truncation).""" + tree = parse_read_statement(sql) + if tree is None: + return GuardedSQL(sql.strip().rstrip(";"), None, None, False) + + fetch = row_cap + 1 + asked = _limit_value(tree) + if isinstance(tree, exp.Select) and not tree.args.get("fetch"): + if asked is None or asked > fetch: + tree = tree.limit(fetch, copy=True) + elif asked is None or asked > fetch or isinstance(tree, exp.SetOperation) or tree.args.get("fetch"): + tree = exp.select("*").from_(tree.subquery("_q")).limit(fetch) + return GuardedSQL(tree.sql(dialect=_DIALECT), row_cap, asked, True) + + +def parse_table_name(table_name: str) -> exp.Table: + """Parse a (possibly quoted, 1–3 part) table name; reject anything that isn't a plain table.""" + raw = (table_name or "").strip() + if not raw: + raise GuardError("empty table name") + try: + table = sqlglot.parse_one(raw, into=exp.Table, dialect=_DIALECT) + except SqlglotError as e: + raise GuardError(f"invalid table name {raw!r}") from e + parts = [table.args.get(k) for k in ("catalog", "db", "this")] + if not isinstance(table.this, exp.Identifier) or any( + p is not None and not isinstance(p, exp.Identifier) for p in parts + ): + raise GuardError(f"invalid table name {raw!r}") + if set(table.args) - {"catalog", "db", "this"} and any( + v for k, v in table.args.items() if k not in ("catalog", "db", "this") + ): + raise GuardError(f"invalid table name {raw!r}") + return exp.Table(**{k: v for k, v in zip(("catalog", "db", "this"), parts) if v is not None}) + + +def quoted_column(column_name: str) -> exp.Column: + """Build a quoted column reference from a raw or double-quoted name (spaces/Hebrew allowed).""" + name = (column_name or "").strip() + if len(name) >= 2 and name.startswith('"') and name.endswith('"'): + name = name[1:-1].replace('""', '"') + if not name: + raise GuardError("empty column name") + return exp.column(exp.to_identifier(name, quoted=True)) + + +def sample_rows_sql(table_name: str, row_cap: int) -> str: + table = parse_table_name(table_name) + return exp.select("*").from_(table).limit(row_cap + 1).sql(dialect=_DIALECT) + + +def distinct_values_sql(table_name: str, column_name: str, row_cap: int) -> str: + table = parse_table_name(table_name) + column = quoted_column(column_name) + return exp.select(column).distinct().from_(table).limit(row_cap + 1).sql(dialect=_DIALECT) diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 24c3414..03c061f 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -4,8 +4,11 @@ from typing import Optional from langchain_core.tools import tool +from agent.config import settings +from agent.utils import sql_guard from agent.utils.jeen_metadata_client import get_jeen_metadata_client -from agent.utils.sql import clean_sql, resolve_wkt_polygons +from agent.utils.sql import clean_sql +from agent.utils.sql_guard import clamp from core.trino import execute_query_sync from agent.services.geo_utils import get_geojson_polygon, geojson_to_simplified_wkt @@ -229,18 +232,61 @@ def _classify_trino_error(error_message: str) -> str: return "EXECUTION_ERROR" +_HINTS = { + "SYNTAX_ERROR": "Fix the specific syntax line — do not redesign the entire query.", + "TABLE_NOT_FOUND": "Re-verify the exact 3-part table name from get_database_catalog.", + "COLUMN_NOT_FOUND": "Re-verify the column name from get_table_columns for this table.", + "TYPE_MISMATCH": "Add CAST(column AS target_type) for the mismatched column.", + "FUNCTION_NOT_FOUND": "Check Trino function spelling. E.g., use ST_GeometryFromText, not ST_GeomFromText.", + "TIMEOUT_OR_RESOURCE": "Add a tighter LIMIT or simplify the query.", + "FORBIDDEN_STATEMENT": "Only a single read-only SELECT/WITH (or SHOW/DESCRIBE) statement without comments is allowed.", + "EXECUTION_ERROR": "Investigate the specific error message.", +} + + +def _error_result(error_category: str, error_message: str) -> str: + return json.dumps({ + "success": False, + "error_category": error_category, + "error_message": error_message, + "hint": _HINTS.get(error_category, "Investigate the error message."), + }, ensure_ascii=False) + + +def _run_sql(sql: str, row_cap: int) -> str: + """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation.""" + try: + res = execute_query_sync(sql) + except Exception as e: + return _error_result("EXECUTION_ERROR", str(e)) + if not res.success: + error_msg = res.error_message or "Unknown error" + return _error_result(_classify_trino_error(error_msg), error_msg) + + rows = res.rows or [] + truncated = len(rows) > row_cap + rows = rows[:row_cap] + return json.dumps({ + "success": True, + "columns": res.columns, + "row_count": len(rows), + "truncated": truncated, + "rows": rows, + }, ensure_ascii=False, default=str) + + @tool def execute_trino_query(sql: str, limit: int = 50) -> str: """ Executes a read-only Trino SQL query and returns the resulting rows. Use this to test SQL queries against the actual database and perform exploratory data analysis. - Always use LIMIT on exploratory queries to avoid pulling millions of rows. + Only a single SELECT / WITH (or SHOW / DESCRIBE) statement is accepted; anything that writes, + multiple statements, SQL comments and TABLE(...) pass-through functions are rejected with + error_category FORBIDDEN_STATEMENT. - IMPORTANT — WKT Location Tokens: - If your SQL contains location placeholders in the form '@location_name_wkt@' (produced by - resolve_location_to_wkt), you MUST replace them with the actual WKT string before calling - this tool. Pass the raw WKT inside ST_GeometryFromText('...') directly in the SQL string. + Results are capped: an outer LIMIT is enforced automatically, and the response includes + 'truncated': true when more rows existed than were returned. On failure, the response includes an 'error_category' field to help you classify and fix the error precisely: @@ -249,50 +295,19 @@ def execute_trino_query(sql: str, limit: int = 50) -> str: - TYPE_MISMATCH: add an explicit CAST(col AS type) - FUNCTION_NOT_FOUND: check the Trino function name - TIMEOUT_OR_RESOURCE: simplify the query or add a tighter LIMIT + - FORBIDDEN_STATEMENT: rewrite as a single read-only query without comments Args: sql (str): The exact Trino SQL query string to execute. Markdown fences and trailing semicolons are stripped automatically. limit (int): The maximum number of rows to return (1–100). Defaults to 50. """ - sql_clean = clean_sql(sql).rstrip(';') - if "limit" not in sql_clean.lower(): - sql_clean = f"{sql_clean} LIMIT {limit}" - + row_cap = clamp(limit, 1, settings.DEEP_AGENT_MAX_ROWS, 50) try: - res = execute_query_sync(sql_clean) - if not res.success: - error_msg = res.error_message or "Unknown error" - error_category = _classify_trino_error(error_msg) - result_dict = { - "success": False, - "error_category": error_category, - "error_message": error_msg, - "hint": { - "SYNTAX_ERROR": "Fix the specific syntax line — do not redesign the entire query.", - "TABLE_NOT_FOUND": "Re-verify the exact 3-part table name from get_database_catalog.", - "COLUMN_NOT_FOUND": "Re-verify the column name from get_table_columns for this table.", - "TYPE_MISMATCH": "Add CAST(column AS target_type) for the mismatched column.", - "FUNCTION_NOT_FOUND": "Check Trino function spelling. E.g., use ST_GeometryFromText, not ST_GeomFromText.", - "TIMEOUT_OR_RESOURCE": "Add a tighter LIMIT or simplify the query.", - "EXECUTION_ERROR": "Investigate the specific error message.", - }.get(error_category, "Investigate the error message."), - } - return json.dumps(result_dict, ensure_ascii=False) - - result_dict = { - "success": True, - "columns": res.columns, - "row_count": res.row_count, - "rows": res.rows, - } - return json.dumps(result_dict, ensure_ascii=False, default=str) - except Exception as e: - return json.dumps({ - "success": False, - "error_category": "EXECUTION_ERROR", - "error_message": str(e), - }, ensure_ascii=False) + guarded = sql_guard.prepare(clean_sql(sql), row_cap) + except sql_guard.GuardError as e: + return _error_result("FORBIDDEN_STATEMENT", str(e)) + return _run_sql(guarded.sql, guarded.row_cap if guarded.is_query else settings.DEEP_AGENT_MAX_ROWS) @tool @@ -305,12 +320,15 @@ def get_sample_rows(table_name: str, limit: int = 5) -> str: Do NOT use this for counting or aggregating data. Args: - table_name (str): The fully qualified exact name of the table. + table_name (str): The fully qualified exact name of the table, e.g. '"catalog"."schema"."table"'. limit (int): The number of rows to sample (1–10). Defaults to 5. """ - safe_table = table_name.split()[0].rstrip(';') - sql = f"SELECT * FROM {safe_table} LIMIT {limit}" - return execute_trino_query.invoke({"sql": sql, "limit": limit}) + row_cap = clamp(limit, 1, settings.DEEP_AGENT_MAX_SAMPLE_ROWS, 5) + try: + sql = sql_guard.sample_rows_sql(table_name, row_cap) + except sql_guard.GuardError as e: + return _error_result("FORBIDDEN_STATEMENT", str(e)) + return _run_sql(sql, row_cap) @tool @@ -332,13 +350,15 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 Args: table_name (str): The fully qualified exact name of the table. - column_name (str): The exact name of the column. + column_name (str): The exact name of the column (plain or double-quoted; spaces and Hebrew are fine). limit (int): Maximum distinct values to return (1–100). Defaults to 50. """ - safe_table = table_name.split()[0].rstrip(';') - safe_col = column_name.split()[0].rstrip(';') - sql = f"SELECT DISTINCT {safe_col} FROM {safe_table} LIMIT {limit}" - return execute_trino_query.invoke({"sql": sql, "limit": limit}) + row_cap = clamp(limit, 1, settings.DEEP_AGENT_MAX_ROWS, 50) + try: + sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) + except sql_guard.GuardError as e: + return _error_result("FORBIDDEN_STATEMENT", str(e)) + return _run_sql(sql, row_cap) # --------------------------------------------------------------------------- @@ -357,7 +377,11 @@ def validate_sql_syntax(sql: str) -> str: Args: sql (str): The exact Trino SQL query string to validate. """ - sql_clean = clean_sql(sql).rstrip(';') + sql_clean = clean_sql(sql) + try: + sql_guard.parse_read_statement(sql_clean) + except sql_guard.GuardError as e: + return f"Syntax Error: {e}" try: res = execute_query_sync(f"EXPLAIN (TYPE VALIDATE) {sql_clean}") if res.success: diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py new file mode 100644 index 0000000..a60ffca --- /dev/null +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -0,0 +1,80 @@ +import json +from unittest.mock import patch + +import pytest + +from core.trino import TrinoExecutionResult +from deep_agent import tools + + +def _ok(n_rows: int) -> TrinoExecutionResult: + return TrinoExecutionResult( + success=True, rows=[[i] for i in range(n_rows)], columns=["id"], row_count=n_rows, execution_time_ms=1 + ) + + +@pytest.fixture +def trino(): + with patch.object(tools, "execute_query_sync") as mock: + yield mock + + +@pytest.mark.parametrize("sql", ["DROP TABLE t", "DELETE FROM t", "SELECT 1; DROP TABLE t", "SELECT 1 -- x"]) +def test_forbidden_sql_never_reaches_trino(trino, sql): + out = json.loads(tools.execute_trino_query.invoke({"sql": sql})) + assert out["success"] is False + assert out["error_category"] == "FORBIDDEN_STATEMENT" + trino.assert_not_called() + + +def test_limit_argument_is_clamped_and_truncation_reported(trino): + trino.return_value = _ok(101) + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t", "limit": 1_000_000})) + executed = trino.call_args.args[0] + assert executed.endswith("LIMIT 101") + assert out["row_count"] == 100 + assert out["truncated"] is True + + +def test_speed_limit_column_still_gets_limit(trino): + trino.return_value = _ok(3) + out = json.loads(tools.execute_trino_query.invoke({"sql": "```sql\nSELECT speed_limit FROM t;\n```", "limit": 10})) + assert trino.call_args.args[0] == "SELECT speed_limit FROM t LIMIT 11" + assert out["truncated"] is False + assert out["row_count"] == 3 + + +def test_trino_error_is_reported(trino): + trino.return_value = TrinoExecutionResult(success=False, error_message="line 1:8: Column 'x' cannot be resolved") + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT x FROM t"})) + assert out["error_category"] == "COLUMN_NOT_FOUND" + + +def test_sample_rows_handles_hebrew_quoted_table(trino): + trino.return_value = _ok(2) + tools.get_sample_rows.invoke({"table_name": '"postgres"."public"."טבלת ערים"', "limit": 50}) + assert trino.call_args.args[0] == 'SELECT * FROM "postgres"."public"."טבלת ערים" LIMIT 11' + + +def test_sample_rows_rejects_injection(trino): + out = json.loads(tools.get_sample_rows.invoke({"table_name": "t; DROP TABLE t"})) + assert out["error_category"] == "FORBIDDEN_STATEMENT" + trino.assert_not_called() + + +def test_distinct_values_quotes_hebrew_column(trino): + trino.return_value = _ok(1) + tools.get_column_distinct_values.invoke({"table_name": "postgres.public.t", "column_name": "שם עיר", "limit": 20}) + assert trino.call_args.args[0] == 'SELECT DISTINCT "שם עיר" FROM postgres.public.t LIMIT 21' + + +def test_validate_rejects_writes_without_calling_trino(trino): + out = tools.validate_sql_syntax.invoke({"sql": "DELETE FROM t"}) + assert out.startswith("Syntax Error:") + trino.assert_not_called() + + +def test_validate_runs_explain_for_reads(trino): + trino.return_value = _ok(0) + assert tools.validate_sql_syntax.invoke({"sql": "SELECT 1"}) == "Syntax is VALID." + assert trino.call_args.args[0] == "EXPLAIN (TYPE VALIDATE) SELECT 1" diff --git a/agent/tests/test_sql_guard.py b/agent/tests/test_sql_guard.py new file mode 100644 index 0000000..79dabd4 --- /dev/null +++ b/agent/tests/test_sql_guard.py @@ -0,0 +1,134 @@ +import pytest +import sqlglot +from sqlglot import exp + +from agent.utils import sql_guard +from agent.utils.sql_guard import GuardError, clamp, distinct_values_sql, prepare, sample_rows_sql + + +def _outer_limit(sql: str) -> int | None: + tree = sqlglot.parse_one(sql, read="trino") + lim = tree.args.get("limit") + return int(lim.expression.this) if lim else None + + +@pytest.mark.parametrize("sql", [ + "INSERT INTO t VALUES (1)", + "UPDATE t SET a = 1", + "DELETE FROM t", + "MERGE INTO t USING s ON t.id = s.id WHEN MATCHED THEN DELETE", + "DROP TABLE t", + "CREATE TABLE x AS SELECT * FROM t", + "ALTER TABLE t ADD COLUMN c int", + "CALL system.sync_partition_metadata('a', 'b', 'FULL')", + "GRANT SELECT ON t TO u", + "SET SESSION query_max_run_time = '1h'", + "SELECT 1; DROP TABLE t", + "SELECT 1; SELECT 2", + "SELECT * FROM TABLE(postgres.system.query(query => 'DELETE FROM t'))", + "SELECT 1 -- sneaky comment", + "SELECT /* hidden */ 1", + "", + " ", +]) +def test_rejects_non_read_statements(sql): + with pytest.raises(GuardError): + prepare(sql, 50) + + +@pytest.mark.parametrize("sql", [ + "SELECT speed_limit FROM t", # 'limit' substring bypass + "WITH a AS (SELECT * FROM t LIMIT 5) SELECT * FROM a JOIN b ON 1=1", # inner LIMIT only + "SELECT * FROM t", +]) +def test_unbounded_selects_get_an_outer_limit(sql): + guarded = prepare(sql, 50) + assert guarded.is_query + assert _outer_limit(guarded.sql) == 51 # cap + 1 to detect truncation + + +def test_larger_explicit_limit_is_capped(): + guarded = prepare("SELECT * FROM t LIMIT 100000", 50) + assert _outer_limit(guarded.sql) == 51 + assert guarded.requested_limit == 100000 + + +def test_smaller_explicit_limit_is_kept(): + guarded = prepare("SELECT * FROM t LIMIT 5", 50) + assert _outer_limit(guarded.sql) == 5 + + +@pytest.mark.parametrize("sql", [ + "SELECT a FROM t UNION SELECT a FROM u", + "SELECT a FROM t UNION ALL SELECT a FROM u LIMIT 1000", + "SELECT a FROM t FETCH FIRST 1000 ROWS ONLY", +]) +def test_set_operations_and_fetch_are_wrapped(sql): + guarded = prepare(sql, 10) + tree = sqlglot.parse_one(guarded.sql, read="trino") + assert isinstance(tree, exp.Select) + assert _outer_limit(guarded.sql) == 11 + + +def test_string_literal_with_dashes_is_not_a_comment(): + guarded = prepare("SELECT * FROM t WHERE code = 'a--b'", 10) + assert "'a--b'" in guarded.sql + + +@pytest.mark.parametrize("sql", ["SHOW TABLES FROM postgres.public", "DESCRIBE postgres.public.t"]) +def test_show_and_describe_pass_without_limit(sql): + guarded = prepare(sql, 10) + assert not guarded.is_query + assert "LIMIT" not in guarded.sql.upper() + + +def test_trailing_semicolon_is_accepted(): + assert prepare("SELECT 1;", 10).is_query + + +def test_clamp(): + assert clamp(1_000_000, 1, 100, 50) == 100 + assert clamp(0, 1, 100, 50) == 1 + assert clamp(None, 1, 100, 50) == 50 + + +@pytest.mark.parametrize("table, expected", [ + ('"postgres"."public"."my table"', '"postgres"."public"."my table"'), + ('"postgres"."public"."שם טבלה"', '"postgres"."public"."שם טבלה"'), + ("postgres.public.flights_table", "postgres.public.flights_table"), + ("flights_table", "flights_table"), +]) +def test_sample_rows_sql_keeps_valid_identifiers(table, expected): + sql = sample_rows_sql(table, 5) + assert sql == f"SELECT * FROM {expected} LIMIT 6" + + +@pytest.mark.parametrize("table", [ + "x; DROP TABLE y", + '"a"."b"."c" UNION SELECT * FROM secrets', + "t WHERE 1=1", + "(SELECT 1)", + "", +]) +def test_sample_rows_sql_rejects_injection(table): + with pytest.raises(GuardError): + sample_rows_sql(table, 5) + + +@pytest.mark.parametrize("column, expected", [ + ("launch_country", '"launch_country"'), + ('"שם עיר"', '"שם עיר"'), + ("שם עיר", '"שם עיר"'), + ('weird"name', '"weird""name"'), +]) +def test_distinct_values_sql_quotes_columns(column, expected): + sql = distinct_values_sql('"postgres"."public"."t"', column, 20) + assert sql == f'SELECT DISTINCT {expected} FROM "postgres"."public"."t" LIMIT 21' + sql_guard.parse_read_statement(sql) # the generated SQL itself passes the guard + + +def test_distinct_values_column_injection_is_neutralised(): + sql = distinct_values_sql("t", "a FROM t; DROP TABLE t", 5) + # The whole input becomes one quoted identifier, never executable SQL. + assert sql == 'SELECT DISTINCT "a FROM t; DROP TABLE t" FROM t LIMIT 6' + sql_guard.parse_read_statement(sql) From bad0b38125f1b9e41554958783dde9be52eacdf6 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 26 Oct 2026 14:19:17 +0200 Subject: [PATCH 08/37] fix(deep-agent): keep FETCH/UNION ordering in the SQL guard; make row ceilings optional On top of #35 (review fixes): - FETCH FIRST n ROWS was not recognised as a limit and got replaced by the cap, so a "top 5" query returned up to cap rows; it is now read as the requested limit and left as written when within the cap (WITH TIES kept) - set operations were wrapped in SELECT * FROM (...) LIMIT, which lets Trino drop the inner ORDER BY; the LIMIT is now set on the set operation itself - SQL already within the cap runs exactly as written (no sqlglot rewrite) - DEEP_AGENT_MAX_ROWS / DEEP_AGENT_MAX_SAMPLE_ROWS keep their 100 / 10 defaults but accept "none" (or empty / "unlimited") to disable the ceiling; with no ceiling the SQL is validated only and every row is returned - execute_trino_query's limit argument now defaults to the configured ceiling Verified the ORDER BY and FETCH cases against a real Trino 443. Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 3 +- agent/src/agent/config.py | 15 ++++-- agent/src/agent/utils/sql_guard.py | 53 ++++++++++++++++------ agent/src/deep_agent/tools.py | 33 ++++++++------ agent/tests/deep_agent/test_trino_tools.py | 45 ++++++++++++++++++ agent/tests/test_sql_guard.py | 47 ++++++++++++++++--- 6 files changed, 157 insertions(+), 39 deletions(-) diff --git a/agent/README.md b/agent/README.md index ce745d4..e188a79 100644 --- a/agent/README.md +++ b/agent/README.md @@ -55,7 +55,8 @@ Run logs are opt-in and git-ignored (`agent/runs/`, `agent/*.jsonl`, `agent/*.cs Every SQL the deep agent runs goes through `agent/utils/sql_guard.py` (sqlglot, Trino dialect): - exactly one read-only statement (`SELECT` / `WITH` / set operations, plus `SHOW` / `DESCRIBE`); writes, DDL, `CALL`, `SET`, multi-statements, SQL comments and `TABLE(...)` pass-through functions are rejected with `FORBIDDEN_STATEMENT` -- an outer `LIMIT` of cap + 1 is enforced at the AST level (`DEEP_AGENT_MAX_ROWS`, default 100; `DEEP_AGENT_MAX_SAMPLE_ROWS`, default 10) and results report `truncated` +- an outer `LIMIT` of cap + 1 is enforced at the AST level (`DEEP_AGENT_MAX_ROWS`, default 100; `DEEP_AGENT_MAX_SAMPLE_ROWS`, default 10) and results report `truncated`. A `LIMIT` / `FETCH FIRST` already within the cap is left as written, and set operations get the `LIMIT` in place so their `ORDER BY` survives +- set either variable to `none` to disable that ceiling: SQL then runs exactly as written and every row is returned (mind the model's context size) - table and column names in `get_sample_rows` / `get_column_distinct_values` are parsed and quoted by sqlglot, never string-interpolated The guard is an application-level control. The Trino principal used by the agent should also be SELECT-only. diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index e739d61..5972609 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -1,4 +1,4 @@ -from pydantic import Field +from pydantic import Field, field_validator from pydantic_settings import BaseSettings, SettingsConfigDict from typing import Literal @@ -48,8 +48,9 @@ class AgentSettings(BaseSettings): # ── Deep Agent ──────────────────────────────────────────────────────────── DEEP_AGENT_SKILLS_DIR: str | None = None # Override packaged skills dir (//SKILL.md) DEEP_AGENT_MEMORY_DIR: str | None = None # Override packaged memory dir (must contain AGENTS.md) - DEEP_AGENT_MAX_ROWS: int = Field(default=100, gt=0) # Hard cap on rows returned by execute_trino_query - DEEP_AGENT_MAX_SAMPLE_ROWS: int = Field(default=10, gt=0) # Hard cap on rows returned by get_sample_rows + # Row ceilings for the deep agent's SQL tools. Set to "none" (or empty) to disable the ceiling. + DEEP_AGENT_MAX_ROWS: int | None = Field(default=100, gt=0) # execute_trino_query / get_column_distinct_values + DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" @@ -102,5 +103,13 @@ class AgentSettings(BaseSettings): # ── G2-05: Redis Schema Cache ───────────────────────────────────────────── SCHEMA_CACHE_TTL: int = Field(default=600, gt=0) # seconds — DDL content + @field_validator("DEEP_AGENT_MAX_ROWS", "DEEP_AGENT_MAX_SAMPLE_ROWS", mode="before") + @classmethod + def _no_row_ceiling(cls, value): + # Env vars can't hold None; these spellings mean "no ceiling". + if isinstance(value, str) and value.strip().lower() in ("", "none", "null", "unlimited"): + return None + return value + settings = AgentSettings() diff --git a/agent/src/agent/utils/sql_guard.py b/agent/src/agent/utils/sql_guard.py index c886ef6..d19fd50 100644 --- a/agent/src/agent/utils/sql_guard.py +++ b/agent/src/agent/utils/sql_guard.py @@ -34,10 +34,15 @@ class GuardedSQL: is_query: bool # SELECT-like (row cap applied) vs SHOW/DESCRIBE -def clamp(value: int | None, low: int, high: int, default: int) -> int: - if value is None: - return default - return max(low, min(int(value), high)) +def effective_cap(requested: int | None, ceiling: int | None) -> int | None: + """Rows to return: the caller's request, bounded by the configured ceiling when one is set. + + None means unlimited — no ceiling configured and nothing requested. + """ + if requested is None: + return ceiling + requested = max(1, int(requested)) + return min(requested, ceiling) if ceiling is not None else requested def _has_comments(sql: str) -> bool: @@ -65,9 +70,19 @@ def _reject_writes(tree: exp.Expression) -> None: def _limit_value(tree: exp.Expression) -> int | None: + """Row count of the outer LIMIT n or FETCH FIRST n ROWS (sqlglot stores both under 'limit').""" lim = tree.args.get("limit") - if isinstance(lim, exp.Limit) and isinstance(lim.expression, exp.Literal) and not lim.expression.is_string: - return int(lim.expression.this) + if isinstance(lim, exp.Limit): + count = lim.expression + elif isinstance(lim, exp.Fetch): + options = lim.args.get("limit_options") + if options is not None and options.args.get("percent"): + return None + count = lim.args.get("count") + else: + return None + if isinstance(count, exp.Literal) and not count.is_string: + return int(count.this) return None @@ -103,18 +118,28 @@ def parse_read_statement(sql: str) -> exp.Expression | None: return tree -def prepare(sql: str, row_cap: int) -> GuardedSQL: - """Validate `sql` and enforce an outer LIMIT of row_cap + 1 (the extra row flags truncation).""" +def prepare(sql: str, row_cap: int | None) -> GuardedSQL: + """Validate `sql`; when row_cap is set, enforce an outer LIMIT of row_cap + 1 (the extra row flags truncation). + + With row_cap=None the statement is only validated and runs exactly as written. + """ tree = parse_read_statement(sql) + original = sql.strip().rstrip(";").strip() if tree is None: - return GuardedSQL(sql.strip().rstrip(";"), None, None, False) + return GuardedSQL(original, None, None, False) - fetch = row_cap + 1 asked = _limit_value(tree) - if isinstance(tree, exp.Select) and not tree.args.get("fetch"): - if asked is None or asked > fetch: - tree = tree.limit(fetch, copy=True) - elif asked is None or asked > fetch or isinstance(tree, exp.SetOperation) or tree.args.get("fetch"): + if row_cap is None: + return GuardedSQL(original, None, asked, True) + + fetch = row_cap + 1 + if asked is not None and asked <= fetch: + # Already within the cap: run it exactly as written (keeps FETCH ... WITH TIES semantics). + return GuardedSQL(original, row_cap, asked, True) + if isinstance(tree, (exp.Select, exp.SetOperation)): + # Set the outer LIMIT in place. Wrapping in a subquery would let Trino drop the ORDER BY. + tree = tree.limit(fetch, copy=True) + else: tree = exp.select("*").from_(tree.subquery("_q")).limit(fetch) return GuardedSQL(tree.sql(dialect=_DIALECT), row_cap, asked, True) diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 03c061f..af374d0 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -8,7 +8,7 @@ from agent.utils import sql_guard from agent.utils.jeen_metadata_client import get_jeen_metadata_client from agent.utils.sql import clean_sql -from agent.utils.sql_guard import clamp +from agent.utils.sql_guard import effective_cap from core.trino import execute_query_sync from agent.services.geo_utils import get_geojson_polygon, geojson_to_simplified_wkt @@ -253,8 +253,11 @@ def _error_result(error_category: str, error_message: str) -> str: }, ensure_ascii=False) -def _run_sql(sql: str, row_cap: int) -> str: - """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation.""" +def _run_sql(sql: str, row_cap: int | None) -> str: + """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation. + + row_cap=None means no ceiling: every returned row is passed through. + """ try: res = execute_query_sync(sql) except Exception as e: @@ -264,8 +267,9 @@ def _run_sql(sql: str, row_cap: int) -> str: return _error_result(_classify_trino_error(error_msg), error_msg) rows = res.rows or [] - truncated = len(rows) > row_cap - rows = rows[:row_cap] + truncated = row_cap is not None and len(rows) > row_cap + if truncated: + rows = rows[:row_cap] return json.dumps({ "success": True, "columns": res.columns, @@ -276,7 +280,7 @@ def _run_sql(sql: str, row_cap: int) -> str: @tool -def execute_trino_query(sql: str, limit: int = 50) -> str: +def execute_trino_query(sql: str, limit: int | None = None) -> str: """ Executes a read-only Trino SQL query and returns the resulting rows. @@ -285,8 +289,8 @@ def execute_trino_query(sql: str, limit: int = 50) -> str: multiple statements, SQL comments and TABLE(...) pass-through functions are rejected with error_category FORBIDDEN_STATEMENT. - Results are capped: an outer LIMIT is enforced automatically, and the response includes - 'truncated': true when more rows existed than were returned. + Results are capped at a configured row ceiling (when one is set): an outer LIMIT is enforced + automatically, and the response includes 'truncated': true when more rows existed than were returned. On failure, the response includes an 'error_category' field to help you classify and fix the error precisely: @@ -300,9 +304,10 @@ def execute_trino_query(sql: str, limit: int = 50) -> str: Args: sql (str): The exact Trino SQL query string to execute. Markdown fences and trailing semicolons are stripped automatically. - limit (int): The maximum number of rows to return (1–100). Defaults to 50. + limit (int, optional): Maximum number of rows to return. Defaults to the configured row + ceiling; a larger value is reduced to that ceiling. """ - row_cap = clamp(limit, 1, settings.DEEP_AGENT_MAX_ROWS, 50) + row_cap = effective_cap(limit, settings.DEEP_AGENT_MAX_ROWS) try: guarded = sql_guard.prepare(clean_sql(sql), row_cap) except sql_guard.GuardError as e: @@ -321,9 +326,9 @@ def get_sample_rows(table_name: str, limit: int = 5) -> str: Args: table_name (str): The fully qualified exact name of the table, e.g. '"catalog"."schema"."table"'. - limit (int): The number of rows to sample (1–10). Defaults to 5. + limit (int): The number of rows to sample. Defaults to 5 (bounded by the configured sample ceiling). """ - row_cap = clamp(limit, 1, settings.DEEP_AGENT_MAX_SAMPLE_ROWS, 5) + row_cap = effective_cap(limit if limit is not None else 5, settings.DEEP_AGENT_MAX_SAMPLE_ROWS) try: sql = sql_guard.sample_rows_sql(table_name, row_cap) except sql_guard.GuardError as e: @@ -351,9 +356,9 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 Args: table_name (str): The fully qualified exact name of the table. column_name (str): The exact name of the column (plain or double-quoted; spaces and Hebrew are fine). - limit (int): Maximum distinct values to return (1–100). Defaults to 50. + limit (int): Maximum distinct values to return. Defaults to 50 (bounded by the configured row ceiling). """ - row_cap = clamp(limit, 1, settings.DEEP_AGENT_MAX_ROWS, 50) + row_cap = effective_cap(limit if limit is not None else 50, settings.DEEP_AGENT_MAX_ROWS) try: sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) except sql_guard.GuardError as e: diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py index a60ffca..eee68d2 100644 --- a/agent/tests/deep_agent/test_trino_tools.py +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -36,6 +36,51 @@ def test_limit_argument_is_clamped_and_truncation_reported(trino): assert out["truncated"] is True +def test_omitted_limit_uses_the_configured_ceiling(trino, monkeypatch): + monkeypatch.setattr(tools.settings, "DEEP_AGENT_MAX_ROWS", 100) + trino.return_value = _ok(5) + tools.execute_trino_query.invoke({"sql": "SELECT id FROM t"}) + assert trino.call_args.args[0] == "SELECT id FROM t LIMIT 101" + + +def test_no_ceiling_runs_sql_as_written_and_returns_every_row(trino, monkeypatch): + monkeypatch.setattr(tools.settings, "DEEP_AGENT_MAX_ROWS", None) + trino.return_value = _ok(5000) + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t;"})) + assert trino.call_args.args[0] == "SELECT id FROM t" + assert out["row_count"] == 5000 + assert out["truncated"] is False + + +def test_no_ceiling_still_honours_an_explicit_limit(trino, monkeypatch): + monkeypatch.setattr(tools.settings, "DEEP_AGENT_MAX_ROWS", None) + trino.return_value = _ok(11) + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t", "limit": 10})) + assert trino.call_args.args[0] == "SELECT id FROM t LIMIT 11" + assert out["row_count"] == 10 + assert out["truncated"] is True + + +@pytest.mark.parametrize("raw", ["none", "None", "", "unlimited"]) +def test_row_ceiling_can_be_disabled_from_env(monkeypatch, raw): + from agent.config import AgentSettings + + monkeypatch.setenv("DEEP_AGENT_MAX_ROWS", raw) + monkeypatch.setenv("DEEP_AGENT_MAX_SAMPLE_ROWS", raw) + s = AgentSettings() + assert s.DEEP_AGENT_MAX_ROWS is None + assert s.DEEP_AGENT_MAX_SAMPLE_ROWS is None + + +def test_row_ceiling_defaults(monkeypatch): + from agent.config import AgentSettings + + monkeypatch.delenv("DEEP_AGENT_MAX_ROWS", raising=False) + monkeypatch.delenv("DEEP_AGENT_MAX_SAMPLE_ROWS", raising=False) + s = AgentSettings(_env_file=None) + assert (s.DEEP_AGENT_MAX_ROWS, s.DEEP_AGENT_MAX_SAMPLE_ROWS) == (100, 10) + + def test_speed_limit_column_still_gets_limit(trino): trino.return_value = _ok(3) out = json.loads(tools.execute_trino_query.invoke({"sql": "```sql\nSELECT speed_limit FROM t;\n```", "limit": 10})) diff --git a/agent/tests/test_sql_guard.py b/agent/tests/test_sql_guard.py index 79dabd4..9ba9ae4 100644 --- a/agent/tests/test_sql_guard.py +++ b/agent/tests/test_sql_guard.py @@ -3,7 +3,7 @@ from sqlglot import exp from agent.utils import sql_guard -from agent.utils.sql_guard import GuardError, clamp, distinct_values_sql, prepare, sample_rows_sql +from agent.utils.sql_guard import GuardError, distinct_values_sql, effective_cap, prepare, sample_rows_sql def _outer_limit(sql: str) -> int | None: @@ -63,13 +63,44 @@ def test_smaller_explicit_limit_is_kept(): "SELECT a FROM t UNION ALL SELECT a FROM u LIMIT 1000", "SELECT a FROM t FETCH FIRST 1000 ROWS ONLY", ]) -def test_set_operations_and_fetch_are_wrapped(sql): +def test_set_operations_and_fetch_get_the_cap(sql): guarded = prepare(sql, 10) + assert _outer_limit(guarded.sql) == 11 + + +def test_union_order_by_keeps_its_order(): + # Wrapping in SELECT * FROM (...) would let Trino drop the inner ORDER BY. + guarded = prepare("SELECT a FROM t UNION ALL SELECT a FROM u ORDER BY a", 10) tree = sqlglot.parse_one(guarded.sql, read="trino") - assert isinstance(tree, exp.Select) + assert isinstance(tree, exp.Union) + assert tree.args.get("order") is not None assert _outer_limit(guarded.sql) == 11 +@pytest.mark.parametrize("sql, rows", [ + ("SELECT a FROM t ORDER BY a FETCH FIRST 5 ROWS ONLY", 5), + ("SELECT a FROM t ORDER BY a FETCH FIRST 5 ROWS WITH TIES", 5), + ("SELECT a FROM t UNION ALL SELECT a FROM u ORDER BY a FETCH FIRST 3 ROWS ONLY", 3), +]) +def test_fetch_within_cap_is_kept_as_written(sql, rows): + guarded = prepare(sql, 100) + assert guarded.requested_limit == rows + assert guarded.sql == sql + + +def test_no_cap_runs_sql_exactly_as_written(): + sql = "SELECT a FROM t UNION ALL SELECT a FROM u ORDER BY a" + guarded = prepare(sql + ";", None) + assert guarded.sql == sql + assert guarded.row_cap is None + assert guarded.is_query + + +def test_no_cap_still_rejects_writes(): + with pytest.raises(GuardError): + prepare("DELETE FROM t", None) + + def test_string_literal_with_dashes_is_not_a_comment(): guarded = prepare("SELECT * FROM t WHERE code = 'a--b'", 10) assert "'a--b'" in guarded.sql @@ -86,10 +117,12 @@ def test_trailing_semicolon_is_accepted(): assert prepare("SELECT 1;", 10).is_query -def test_clamp(): - assert clamp(1_000_000, 1, 100, 50) == 100 - assert clamp(0, 1, 100, 50) == 1 - assert clamp(None, 1, 100, 50) == 50 +def test_effective_cap(): + assert effective_cap(1_000_000, 100) == 100 + assert effective_cap(0, 100) == 1 + assert effective_cap(None, 100) == 100 + assert effective_cap(None, None) is None + assert effective_cap(1_000_000, None) == 1_000_000 @pytest.mark.parametrize("table, expected", [ From 1b3e509ca3e5a77cd3ab487961337b5735bc9dd0 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 26 Oct 2026 15:49:38 +0200 Subject: [PATCH 09/37] fix(deep-agent): pass Trino's own errors through; honest validate_sql (#39, revised) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Based on deep-agent/39-trino-errors (aa55bf9), revised in review: - core: TrinoExecutionResult keeps Trino's structured error (error_name, error_type, error_code, error_location, query_id) and the clean message; query_id on success too - trino_errors.py passes Trino's errorName / errorType / message / location through unchanged — no category mapping, hints or keyword heuristics. Only two non-Trino names: FORBIDDEN_STATEMENT (SQL guard) and CONNECTION_ERROR (Trino unreachable / no structured error) - validate_sql_syntax renamed validate_sql: it runs EXPLAIN (TYPE VALIDATE), which checks syntax, names, types and signatures; returns JSON. Line-1 error_location columns are corrected for the EXPLAIN prefix (message raw) - prompt and AGENTS.md updated to error_name / validate_sql - agent installs core as an editable path dependency Co-Authored-By: Claude Opus 5.5 --- agent/pyproject.toml | 2 +- agent/src/deep_agent/agent.py | 12 +-- agent/src/deep_agent/memory/AGENTS.md | 6 +- agent/src/deep_agent/tools.py | 109 ++++++++----------- agent/src/deep_agent/trino_errors.py | 47 ++++++++ agent/tests/deep_agent/test_trino_errors.py | 114 ++++++++++++++++++++ agent/tests/deep_agent/test_trino_tools.py | 18 ++-- agent/tests/fixtures/trino_errors.json | 15 +++ agent/uv.lock | 4 +- core/src/core/trino.py | 21 +++- 10 files changed, 264 insertions(+), 84 deletions(-) create mode 100644 agent/src/deep_agent/trino_errors.py create mode 100644 agent/tests/deep_agent/test_trino_errors.py create mode 100644 agent/tests/fixtures/trino_errors.json diff --git a/agent/pyproject.toml b/agent/pyproject.toml index 05e327b..9e9fb98 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -31,7 +31,7 @@ dependencies = [ deep-agent = "deep_agent.cli:main" [tool.uv.sources] -core = { path = "../core" } +core = { path = "../core", editable = true } esca-sdk = { git = "https://github.com/elirazpevz/esca.git", subdirectory = "packages/esca-sdk" } [build-system] diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 96b3305..2eb57c8 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -23,7 +23,7 @@ search_knowledge_pairs, search_column_values, resolve_location_to_wkt, - validate_sql_syntax, + validate_sql, enrich_sql_filters, ) import datetime @@ -108,7 +108,7 @@ - Break complex or multi-step logic into named CTE blocks (e.g. `WITH filtered_data AS (...), aggregated_counts AS (...)`). - CTEs make queries significantly cleaner to read, prevent join fan-out (by aggregating child tables in a CTE before joining), and make window rankings (`ROW_NUMBER() / RANK()`) and multi-stage metrics easy to organize. - SQL uses ONLY confirmed 3-part table names: `"catalog"."schema"."table"` -- `validate_sql_syntax` — free, instant, catches typos and wrong function names. Always call before `execute_trino_query` on a fresh draft. +- `validate_sql` — Trino checks the draft without running it (syntax, table/column names, types, functions). Always call before `execute_trino_query` on a fresh draft. - `enrich_sql_filters` — run on any SQL that filters text columns --- @@ -116,7 +116,7 @@ ## Phase 5 — Execute & Diagnose - `execute_trino_query` — always LIMIT exploratory queries -- **Classify the error before retrying** (the response includes `error_category`): +- **Read the error before retrying** (the response includes Trino's `error_name`, `error_type` and `error_message`): - `SYNTAX_ERROR` → fix the specific line only, do not redesign - `TABLE_NOT_FOUND` / `COLUMN_NOT_FOUND` → re-verify exact identifiers from catalog - `TYPE_MISMATCH` → add `CAST(col AS type)` @@ -167,10 +167,10 @@ - `resolve_location_to_wkt` — Hebrew location → WKT polygon for `ST_GeometryFromText(...)` **Execution** -- `execute_trino_query` — runs SQL; response includes `error_category` on failure +- `execute_trino_query` — runs SQL; on failure the response carries Trino's `error_name` / `error_type` / `error_message` - `get_sample_rows` — peek at raw data format, string casing, date format - `get_column_distinct_values` — live distinct values. Appropriate for standard low-cardinality `categorical` columns (e.g. `launch_country`) when not listed in catalog. -- `validate_sql_syntax` — free dry-run. Call before every execute on a new draft. +- `validate_sql` — dry-run check by Trino, reads no data. Call before every execute on a new draft. **Post-processing** - `enrich_sql_filters` — AST-level auto-correction of categorical filter values. Use after drafting SQL with text filters. @@ -235,7 +235,7 @@ def create_deep_agent(model: BaseChatModel | None = None): execute_trino_query, get_sample_rows, get_column_distinct_values, - validate_sql_syntax, + validate_sql, # Post-processing enrich_sql_filters, ] diff --git a/agent/src/deep_agent/memory/AGENTS.md b/agent/src/deep_agent/memory/AGENTS.md index 9065340..1e54717 100644 --- a/agent/src/deep_agent/memory/AGENTS.md +++ b/agent/src/deep_agent/memory/AGENTS.md @@ -101,7 +101,7 @@ Understand what each tool supports and choose based on the column's `semantic_ty When SQL fails, classify the error **before** deciding what to fix: -| Error category | Targeted fix | +| Trino `error_name` / situation | Targeted fix | |---------------|-------------| | `SYNTAX_ERROR` | Fix the specific line only — do not redesign the query | | `TABLE_NOT_FOUND` | Re-verify the exact 3-part identifier from `get_database_catalog` | @@ -142,8 +142,8 @@ Before writing the final response, translate your SQL back to plain English and **Subagent delegation can keep your context clean.** If you need to explore many tables or profile many columns at once — delegate to a focused subagent via `task` and process the result. Don't exhaust your context on breadth-first exploration inline. -**`validate_sql_syntax` is free.** -Runs `EXPLAIN (TYPE VALIDATE)` — no data touched, instant. Call it before every `execute_trino_query` on a fresh draft. +**`validate_sql` is cheap.** +Runs `EXPLAIN (TYPE VALIDATE)` — Trino checks syntax, names and types without touching data. Call it before every `execute_trino_query` on a fresh draft. **Dumping distinct values on high-cardinality columns wastes latency and tokens.** For `large_categorical` or `large_unit_id` columns with hundreds or thousands of values, `get_column_distinct_values` returns a random slice of unrelated values. Always use `search_column_values` for targeted search on high-cardinality columns, and save `get_column_distinct_values` for low-cardinality categories. diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index af374d0..6f60f53 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -9,6 +9,7 @@ from agent.utils.jeen_metadata_client import get_jeen_metadata_client from agent.utils.sql import clean_sql from agent.utils.sql_guard import effective_cap +from deep_agent import trino_errors from core.trino import execute_query_sync from agent.services.geo_utils import get_geojson_polygon, geojson_to_simplified_wkt @@ -214,43 +215,8 @@ async def get_column_profile(table_name: str, column_name: str) -> str: # Query Execution # --------------------------------------------------------------------------- -def _classify_trino_error(error_message: str) -> str: - """Classify a Trino error message into an actionable category.""" - msg = error_message.lower() - if any(k in msg for k in ["syntax error", "mismatched input", "parse error", "unexpected"]): - return "SYNTAX_ERROR" - if any(k in msg for k in ["table not found", "schema not found", "catalog not found", "does not exist"]): - return "TABLE_NOT_FOUND" - if any(k in msg for k in ["column", "field", "not found in", "cannot resolve"]): - return "COLUMN_NOT_FOUND" - if any(k in msg for k in ["type mismatch", "cannot cast", "invalid cast", "expected", "varchar", "bigint", "double"]): - return "TYPE_MISMATCH" - if any(k in msg for k in ["function not found", "no function", "not a function"]): - return "FUNCTION_NOT_FOUND" - if any(k in msg for k in ["timeout", "exceeded", "resource", "query killed"]): - return "TIMEOUT_OR_RESOURCE" - return "EXECUTION_ERROR" - - -_HINTS = { - "SYNTAX_ERROR": "Fix the specific syntax line — do not redesign the entire query.", - "TABLE_NOT_FOUND": "Re-verify the exact 3-part table name from get_database_catalog.", - "COLUMN_NOT_FOUND": "Re-verify the column name from get_table_columns for this table.", - "TYPE_MISMATCH": "Add CAST(column AS target_type) for the mismatched column.", - "FUNCTION_NOT_FOUND": "Check Trino function spelling. E.g., use ST_GeometryFromText, not ST_GeomFromText.", - "TIMEOUT_OR_RESOURCE": "Add a tighter LIMIT or simplify the query.", - "FORBIDDEN_STATEMENT": "Only a single read-only SELECT/WITH (or SHOW/DESCRIBE) statement without comments is allowed.", - "EXECUTION_ERROR": "Investigate the specific error message.", -} - - -def _error_result(error_category: str, error_message: str) -> str: - return json.dumps({ - "success": False, - "error_category": error_category, - "error_message": error_message, - "hint": _HINTS.get(error_category, "Investigate the error message."), - }, ensure_ascii=False) +def _json(payload: dict) -> str: + return json.dumps(payload, ensure_ascii=False, default=str) def _run_sql(sql: str, row_cap: int | None) -> str: @@ -261,10 +227,9 @@ def _run_sql(sql: str, row_cap: int | None) -> str: try: res = execute_query_sync(sql) except Exception as e: - return _error_result("EXECUTION_ERROR", str(e)) + return _json(trino_errors.from_exception(e)) if not res.success: - error_msg = res.error_message or "Unknown error" - return _error_result(_classify_trino_error(error_msg), error_msg) + return _json(trino_errors.from_result(res)) rows = res.rows or [] truncated = row_cap is not None and len(rows) > row_cap @@ -276,6 +241,7 @@ def _run_sql(sql: str, row_cap: int | None) -> str: "row_count": len(rows), "truncated": truncated, "rows": rows, + "query_id": res.query_id, }, ensure_ascii=False, default=str) @@ -287,19 +253,19 @@ def execute_trino_query(sql: str, limit: int | None = None) -> str: Use this to test SQL queries against the actual database and perform exploratory data analysis. Only a single SELECT / WITH (or SHOW / DESCRIBE) statement is accepted; anything that writes, multiple statements, SQL comments and TABLE(...) pass-through functions are rejected with - error_category FORBIDDEN_STATEMENT. + error_name FORBIDDEN_STATEMENT. Results are capped at a configured row ceiling (when one is set): an outer LIMIT is enforced automatically, and the response includes 'truncated': true when more rows existed than were returned. - On failure, the response includes an 'error_category' field to help you classify and fix - the error precisely: - - SYNTAX_ERROR: fix the specific syntax — do not redesign the query - - TABLE_NOT_FOUND / COLUMN_NOT_FOUND: re-verify exact identifiers from the catalog - - TYPE_MISMATCH: add an explicit CAST(col AS type) - - FUNCTION_NOT_FOUND: check the Trino function name - - TIMEOUT_OR_RESOURCE: simplify the query or add a tighter LIMIT - - FORBIDDEN_STATEMENT: rewrite as a single read-only query without comments + On failure, the response carries Trino's own error, unmodified: + - error_name: Trino's error code (e.g. SYNTAX_ERROR, COLUMN_NOT_FOUND, TYPE_MISMATCH, + EXPRESSION_NOT_AGGREGATE, DIVISION_BY_ZERO) + - error_type: Trino's error class — USER_ERROR means the SQL itself is wrong; + INSUFFICIENT_RESOURCES, INTERNAL_ERROR and EXTERNAL come from the cluster or the source database + - error_message: Trino's message; error_location: {line, column} of the offending token + Two errors don't come from Trino: FORBIDDEN_STATEMENT (rejected before reaching Trino — rewrite + as a single read-only query without comments) and CONNECTION_ERROR (Trino could not be reached). Args: sql (str): The exact Trino SQL query string to execute. Markdown fences and trailing @@ -311,7 +277,7 @@ def execute_trino_query(sql: str, limit: int | None = None) -> str: try: guarded = sql_guard.prepare(clean_sql(sql), row_cap) except sql_guard.GuardError as e: - return _error_result("FORBIDDEN_STATEMENT", str(e)) + return _json(trino_errors.forbidden(str(e))) return _run_sql(guarded.sql, guarded.row_cap if guarded.is_query else settings.DEEP_AGENT_MAX_ROWS) @@ -332,7 +298,7 @@ def get_sample_rows(table_name: str, limit: int = 5) -> str: try: sql = sql_guard.sample_rows_sql(table_name, row_cap) except sql_guard.GuardError as e: - return _error_result("FORBIDDEN_STATEMENT", str(e)) + return _json(trino_errors.forbidden(str(e))) return _run_sql(sql, row_cap) @@ -362,7 +328,7 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 try: sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) except sql_guard.GuardError as e: - return _error_result("FORBIDDEN_STATEMENT", str(e)) + return _json(trino_errors.forbidden(str(e))) return _run_sql(sql, row_cap) @@ -371,13 +337,17 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 # --------------------------------------------------------------------------- @tool -def validate_sql_syntax(sql: str) -> str: +def validate_sql(sql: str) -> str: """ - Validates the syntax of a Trino SQL query without executing it against data. + Asks Trino to check a query without running it (EXPLAIN (TYPE VALIDATE)). Trino parses it and + resolves it against the catalog: syntax, table and column names, types and function signatures. + No data is read. + + Use this to dry-run a new draft before execute_trino_query. It cannot tell you whether the + query returns rows. - Use this to dry-run a query and instantly catch syntax errors (missing CASTs, typos, bad - function names). This is cheap — always call this before execute_trino_query on a new draft. - Do NOT use this to check if a query returns 0 rows; it only checks syntax validity. + Returns JSON: {"valid": true}, or {"valid": false, ...} with the same error fields as + execute_trino_query (error_name, error_type, error_message, error_location). Args: sql (str): The exact Trino SQL query string to validate. @@ -386,15 +356,26 @@ def validate_sql_syntax(sql: str) -> str: try: sql_guard.parse_read_statement(sql_clean) except sql_guard.GuardError as e: - return f"Syntax Error: {e}" + return _invalid(trino_errors.forbidden(str(e))) try: - res = execute_query_sync(f"EXPLAIN (TYPE VALIDATE) {sql_clean}") - if res.success: - return "Syntax is VALID." - else: - return f"Syntax Error: {res.error_message}" + res = execute_query_sync(f"{_VALIDATE_PREFIX}{sql_clean}") except Exception as e: - return f"Validation failed: {str(e)}" + return _invalid(trino_errors.from_exception(e)) + if res.success: + return _json({"valid": True}) + error = trino_errors.from_result(res) + location = error.get("error_location") + if location and location["line"] == 1: + # Trino counts columns from the start of "EXPLAIN (TYPE VALIDATE) ..."; report them against the caller's SQL. + location["column"] = max(1, location["column"] - len(_VALIDATE_PREFIX)) + return _invalid(error) + + +_VALIDATE_PREFIX = "EXPLAIN (TYPE VALIDATE) " + + +def _invalid(error: dict) -> str: + return _json({"valid": False, **{k: v for k, v in error.items() if k != "success"}}) # --------------------------------------------------------------------------- diff --git a/agent/src/deep_agent/trino_errors.py b/agent/src/deep_agent/trino_errors.py new file mode 100644 index 0000000..c740e0e --- /dev/null +++ b/agent/src/deep_agent/trino_errors.py @@ -0,0 +1,47 @@ +""" +Error payloads returned to the agent when SQL fails. + +Trino errors are passed through as Trino reported them (errorName, errorType, message, +location, query id) — no re-labelling. Two failures never get a Trino error and are +named here instead: + + FORBIDDEN_STATEMENT the SQL guard rejected the statement before it reached Trino + CONNECTION_ERROR Trino could not be reached / returned no structured error +""" + +from core.trino import TrinoExecutionResult + +FORBIDDEN_STATEMENT = "FORBIDDEN_STATEMENT" +CONNECTION_ERROR = "CONNECTION_ERROR" + + +def from_result(res: TrinoExecutionResult) -> dict: + """Error payload for a failed TrinoExecutionResult.""" + if res.error_name is None: + return _payload(CONNECTION_ERROR, None, res.error_message or "Unknown error") + return _payload(res.error_name, res.error_type, res.error_message or "", res.error_location, res.query_id) + + +def forbidden(message: str) -> dict: + """Error payload for SQL the guard rejected.""" + return _payload(FORBIDDEN_STATEMENT, None, message) + + +def from_exception(exc: Exception) -> dict: + """Error payload for an exception raised while calling Trino.""" + return _payload(CONNECTION_ERROR, None, str(exc)) + + +def _payload( + name: str, + error_type: str | None, + message: str, + location: tuple[int, int] | None = None, + query_id: str | None = None, +) -> dict: + out: dict = {"success": False, "error_name": name, "error_type": error_type, "error_message": message} + if location: + out["error_location"] = {"line": location[0], "column": location[1]} + if query_id: + out["query_id"] = query_id + return out diff --git a/agent/tests/deep_agent/test_trino_errors.py b/agent/tests/deep_agent/test_trino_errors.py new file mode 100644 index 0000000..c1d4bfa --- /dev/null +++ b/agent/tests/deep_agent/test_trino_errors.py @@ -0,0 +1,114 @@ +import json +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +import trino.exceptions + +import core.trino as core_trino +from core.trino import TrinoExecutionResult +from deep_agent import tools, trino_errors + +FIXTURES = json.loads((Path(__file__).parent.parent / "fixtures" / "trino_errors.json").read_text(encoding="utf-8")) + + +def _failing_connection(exc: Exception) -> MagicMock: + conn = MagicMock() + conn.cursor.return_value.execute.side_effect = exc + return conn + + +def _run_through_core(error: dict) -> TrinoExecutionResult: + exc = trino.exceptions.TrinoUserError(error, query_id="20261020_000000_00001_abcde") + with patch.object(core_trino.settings, "TRINO_ENABLED", True), \ + patch.object(core_trino, "get_trino_connection", return_value=_failing_connection(exc)): + return core_trino.execute_query_sync("SELECT 1") + + +@pytest.mark.parametrize("error", FIXTURES, ids=[e["errorName"] for e in FIXTURES]) +def test_trino_errors_are_passed_through_unchanged(error): + res = _run_through_core(error) + assert res.success is False + assert res.error_message == error["message"] # clean message, not the exception repr + assert res.query_id == "20261020_000000_00001_abcde" + + out = trino_errors.from_result(res) + assert out["error_name"] == error["errorName"] + assert out["error_type"] == error["errorType"] + assert out["error_message"] == error["message"] + location = error.get("errorLocation") + if location: + assert out["error_location"] == {"line": location["lineNumber"], "column": location["columnNumber"]} + else: + assert "error_location" not in out + + +def test_connection_failure_is_reported_as_connection_error(): + exc = ConnectionError("HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /v1/statement") + with patch.object(core_trino.settings, "TRINO_ENABLED", True), \ + patch.object(core_trino, "get_trino_connection", return_value=_failing_connection(exc)): + res = core_trino.execute_query_sync("SELECT 1") + out = trino_errors.from_result(res) + assert out["error_name"] == "CONNECTION_ERROR" + assert out["error_type"] is None + assert "Max retries exceeded" in out["error_message"] + + +def test_execute_tool_returns_trinos_error(): + res = TrinoExecutionResult( + success=False, error_message="line 1:8: Function 'st_geomfromtext' not registered", + error_name="FUNCTION_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 8), query_id="q1", + ) + with patch.object(tools, "execute_query_sync", return_value=res): + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT ST_GeomFromText('POINT(1 1)')"})) + assert out == { + "success": False, + "error_name": "FUNCTION_NOT_FOUND", + "error_type": "USER_ERROR", + "error_message": "line 1:8: Function 'st_geomfromtext' not registered", + "error_location": {"line": 1, "column": 8}, + "query_id": "q1", + } + + +def test_execute_tool_reports_exceptions_as_connection_error(): + with patch.object(tools, "execute_query_sync", side_effect=OSError("connection refused")): + out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT 1"})) + assert out["error_name"] == "CONNECTION_ERROR" + assert out["error_message"] == "connection refused" + + +def test_validate_returns_trinos_error(): + res = TrinoExecutionResult( + success=False, error_message="line 1:32: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 32), + ) + with patch.object(tools, "execute_query_sync", return_value=res): + out = json.loads(tools.validate_sql.invoke({"sql": "SELECT x FROM t"})) + assert out["valid"] is False + assert out["error_name"] == "COLUMN_NOT_FOUND" + assert out["error_type"] == "USER_ERROR" + assert "success" not in out + + + +def test_validate_reports_location_against_the_callers_sql(): + # Trino sees "EXPLAIN (TYPE VALIDATE) SELECT x FROM t"; 'x' is at column 32 there, column 8 in the caller's SQL. + res = TrinoExecutionResult( + success=False, error_message="line 1:32: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 32), + ) + with patch.object(tools, "execute_query_sync", return_value=res): + out = json.loads(tools.validate_sql.invoke({"sql": "SELECT x FROM t"})) + assert out["error_location"] == {"line": 1, "column": 8} + assert out["error_message"] == "line 1:32: Column 'x' cannot be resolved" # Trino's message stays raw + + +def test_validate_leaves_later_lines_alone(): + res = TrinoExecutionResult( + success=False, error_message="line 3:7: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(3, 7), + ) + with patch.object(tools, "execute_query_sync", return_value=res): + out = json.loads(tools.validate_sql.invoke({"sql": "SELECT a\nFROM t\nWHERE x = 1"})) + assert out["error_location"] == {"line": 3, "column": 7} diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py index eee68d2..90bf0ed 100644 --- a/agent/tests/deep_agent/test_trino_tools.py +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -23,7 +23,7 @@ def trino(): def test_forbidden_sql_never_reaches_trino(trino, sql): out = json.loads(tools.execute_trino_query.invoke({"sql": sql})) assert out["success"] is False - assert out["error_category"] == "FORBIDDEN_STATEMENT" + assert out["error_name"] == "FORBIDDEN_STATEMENT" trino.assert_not_called() @@ -90,9 +90,12 @@ def test_speed_limit_column_still_gets_limit(trino): def test_trino_error_is_reported(trino): - trino.return_value = TrinoExecutionResult(success=False, error_message="line 1:8: Column 'x' cannot be resolved") + trino.return_value = TrinoExecutionResult( + success=False, error_message="line 1:8: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", + ) out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT x FROM t"})) - assert out["error_category"] == "COLUMN_NOT_FOUND" + assert out["error_name"] == "COLUMN_NOT_FOUND" def test_sample_rows_handles_hebrew_quoted_table(trino): @@ -103,7 +106,7 @@ def test_sample_rows_handles_hebrew_quoted_table(trino): def test_sample_rows_rejects_injection(trino): out = json.loads(tools.get_sample_rows.invoke({"table_name": "t; DROP TABLE t"})) - assert out["error_category"] == "FORBIDDEN_STATEMENT" + assert out["error_name"] == "FORBIDDEN_STATEMENT" trino.assert_not_called() @@ -114,12 +117,13 @@ def test_distinct_values_quotes_hebrew_column(trino): def test_validate_rejects_writes_without_calling_trino(trino): - out = tools.validate_sql_syntax.invoke({"sql": "DELETE FROM t"}) - assert out.startswith("Syntax Error:") + out = json.loads(tools.validate_sql.invoke({"sql": "DELETE FROM t"})) + assert out["valid"] is False + assert out["error_name"] == "FORBIDDEN_STATEMENT" trino.assert_not_called() def test_validate_runs_explain_for_reads(trino): trino.return_value = _ok(0) - assert tools.validate_sql_syntax.invoke({"sql": "SELECT 1"}) == "Syntax is VALID." + assert json.loads(tools.validate_sql.invoke({"sql": "SELECT 1"})) == {"valid": True} assert trino.call_args.args[0] == "EXPLAIN (TYPE VALIDATE) SELECT 1" diff --git a/agent/tests/fixtures/trino_errors.json b/agent/tests/fixtures/trino_errors.json new file mode 100644 index 0000000..1183feb --- /dev/null +++ b/agent/tests/fixtures/trino_errors.json @@ -0,0 +1,15 @@ +[ + {"message": "line 1:8: Function 'st_geomfromtext' not registered", "errorCode": 44, "errorName": "FUNCTION_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "line 1:8: Unexpected parameters (varchar(10), integer) for function date_parse. Expected: date_parse(varchar(x), varchar(y))", "errorCode": 44, "errorName": "FUNCTION_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "line 1:8: Column 'fligth_id' cannot be resolved", "errorCode": 47, "errorName": "COLUMN_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "line 1:15: Table 'postgres.public.flight' does not exist", "errorCode": 46, "errorName": "TABLE_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 15}}, + {"message": "line 1:15: Schema 'pubic' does not exist", "errorCode": 45, "errorName": "SCHEMA_NOT_FOUND", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 15}}, + {"message": "line 1:1: mismatched input 'SELEC'. Expecting: 'ALTER', 'ANALYZE', 'CALL', 'SELECT', 'WITH'", "errorCode": 1, "errorName": "SYNTAX_ERROR", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 1}}, + {"message": "line 3:5: Cannot apply operator: timestamp(3) = varchar(10)", "errorCode": 58, "errorName": "TYPE_MISMATCH", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 3, "columnNumber": 5}}, + {"message": "line 1:8: 'city_name' must be an aggregate expression or appear in GROUP BY clause", "errorCode": 2, "errorName": "EXPRESSION_NOT_AGGREGATE", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "Division by zero", "errorCode": 8, "errorName": "DIVISION_BY_ZERO", "errorType": "USER_ERROR"}, + {"message": "line 1:8: Column 'city_code' is ambiguous", "errorCode": 18, "errorName": "AMBIGUOUS_NAME", "errorType": "USER_ERROR", "errorLocation": {"lineNumber": 1, "columnNumber": 8}}, + {"message": "Value cannot be cast to timestamp: 2026-06-01T10:00:00Z", "errorCode": 9, "errorName": "INVALID_CAST_ARGUMENT", "errorType": "USER_ERROR"}, + {"message": "Query exceeded per-node memory limit of 1GB [Allocated: 1.00GB]", "errorCode": 131079, "errorName": "EXCEEDED_LOCAL_MEMORY_LIMIT", "errorType": "INSUFFICIENT_RESOURCES"}, + {"message": "Error opening Hive split: connection reset", "errorCode": 16777216, "errorName": "GENERIC_INTERNAL_ERROR", "errorType": "INTERNAL_ERROR"} +] diff --git a/agent/uv.lock b/agent/uv.lock index cfcae1a..a9409bc 100644 --- a/agent/uv.lock +++ b/agent/uv.lock @@ -40,7 +40,7 @@ dev = [ [package.metadata] requires-dist = [ - { name = "core", directory = "../core" }, + { name = "core", editable = "../core" }, { name = "deepagents", specifier = ">=0.6.12" }, { name = "esca-sdk", git = "https://github.com/elirazpevz/esca.git?subdirectory=packages%2Fesca-sdk" }, { name = "fastapi", specifier = ">=0.115.6" }, @@ -259,7 +259,7 @@ wheels = [ [[package]] name = "core" version = "0.1.0" -source = { directory = "../core" } +source = { editable = "../core" } dependencies = [ { name = "alembic" }, { name = "langchain" }, diff --git a/core/src/core/trino.py b/core/src/core/trino.py index 34e1aa7..13e356a 100644 --- a/core/src/core/trino.py +++ b/core/src/core/trino.py @@ -7,6 +7,7 @@ from typing import Any import trino +import trino.exceptions from pydantic import BaseModel import urllib3 from core.config import settings @@ -25,6 +26,12 @@ class TrinoExecutionResult(BaseModel): row_count: int = 0 execution_time_ms: int = 0 error_message: str | None = None + # Structured Trino error details (populated from trino.exceptions.TrinoQueryError) + error_name: str | None = None # e.g. SYNTAX_ERROR, COLUMN_NOT_FOUND, FUNCTION_NOT_FOUND + error_type: str | None = None # USER_ERROR | INSUFFICIENT_RESOURCES | INTERNAL_ERROR | EXTERNAL + error_code: int | None = None + error_location: tuple[int, int] | None = None # (line, column) of the offending token + query_id: str | None = None def get_trino_connection(): @@ -79,6 +86,7 @@ def execute_query_sync(sql: str, table_id: str = "", params: tuple | dict | list cur.execute(sql) rows = cur.fetchall() columns = [desc[0] for desc in cur.description] if cur.description else [] + query_id = getattr(cur, "query_id", None) execution_time_ms = int((time.time() - start_time) * 1000) logger.info(f"[CoreTrinoClient] OK — {len(rows)} rows in {execution_time_ms}ms") cur.close() @@ -89,6 +97,7 @@ def execute_query_sync(sql: str, table_id: str = "", params: tuple | dict | list columns=columns, row_count=len(rows), execution_time_ms=execution_time_ms, + query_id=query_id, ) except Exception as exc: execution_time_ms = int((time.time() - start_time) * 1000) @@ -103,11 +112,21 @@ def execute_query_sync(sql: str, table_id: str = "", params: tuple | dict | list conn.close() except: pass + details: dict[str, Any] = {} + if isinstance(exc, trino.exceptions.TrinoQueryError): + details = { + "error_message": exc.message, + "error_name": exc.error_name, + "error_type": exc.error_type, + "error_code": exc.error_code, + "error_location": exc.error_location, + "query_id": exc.query_id, + } return TrinoExecutionResult( success=False, rows=[], columns=[], row_count=0, execution_time_ms=execution_time_ms, - error_message=str(exc), + **{"error_message": str(exc), **details}, ) From 016dfbc074c5d8c8f507b8712ad5e4de2f66edc4 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 26 Oct 2026 16:12:48 +0200 Subject: [PATCH 10/37] refactor(deep-agent): one tool envelope, surface MCP errors, compact value search (#45, revised) Based on deep-agent/45-tool-contracts (5e89569), revised in review: - envelope.py: every tool returns {ok, data, error}; error = {name, message, ...details}. error.name is Trino's own code for SQL failures (#39) or one of METADATA_ERROR / NOT_FOUND / INVALID_INPUT / ENRICHMENT_ERROR / LOCATION_NOT_FOUND for our tools. No category/hint layer. - Jeen client: honour MCP isError and unexpected payloads by raising JeenMetadataError instead of returning []/None/{"error"}; METADATA_ERROR tells the model the data is not necessarily empty - get_database_catalog stays plain text (no JSON escaping of the catalog) - search_column_values: no duplicated payload, all matches returned, no prefix guessing, limit passed through unclamped - resolve_location_to_wkt returns the polygon once (data.wkt, unquoted) - DEEP_AGENT_TOOLS defined once; dead code removed; ruff (pyflakes) on deep_agent via lint-staged Co-Authored-By: Claude Opus 5.5 --- agent/src/agent/utils/jeen_metadata_client.py | 67 ++- agent/src/deep_agent/agent.py | 54 +-- agent/src/deep_agent/envelope.py | 37 ++ agent/src/deep_agent/tools.py | 427 +++++++++--------- agent/src/deep_agent/trino_errors.py | 39 +- agent/tests/deep_agent/test_tool_contracts.py | 213 +++++++++ agent/tests/deep_agent/test_trino_errors.py | 49 +- agent/tests/deep_agent/test_trino_tools.py | 30 +- package.json | 3 + 9 files changed, 562 insertions(+), 357 deletions(-) create mode 100644 agent/src/deep_agent/envelope.py create mode 100644 agent/tests/deep_agent/test_tool_contracts.py diff --git a/agent/src/agent/utils/jeen_metadata_client.py b/agent/src/agent/utils/jeen_metadata_client.py index 89f8415..84023c5 100644 --- a/agent/src/agent/utils/jeen_metadata_client.py +++ b/agent/src/agent/utils/jeen_metadata_client.py @@ -43,7 +43,7 @@ import json import logging -from typing import Any +from typing import Any, NoReturn from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client @@ -53,6 +53,10 @@ logger = logging.getLogger(__name__) +class JeenMetadataError(RuntimeError): + """The MCP server reported an error, or returned a payload of an unexpected shape.""" + + # --------------------------------------------------------------------------- # Low-level MCP call helper # --------------------------------------------------------------------------- @@ -90,11 +94,11 @@ async def _call_mcp_tool( # result.content is a list of ContentBlock objects. # We expect the first (and only) block to be a TextContent. - if not result.content: - return {} - - first = result.content[0] + first = result.content[0] if result.content else None text = getattr(first, "text", None) + + if getattr(result, "isError", False): + raise JeenMetadataError(f"MCP tool '{tool_name}' failed: {text or 'no error details'}") if text is None: return {} @@ -104,6 +108,21 @@ async def _call_mcp_tool( return text +def _reraise_as_metadata_error(exc: Exception) -> NoReturn: + if isinstance(exc, JeenMetadataError): + raise exc + raise JeenMetadataError(str(exc)) from exc + + +def _expect_list(payload: Any, key: str, method: str) -> list[dict[str, Any]]: + """Unwrap a list payload (bare or under `key`); anything else is an error, never an empty result.""" + if isinstance(payload, dict) and key in payload: + payload = payload[key] + if isinstance(payload, list): + return payload + raise JeenMetadataError(f"{method} returned unexpected payload: {str(payload)[:300]}") + + # --------------------------------------------------------------------------- # Public client façade # --------------------------------------------------------------------------- @@ -186,7 +205,11 @@ async def search_column_values( try: payload = await self._call("search_column_values", args) if raw: - return payload if isinstance(payload, dict) else {"values": payload} + if isinstance(payload, dict): + return payload + if isinstance(payload, list): + return {"values": payload} + raise JeenMetadataError(f"search_column_values returned unexpected payload: {str(payload)[:300]}") if isinstance(payload, dict) and "values" in payload: results = [] @@ -201,7 +224,9 @@ async def search_column_values( return [] except Exception as exc: logger.error("JeenMetadataClient.search_column_values failed: %s", exc, exc_info=True) - return [] if not raw else {"error": str(exc)} + if raw: + _reraise_as_metadata_error(exc) + return [] # ------------------------------------------------------------------ # Glossary / Context @@ -348,12 +373,14 @@ async def get_column_profile(self, table_name: str, column_name: str) -> dict[st "column_name": column_name, }, ) - if isinstance(res, dict): - return res.get("profile") or res - return None except Exception as exc: logger.error("JeenMetadataClient.get_column_profile failed: %s", exc) - return None + _reraise_as_metadata_error(exc) + if isinstance(res, dict): + return res.get("profile") or res + if isinstance(res, str) and res.strip(): + raise JeenMetadataError(f"get_column_profile returned unexpected payload: {res[:300]}") + return None # ------------------------------------------------------------------ # Prompt & Scoping Tools @@ -385,9 +412,7 @@ async def get_tables(self, connection_id: int | None = None) -> list[dict[str, A """ cid = connection_id if connection_id is not None else self._connection_id res = await self._call("get_tables", {"connection_id": cid}) - if isinstance(res, dict) and "tables" in res: - return res["tables"] - return res if isinstance(res, list) else [] + return _expect_list(res, "tables", "get_tables") async def get_columns(self, table_name: str | None = None, connection_id: int | None = None) -> list[dict[str, Any]]: """ @@ -398,9 +423,7 @@ async def get_columns(self, table_name: str | None = None, connection_id: int | if table_name: args["table_name"] = table_name res = await self._call("get_columns", args) - if isinstance(res, dict) and "columns" in res: - return res["columns"] - return res if isinstance(res, list) else [] + return _expect_list(res, "columns", "get_columns") async def get_relationships(self, connection_id: int | None = None) -> list[dict[str, Any]]: """ @@ -408,9 +431,7 @@ async def get_relationships(self, connection_id: int | None = None) -> list[dict """ cid = connection_id if connection_id is not None else self._connection_id res = await self._call("get_relationships", {"connection_id": cid}) - if isinstance(res, dict) and "relationships" in res: - return res["relationships"] - return res if isinstance(res, list) else [] + return _expect_list(res, "relationships", "get_relationships") async def get_source_statistics(self, connection_id: int | None = None) -> dict[str, Any]: """ @@ -479,7 +500,7 @@ async def search(self, query: str, limit: int = 10) -> Any: return await self._call("search", {"connection_id": self._connection_id, "query": query, "limit": limit}) except Exception as exc: logger.error("search failed: %s", exc) - return {"error": str(exc)} + _reraise_as_metadata_error(exc) async def search_business_terms(self, query: str, limit: int = 10) -> Any: """Finds business glossary terms relevant to a question.""" @@ -487,7 +508,7 @@ async def search_business_terms(self, query: str, limit: int = 10) -> Any: return await self._call("search_business_terms", {"connection_id": self._connection_id, "query": query, "limit": limit}) except Exception as exc: logger.error("search_business_terms failed: %s", exc) - return {"error": str(exc)} + _reraise_as_metadata_error(exc) async def search_knowledge_pairs(self, query: str, limit: int = 10) -> Any: """Finds saved question-and-query examples.""" @@ -495,7 +516,7 @@ async def search_knowledge_pairs(self, query: str, limit: int = 10) -> Any: return await self._call("search_knowledge_pairs", {"connection_id": self._connection_id, "query": query, "limit": limit}) except Exception as exc: logger.error("search_knowledge_pairs failed: %s", exc) - return {"error": str(exc)} + _reraise_as_metadata_error(exc) # --------------------------------------------------------------------------- diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 2eb57c8..14cff85 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -2,33 +2,15 @@ Agent logic and LangGraph harness for the Deep Agent. """ +import datetime + from deepagents import create_deep_agent as create_harness_agent from langchain_core.language_models import BaseChatModel from langgraph.checkpoint.memory import MemorySaver -from deep_agent.tools import ( - get_database_catalog, - # get_filtered_prompt, - # resolve_question, - get_database_tables, - get_table_columns, - get_table_relationships, - get_table_profile, - get_column_profile, - execute_trino_query, - get_sample_rows, - get_column_distinct_values, - search_metadata, - search_business_terms, - search_knowledge_pairs, - search_column_values, - resolve_location_to_wkt, - validate_sql, - enrich_sql_filters, -) -import datetime from agent.llm import get_llm from deep_agent.resources import build_resources +from deep_agent.tools import DEEP_AGENT_TOOLS SYSTEM_PROMPT = """You are an elite, autonomous Deep SQL Analyst. Your mission: translate Hebrew natural-language questions into verified Trino SQL that is **semantically correct** — not just syntactically valid or merely executable. @@ -116,7 +98,7 @@ ## Phase 5 — Execute & Diagnose - `execute_trino_query` — always LIMIT exploratory queries -- **Read the error before retrying** (the response includes Trino's `error_name`, `error_type` and `error_message`): +- Every tool returns `{{"ok", "data", "error"}}` — check `ok` first (`get_database_catalog` returns the catalog as plain text). **Read the error before retrying**: for SQL, `error.name` / `error.type` / `error.message` are Trino's own, and `error.location` points at the offending token: - `SYNTAX_ERROR` → fix the specific line only, do not redesign - `TABLE_NOT_FOUND` / `COLUMN_NOT_FOUND` → re-verify exact identifiers from catalog - `TYPE_MISMATCH` → add `CAST(col AS type)` @@ -167,7 +149,7 @@ - `resolve_location_to_wkt` — Hebrew location → WKT polygon for `ST_GeometryFromText(...)` **Execution** -- `execute_trino_query` — runs SQL; on failure the response carries Trino's `error_name` / `error_type` / `error_message` +- `execute_trino_query` — runs SQL; on failure `error` carries Trino's own `name` / `type` / `message` - `get_sample_rows` — peek at raw data format, string casing, date format - `get_column_distinct_values` — live distinct values. Appropriate for standard low-cardinality `categorical` columns (e.g. `launch_country`) when not listed in catalog. - `validate_sql` — dry-run check by Trino, reads no data. Call before every execute on a new draft. @@ -216,37 +198,13 @@ def create_deep_agent(model: BaseChatModel | None = None): model: Chat model override (tests); defaults to the configured LLM. """ llm = model or get_llm() - - tools = [ - # Discovery & Schema - get_database_catalog, - get_database_tables, - get_table_columns, - get_table_relationships, - get_table_profile, - get_column_profile, - # Search & Resolve - search_metadata, - search_business_terms, - search_knowledge_pairs, - search_column_values, - resolve_location_to_wkt, - # Query Execution - execute_trino_query, - get_sample_rows, - get_column_distinct_values, - validate_sql, - # Post-processing - enrich_sql_filters, - ] - memory = MemorySaver() today = datetime.date.today().isoformat() resources = build_resources() agent = create_harness_agent( model=llm, - tools=tools, + tools=DEEP_AGENT_TOOLS, system_prompt=SYSTEM_PROMPT.format(today=today), checkpointer=memory, backend=resources.backend, diff --git a/agent/src/deep_agent/envelope.py b/agent/src/deep_agent/envelope.py new file mode 100644 index 0000000..b811460 --- /dev/null +++ b/agent/src/deep_agent/envelope.py @@ -0,0 +1,37 @@ +""" +The single return contract for every Deep Agent tool: + + {"ok": true, "data": , "error": null} + {"ok": false, "data": null, "error": {"name", "message", ...details}} + +error.name is Trino's own errorName for SQL failures (see deep_agent.trino_errors), or one of +the names below for failures of our own tools. + +Serialised compactly (no indentation whitespace, raw Unicode) to keep tool output tokens low. +""" + +import json +from typing import Any + +METADATA_ERROR = "METADATA_ERROR" # the Jeen metadata service failed or returned an unexpected payload +NOT_FOUND = "NOT_FOUND" # the metadata service has nothing stored for the requested object +INVALID_INPUT = "INVALID_INPUT" # the tool arguments could not be used +ENRICHMENT_ERROR = "ENRICHMENT_ERROR" # filter enrichment failed; the SQL is unchanged +LOCATION_NOT_FOUND = "LOCATION_NOT_FOUND" # the location could not be resolved to an area + + +def _dumps(payload: dict) -> str: + return json.dumps(payload, ensure_ascii=False, separators=(",", ":"), default=str) + + +def ok(data: Any) -> str: + return _dumps({"ok": True, "data": data, "error": None}) + + +def error(name: str, message: str, **details: Any) -> dict: + """An `error` object: name + message, plus any details that are not None.""" + return {"name": name, "message": message, **{k: v for k, v in details.items() if v is not None}} + + +def fail(err: dict) -> str: + return _dumps({"ok": False, "data": None, "error": err}) diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 6f60f53..eed245b 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -1,17 +1,34 @@ -import json +""" +Deep Agent tools. + +Every tool returns the same JSON envelope (see deep_agent.envelope): + {"ok": true, "data": ..., "error": null} | {"ok": false, "data": null, "error": {"name", "message", ...}} +except get_database_catalog, whose success result is the catalog itself as plain text. +""" + import logging -import asyncio -from typing import Optional +from typing import Any, Optional + from langchain_core.tools import tool from agent.config import settings +from agent.services.geo_utils import geojson_to_simplified_wkt, get_geojson_polygon from agent.utils import sql_guard from agent.utils.jeen_metadata_client import get_jeen_metadata_client from agent.utils.sql import clean_sql from agent.utils.sql_guard import effective_cap -from deep_agent import trino_errors from core.trino import execute_query_sync -from agent.services.geo_utils import get_geojson_polygon, geojson_to_simplified_wkt +from deep_agent import trino_errors +from deep_agent.envelope import ( + ENRICHMENT_ERROR, + INVALID_INPUT, + LOCATION_NOT_FOUND, + METADATA_ERROR, + NOT_FOUND, + error, + fail, + ok, +) logger = logging.getLogger(__name__) @@ -28,6 +45,14 @@ } +def _metadata_failure(what: str, exc: Exception) -> str: + logger.warning("%s failed: %s", what, exc) + return fail(error( + METADATA_ERROR, + f"{what} failed: {exc}. The metadata service failed — this does not mean the data is empty.", + )) + + @tool async def get_database_catalog() -> str: """ @@ -36,82 +61,39 @@ async def get_database_catalog() -> str: Use this FIRST when starting any new query to discover what tables exist, how they relate, and to see column profiling statistics including semantic types, null ratios, and distinct counts. - The output includes Column/Table Names, Descriptions, Types, Universal Base Metrics (Null Rate, - Distinct Count, Cardinality Ratio) and specific Profiling Data Payloads. + On success the result is the catalog as plain text (not JSON): Column/Table Names, Descriptions, + Types, Universal Base Metrics (Null Rate, Distinct Count, Cardinality Ratio) and specific Profiling + Data Payloads, followed by a note on which discovery sources exist for this connection. + On failure it is the usual JSON envelope with ok=false. Column semantic_type values to watch for: - - 'categorical' — small finite value set; use search_column_values to resolve exact spellings. - - 'large_categorical' — too many values to enumerate; use search_column_values with query terms. + - 'categorical' — small finite value set; values are in the catalog or via get_column_distinct_values. + - 'large_categorical' / 'large_unit_id' — too many values to enumerate; use search_column_values. - 'geo' — WKT geometry column; use resolve_location_to_wkt to build filter values. Do NOT use this to fetch live data rows; this only retrieves metadata and schema definitions. """ - client = get_jeen_metadata_client() try: - catalog_prompt = await client.get_catalog_prompt() - - lower_prompt = catalog_prompt.lower() - has_kp = "(no knowledge pairs)" not in lower_prompt - has_bt = "(no business terms)" not in lower_prompt - has_fk = "(no relationships)" not in lower_prompt - - _connection_capabilities["has_knowledge_pairs"] = has_kp - _connection_capabilities["has_business_terms"] = has_bt - _connection_capabilities["has_relationships"] = has_fk - - footer_lines = [ - "\n\n---", - "### Discovery Capabilities Note:", - f"- Knowledge Pairs: {'Available' if has_kp else 'None (skip search_knowledge_pairs)'}", - f"- Business Terms: {'Available' if has_bt else 'None (skip search_business_terms)'}", - f"- Foreign Keys: {'Available' if has_fk else 'None (infer joins from column names)'}", - ] - return catalog_prompt + "\n".join(footer_lines) + catalog_prompt = await get_jeen_metadata_client().get_catalog_prompt() except Exception as e: - return f"Error fetching catalog: {str(e)}" - - -# @tool -# async def get_filtered_prompt(question: str) -> str: -# """ -# Retrieves a narrowed, highly focused catalog prompt scoped specifically to the user's question. -# Contains the AI-selected most relevant columns, primary keys, foreign key joins, and relevant -# knowledge pairs / business terms. - -# Use this when you want a compact, fast overview of just the tables and columns relevant to -# the current question without reading the massive full database catalog. - -# Args: -# question (str): The natural language question (Hebrew or English). -# """ -# client = get_jeen_metadata_client() -# try: -# res = await client.get_filtered_prompt(question) -# if isinstance(res, dict) and "prompt" in res: -# return res["prompt"] -# return json.dumps(res, indent=2, ensure_ascii=False) -# except Exception as e: -# return f"Error fetching filtered prompt: {e}" - - -# @tool -# async def resolve_question(question: str) -> str: -# """ -# Explains how a question maps onto this connection's curated vocabulary: -# which glossary terms, synonyms, acronyms, tables and columns it mentions and what they resolve to. - -# Use this when encountering ambiguous domain abbreviations, jargon, or Hebrew concepts to -# see the curated glossary and lexicon mappings. - -# Args: -# question (str): The natural language question or phrase in Hebrew or English. -# """ -# client = get_jeen_metadata_client() -# try: -# res = await client.resolve_question(question) -# return json.dumps(res, indent=2, ensure_ascii=False) -# except Exception as e: -# return f"Error resolving question: {e}" + return _metadata_failure("get_database_catalog", e) + + lower_prompt = catalog_prompt.lower() + has_kp = "(no knowledge pairs)" not in lower_prompt + has_bt = "(no business terms)" not in lower_prompt + has_fk = "(no relationships)" not in lower_prompt + _connection_capabilities["has_knowledge_pairs"] = has_kp + _connection_capabilities["has_business_terms"] = has_bt + _connection_capabilities["has_relationships"] = has_fk + + footer_lines = [ + "\n\n---", + "### Discovery Capabilities Note:", + f"- Knowledge Pairs: {'Available' if has_kp else 'None (skip search_knowledge_pairs)'}", + f"- Business Terms: {'Available' if has_bt else 'None (skip search_business_terms)'}", + f"- Foreign Keys: {'Available' if has_fk else 'None (infer joins from column names)'}", + ] + return catalog_prompt + "\n".join(footer_lines) @tool @@ -121,12 +103,10 @@ async def get_database_tables() -> str: exact quoted identifiers ("catalog"."schema"."table") for querying. Use this for a quick, clean roster of available tables. """ - client = get_jeen_metadata_client() try: - tables = await client.get_tables() - return json.dumps(tables, indent=2, ensure_ascii=False) + return ok(await get_jeen_metadata_client().get_tables()) except Exception as e: - return f"Error fetching tables: {e}" + return _metadata_failure("get_database_tables", e) @tool @@ -138,12 +118,10 @@ async def get_table_columns(table_name: str) -> str: Args: table_name (str): The table identifier (e.g. '"postgres"."public"."flights_table"' or 'flights_table'). """ - client = get_jeen_metadata_client() try: - cols = await client.get_columns(table_name) - return json.dumps(cols, indent=2, ensure_ascii=False) + return ok(await get_jeen_metadata_client().get_columns(table_name)) except Exception as e: - return f"Error fetching columns for {table_name}: {e}" + return _metadata_failure(f"get_table_columns({table_name})", e) @tool @@ -153,13 +131,14 @@ async def get_table_relationships() -> str: Use this to identify exact join paths and foreign key pairs. """ if not _connection_capabilities.get("has_relationships", True): - return "[] (Notice: This connection has NO foreign key relationships defined in the catalog. Infer joins using matching column names, e.g. flight_id.)" - client = get_jeen_metadata_client() + return ok({ + "relationships": [], + "notice": "This connection has NO foreign key relationships defined. Infer joins using matching column names, e.g. flight_id.", + }) try: - rels = await client.get_relationships() - return json.dumps(rels, indent=2, ensure_ascii=False) + return ok({"relationships": await get_jeen_metadata_client().get_relationships()}) except Exception as e: - return f"Error fetching relationships: {e}" + return _metadata_failure("get_table_relationships", e) @tool @@ -175,14 +154,13 @@ async def get_table_profile(table_name: str) -> str: table_name (str): The fully qualified, exact 3-part name of the table, e.g., '"catalog"."schema"."table"'. """ - client = get_jeen_metadata_client() try: - profile = await client.get_table_profile(table_name) - if not profile: - return f"Error: Schema not found for table {table_name}" - return json.dumps(profile, indent=2, ensure_ascii=False) + profile = await get_jeen_metadata_client().get_table_profile(table_name) except Exception as e: - return f"Error fetching table schema: {str(e)}" + return _metadata_failure(f"get_table_profile({table_name})", e) + if not profile: + return fail(error(NOT_FOUND, f"No stored profile for table {table_name}")) + return ok(profile) @tool @@ -201,24 +179,19 @@ async def get_column_profile(table_name: str, column_name: str) -> str: table_name (str): The fully qualified exact name of the table, e.g., '"catalog"."schema"."table"'. column_name (str): The exact name of the column to profile. """ - client = get_jeen_metadata_client() try: - profile = await client.get_column_profile(table_name, column_name) - if not profile: - return f"Error: Column profile not found for {table_name}.{column_name}" - return json.dumps(profile, indent=2, ensure_ascii=False) + profile = await get_jeen_metadata_client().get_column_profile(table_name, column_name) except Exception as e: - return f"Error fetching column profile: {str(e)}" + return _metadata_failure(f"get_column_profile({table_name}.{column_name})", e) + if not profile: + return fail(error(NOT_FOUND, f"No stored profile for column {table_name}.{column_name}")) + return ok(profile) # --------------------------------------------------------------------------- # Query Execution # --------------------------------------------------------------------------- -def _json(payload: dict) -> str: - return json.dumps(payload, ensure_ascii=False, default=str) - - def _run_sql(sql: str, row_cap: int | None) -> str: """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation. @@ -227,22 +200,21 @@ def _run_sql(sql: str, row_cap: int | None) -> str: try: res = execute_query_sync(sql) except Exception as e: - return _json(trino_errors.from_exception(e)) + return fail(trino_errors.from_exception(e)) if not res.success: - return _json(trino_errors.from_result(res)) + return fail(trino_errors.from_result(res)) rows = res.rows or [] truncated = row_cap is not None and len(rows) > row_cap if truncated: rows = rows[:row_cap] - return json.dumps({ - "success": True, + return ok({ "columns": res.columns, "row_count": len(rows), "truncated": truncated, "rows": rows, "query_id": res.query_id, - }, ensure_ascii=False, default=str) + }) @tool @@ -253,17 +225,17 @@ def execute_trino_query(sql: str, limit: int | None = None) -> str: Use this to test SQL queries against the actual database and perform exploratory data analysis. Only a single SELECT / WITH (or SHOW / DESCRIBE) statement is accepted; anything that writes, multiple statements, SQL comments and TABLE(...) pass-through functions are rejected with - error_name FORBIDDEN_STATEMENT. + error.name FORBIDDEN_STATEMENT. Results are capped at a configured row ceiling (when one is set): an outer LIMIT is enforced - automatically, and the response includes 'truncated': true when more rows existed than were returned. + automatically, and data.truncated is true when more rows existed than were returned. - On failure, the response carries Trino's own error, unmodified: - - error_name: Trino's error code (e.g. SYNTAX_ERROR, COLUMN_NOT_FOUND, TYPE_MISMATCH, + On failure, error carries Trino's own error, unmodified: + - error.name: Trino's error code (e.g. SYNTAX_ERROR, COLUMN_NOT_FOUND, TYPE_MISMATCH, EXPRESSION_NOT_AGGREGATE, DIVISION_BY_ZERO) - - error_type: Trino's error class — USER_ERROR means the SQL itself is wrong; + - error.type: Trino's error class — USER_ERROR means the SQL itself is wrong; INSUFFICIENT_RESOURCES, INTERNAL_ERROR and EXTERNAL come from the cluster or the source database - - error_message: Trino's message; error_location: {line, column} of the offending token + - error.message: Trino's message; error.location: {line, column} of the offending token Two errors don't come from Trino: FORBIDDEN_STATEMENT (rejected before reaching Trino — rewrite as a single read-only query without comments) and CONNECTION_ERROR (Trino could not be reached). @@ -277,7 +249,7 @@ def execute_trino_query(sql: str, limit: int | None = None) -> str: try: guarded = sql_guard.prepare(clean_sql(sql), row_cap) except sql_guard.GuardError as e: - return _json(trino_errors.forbidden(str(e))) + return fail(trino_errors.forbidden(str(e))) return _run_sql(guarded.sql, guarded.row_cap if guarded.is_query else settings.DEEP_AGENT_MAX_ROWS) @@ -298,7 +270,7 @@ def get_sample_rows(table_name: str, limit: int = 5) -> str: try: sql = sql_guard.sample_rows_sql(table_name, row_cap) except sql_guard.GuardError as e: - return _json(trino_errors.forbidden(str(e))) + return fail(trino_errors.forbidden(str(e))) return _run_sql(sql, row_cap) @@ -328,7 +300,7 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 try: sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) except sql_guard.GuardError as e: - return _json(trino_errors.forbidden(str(e))) + return fail(trino_errors.forbidden(str(e))) return _run_sql(sql, row_cap) @@ -336,6 +308,9 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 # SQL Quality # --------------------------------------------------------------------------- +_VALIDATE_PREFIX = "EXPLAIN (TYPE VALIDATE) " + + @tool def validate_sql(sql: str) -> str: """ @@ -346,8 +321,8 @@ def validate_sql(sql: str) -> str: Use this to dry-run a new draft before execute_trino_query. It cannot tell you whether the query returns rows. - Returns JSON: {"valid": true}, or {"valid": false, ...} with the same error fields as - execute_trino_query (error_name, error_type, error_message, error_location). + Returns ok=true with data.valid=true, or ok=false with the same error fields as + execute_trino_query (error.name, error.type, error.message, error.location). Args: sql (str): The exact Trino SQL query string to validate. @@ -356,26 +331,19 @@ def validate_sql(sql: str) -> str: try: sql_guard.parse_read_statement(sql_clean) except sql_guard.GuardError as e: - return _invalid(trino_errors.forbidden(str(e))) + return fail(trino_errors.forbidden(str(e))) try: res = execute_query_sync(f"{_VALIDATE_PREFIX}{sql_clean}") except Exception as e: - return _invalid(trino_errors.from_exception(e)) + return fail(trino_errors.from_exception(e)) if res.success: - return _json({"valid": True}) - error = trino_errors.from_result(res) - location = error.get("error_location") + return ok({"valid": True}) + err = trino_errors.from_result(res) + location = err.get("location") if location and location["line"] == 1: # Trino counts columns from the start of "EXPLAIN (TYPE VALIDATE) ..."; report them against the caller's SQL. location["column"] = max(1, location["column"] - len(_VALIDATE_PREFIX)) - return _invalid(error) - - -_VALIDATE_PREFIX = "EXPLAIN (TYPE VALIDATE) " - - -def _invalid(error: dict) -> str: - return _json({"valid": False, **{k: v for k, v in error.items() if k != "success"}}) + return fail(err) # --------------------------------------------------------------------------- @@ -396,9 +364,10 @@ async def search_metadata(query: str, limit: int = 10) -> str: query (str): The search text (multilingual/Hebrew support) to match against metadata. limit (int): Maximum number of results to return. Defaults to 10. """ - client = get_jeen_metadata_client() - res = await client.search(query, limit) - return json.dumps(res, indent=2, ensure_ascii=False) + try: + return ok(await get_jeen_metadata_client().search(query, limit)) + except Exception as e: + return _metadata_failure("search_metadata", e) @tool @@ -415,10 +384,11 @@ async def search_business_terms(query: str, limit: int = 10) -> str: limit (int): Maximum number of results to return. Defaults to 10. """ if not _connection_capabilities.get("has_business_terms", True): - return "[] (Notice: This connection has NO business terms defined in the catalog. Do not call this tool again.)" - client = get_jeen_metadata_client() - res = await client.search_business_terms(query, limit) - return json.dumps(res, indent=2, ensure_ascii=False) + return ok({"terms": [], "notice": "This connection has NO business terms defined. Do not call this tool again."}) + try: + return ok(await get_jeen_metadata_client().search_business_terms(query, limit)) + except Exception as e: + return _metadata_failure("search_business_terms", e) @tool @@ -438,10 +408,30 @@ async def search_knowledge_pairs(query: str, limit: int = 10) -> str: limit (int): Maximum number of results to return. Defaults to 10. """ if not _connection_capabilities.get("has_knowledge_pairs", True): - return "[] (Notice: This connection has NO knowledge pairs defined in the catalog. Do not call this tool again.)" - client = get_jeen_metadata_client() - res = await client.search_knowledge_pairs(query, limit) - return json.dumps(res, indent=2, ensure_ascii=False) + return ok({"pairs": [], "notice": "This connection has NO knowledge pairs defined. Do not call this tool again."}) + try: + return ok(await get_jeen_metadata_client().search_knowledge_pairs(query, limit)) + except Exception as e: + return _metadata_failure("search_knowledge_pairs", e) + + +def _round_or_none(value: Any) -> float | None: + try: + return round(float(value), 3) + except (TypeError, ValueError): + return None + + +def _value_match(v: Any) -> dict: + if not isinstance(v, dict): + return {"value": v} + return { + "value": v.get("value"), + "table": v.get("table_name") or v.get("table"), + "column": v.get("column_name") or v.get("column"), + "keyword_similarity": _round_or_none(v.get("keyword_similarity")), + "semantic_distance": _round_or_none(v.get("semantic_distance")), + } @tool @@ -456,8 +446,6 @@ async def search_column_values( SUPPORTED COLUMN TYPES: Works exclusively on high-cardinality columns profiled as: - # - `boolean` (not indexed in search MCP — use catalog or get_column_distinct_values) - # - `categorical` (not indexed in search MCP — use catalog or get_column_distinct_values) - `large_categorical` - `large_unit_id` ⚠️ Do NOT use on standard `categorical` or `boolean` columns (e.g. `launch_country`) — they are @@ -468,13 +456,8 @@ async def search_column_values( - Use whenever you need to find how a high-cardinality entity is represented or spelled in the database (e.g., finding 'Tel Aviv 1' from 'תל אביב' or 'Acme Corp' from 'Acme'). Multilingual, keyword, and vector search finds the exact database spelling. - - Essential for high-cardinality columns (`large_categorical`, `large_unit_id`) where dumping - all distinct values is infeasible. - The response includes: - - A 'top_matches' summary listing the exact values you should use in SQL - - If multiple values share a common prefix (e.g., 'Tel Aviv 1', 'Tel Aviv 57'), - the column stores composite strings — use LIKE 'prefix%' in SQL to match all variants + Returns data.matches — every matching value (use each 'value' verbatim in SQL) with: - 'keyword_similarity' close to 1.0 = strong lexical match - 'semantic_distance' close to 0.0 = strong semantic match @@ -484,47 +467,20 @@ async def search_column_values( column (str, optional): Restrict search to one column name. Omit to search all columns. limit (int): Maximum number of results to return. Defaults to 10. """ - client = get_jeen_metadata_client() - res = await client.search_column_values(search_term=search_term, table=table, column=column, limit=limit, raw=True) - - # Build an actionable summary of the top matches at the top of the response - summary_lines = [] - if isinstance(res, dict) and "values" in res: - values = res["values"] - if values: - summary_lines.append(f"TOP MATCHES for '{search_term}' (use these exact strings in SQL):") - seen_values = [] - for v in values[:5]: - if isinstance(v, dict): - val = v.get("value", "") - tbl = v.get("table_name", "") - col = v.get("column_name", "") - ks = round(v.get("keyword_similarity", 0), 3) - sd = round(v.get("semantic_distance", 1), 3) - summary_lines.append(f" - '{val}' (table: {tbl}, column: {col}, keyword_sim: {ks}, sem_dist: {sd})") - seen_values.append(val) - - # Detect composite prefix pattern (e.g., 'Tel Aviv 1', 'Tel Aviv 57') - import re as _re - prefixes = [] - for val in seen_values: - m = _re.match(r'^([A-Za-z\s\'\-\.]+?)\s*\d+$', val.strip()) - if m: - prefixes.append(m.group(1).strip()) - if prefixes: - common_prefix = max(set(prefixes), key=prefixes.count) - if prefixes.count(common_prefix) >= 2: - summary_lines.append( - f"\nNOTE: Multiple values share prefix '{common_prefix}' " - f"— this column stores composite strings (name + code). " - f"Use LIKE '{common_prefix}%' to match all variants, or pick one specific value." - ) - else: - summary_lines.append(f"No matches found for '{search_term}'. The value may not exist in this column.") - - summary = "\n".join(summary_lines) - full_payload = json.dumps(res, indent=2, ensure_ascii=False) - return f"{summary}\n\nFull payload:\n{full_payload}" + try: + res = await get_jeen_metadata_client().search_column_values( + search_term=search_term, table=table, column=column, limit=limit, raw=True + ) + except Exception as e: + return _metadata_failure("search_column_values", e) + + values = (res.get("values") or []) if isinstance(res, dict) else [] + matches = [_value_match(v) for v in values] + return ok({ + "search_term": search_term, + "matches": matches, + "notice": None if matches else "No matches — the value may not exist in this column, or the column is not indexed (only large_categorical / large_unit_id are).", + }) # --------------------------------------------------------------------------- @@ -553,21 +509,23 @@ async def enrich_sql_filters( Do NOT use this on purely numeric SQL or when you already have exact confirmed values. - Returns the enriched SQL string, or the original SQL if no enrichment was needed/possible. + Returns data.sql (the enriched SQL, or the original if nothing changed), data.enriched and + data.changes (one entry per corrected filter). Args: user_request (str): The original natural language request from the user (Hebrew). sql (str): The draft SQL query to enrich. jeen_catalog (str): The full catalog string (output of get_database_catalog). """ - from agent.services.enrichment_orchestrator import EnrichmentOrchestrator from agent.nodes.refiner import parse_jeen_catalog_tables + from agent.services.enrichment_orchestrator import EnrichmentOrchestrator sql_clean = clean_sql(sql) try: schema, tables = parse_jeen_catalog_tables(jeen_catalog) if not tables: - return f"Could not parse schema from catalog. Original SQL returned unchanged:\n{sql_clean}" + return fail(error(INVALID_INPUT, "Could not parse any tables from jeen_catalog; pass the catalog unchanged.", + original_sql=sql_clean)) refined_sql, plan, enriched = await EnrichmentOrchestrator.enrich_query( user_request=user_request, @@ -576,28 +534,25 @@ async def enrich_sql_filters( tables=tables, config=None, ) - - if enriched and plan: - changes = [] - for tf in plan.enrichment_details: - if tf.changed_filter: - changes.append( - f" • column '{tf.column}': '{tf.original_value}' → {tf.refined_values} " - f"(operator: {tf.old_operator} → {tf.new_operator})" - ) - summary = "\n".join(changes) if changes else " (no changes logged)" - return ( - f"✅ SQL enriched successfully. Changes made:\n{summary}\n\n" - f"Enriched SQL:\n```sql\n{refined_sql}\n```" - ) - else: - return ( - f"ℹ️ No categorical filter corrections needed. Original SQL:\n```sql\n{sql_clean}\n```" - ) - except Exception as e: - logger.error(f"enrich_sql_filters failed: {e}", exc_info=True) - return f"Error during enrichment (original SQL unchanged): {e}\n\n```sql\n{sql_clean}\n```" + logger.error("enrich_sql_filters failed: %s", e, exc_info=True) + return fail(error(ENRICHMENT_ERROR, f"{e}. The SQL is unchanged.", original_sql=sql_clean)) + + changes = [] + if enriched and plan: + changes = [ + { + "column": tf.column, + "original_value": tf.original_value, + "refined_values": tf.refined_values, + "old_operator": tf.old_operator, + "new_operator": tf.new_operator, + } + for tf in plan.enrichment_details + if tf.changed_filter + ] + is_enriched = bool(enriched and plan) + return ok({"enriched": is_enriched, "sql": refined_sql if is_enriched else sql_clean, "changes": changes}) # --------------------------------------------------------------------------- @@ -610,14 +565,14 @@ def resolve_location_to_wkt(location_name: str) -> str: Resolves a geographic location name to its WKT (Well-Known Text) polygon representation. Use this whenever the user's query involves a geographic area and you need a WKT polygon for - a Trino ST_GeometryFromText() / ST_Within() / ST_Intersects() call. + a Trino ST_GeometryFromText() / ST_Within() / ST_Contains() call. Supports Hebrew location names directly (e.g., 'תל אביב', 'ירושלים', 'חיפה'). - Returns a simplified polygon quoted WKT string, e.g., 'POLYGON((...))', ready to embed - directly into SQL: ST_GeometryFromText(). + Returns data.wkt — the polygon as plain (unquoted) WKT, e.g. POLYGON((...)). In SQL, wrap it + in single quotes: ST_GeometryFromText(''). The function uses rate-limited Nominatim geocoding with caching and automatic WKT - simplification (binary search), falling back to a bounding-box polygon if needed. + simplification (binary search). Only area geometries are returned (never points). Do NOT use this for exact addresses (e.g., "Rothschild 10, Tel Aviv"); it is designed for administrative areas: cities, regions, districts, and countries. @@ -627,8 +582,32 @@ def resolve_location_to_wkt(location_name: str) -> str: accepted and preferred for Israeli locations. """ geojson = get_geojson_polygon(location_name) - if geojson: - wkt = geojson_to_simplified_wkt(geojson) - if wkt: - return wkt - return f"Error: Could not resolve location '{location_name}' to WKT." + quoted = geojson_to_simplified_wkt(geojson) if geojson else None # returns a single-quoted literal + if not quoted: + return fail(error(LOCATION_NOT_FOUND, f"Could not resolve location '{location_name}' to an area polygon.")) + return ok({"location": location_name, "wkt": quoted.strip("'")}) + + +# The agent's full domain tool set (order = order shown to the model). +DEEP_AGENT_TOOLS = [ + # Discovery & Schema + get_database_catalog, + get_database_tables, + get_table_columns, + get_table_relationships, + get_table_profile, + get_column_profile, + # Search & Resolve + search_metadata, + search_business_terms, + search_knowledge_pairs, + search_column_values, + resolve_location_to_wkt, + # Query Execution + execute_trino_query, + get_sample_rows, + get_column_distinct_values, + validate_sql, + # Post-processing + enrich_sql_filters, +] diff --git a/agent/src/deep_agent/trino_errors.py b/agent/src/deep_agent/trino_errors.py index c740e0e..8a01cf1 100644 --- a/agent/src/deep_agent/trino_errors.py +++ b/agent/src/deep_agent/trino_errors.py @@ -1,5 +1,5 @@ """ -Error payloads returned to the agent when SQL fails. +Error objects returned to the agent when SQL fails (the `error` of the tool envelope). Trino errors are passed through as Trino reported them (errorName, errorType, message, location, query id) — no re-labelling. Two failures never get a Trino error and are @@ -10,38 +10,31 @@ """ from core.trino import TrinoExecutionResult +from deep_agent.envelope import error FORBIDDEN_STATEMENT = "FORBIDDEN_STATEMENT" CONNECTION_ERROR = "CONNECTION_ERROR" def from_result(res: TrinoExecutionResult) -> dict: - """Error payload for a failed TrinoExecutionResult.""" + """Error object for a failed TrinoExecutionResult.""" if res.error_name is None: - return _payload(CONNECTION_ERROR, None, res.error_message or "Unknown error") - return _payload(res.error_name, res.error_type, res.error_message or "", res.error_location, res.query_id) + return error(CONNECTION_ERROR, res.error_message or "Unknown error") + location = {"line": res.error_location[0], "column": res.error_location[1]} if res.error_location else None + return error( + res.error_name, + res.error_message or "", + type=res.error_type, + location=location, + query_id=res.query_id, + ) def forbidden(message: str) -> dict: - """Error payload for SQL the guard rejected.""" - return _payload(FORBIDDEN_STATEMENT, None, message) + """Error object for SQL the guard rejected.""" + return error(FORBIDDEN_STATEMENT, message) def from_exception(exc: Exception) -> dict: - """Error payload for an exception raised while calling Trino.""" - return _payload(CONNECTION_ERROR, None, str(exc)) - - -def _payload( - name: str, - error_type: str | None, - message: str, - location: tuple[int, int] | None = None, - query_id: str | None = None, -) -> dict: - out: dict = {"success": False, "error_name": name, "error_type": error_type, "error_message": message} - if location: - out["error_location"] = {"line": location[0], "column": location[1]} - if query_id: - out["query_id"] = query_id - return out + """Error object for an exception raised while calling Trino.""" + return error(CONNECTION_ERROR, str(exc)) diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py new file mode 100644 index 0000000..c48c711 --- /dev/null +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -0,0 +1,213 @@ +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +import tiktoken + +import agent.utils.jeen_metadata_client as jmc +from agent.utils.jeen_metadata_client import JeenMetadataClient, JeenMetadataError +from core.trino import TrinoExecutionResult +from deep_agent import tools +from deep_agent.tools import DEEP_AGENT_TOOLS + +# Minimal valid arguments for every tool. +TOOL_ARGS = { + "get_database_catalog": {}, + "get_database_tables": {}, + "get_table_columns": {"table_name": "t"}, + "get_table_relationships": {}, + "get_table_profile": {"table_name": "t"}, + "get_column_profile": {"table_name": "t", "column_name": "c"}, + "search_metadata": {"query": "q"}, + "search_business_terms": {"query": "q"}, + "search_knowledge_pairs": {"query": "q"}, + "search_column_values": {"search_term": "תל אביב"}, + "resolve_location_to_wkt": {"location_name": "חיפה"}, + "execute_trino_query": {"sql": "SELECT 1"}, + "get_sample_rows": {"table_name": "t"}, + "get_column_distinct_values": {"table_name": "t", "column_name": "c"}, + "validate_sql": {"sql": "SELECT 1"}, + "enrich_sql_filters": {"user_request": "q", "sql": "SELECT 1 FROM t WHERE a = 'x'", "jeen_catalog": "cat"}, +} + + +def _client(fail: bool) -> MagicMock: + client = MagicMock() + names = ["get_catalog_prompt", "get_tables", "get_columns", "get_relationships", "get_table_profile", + "get_column_profile", "search", "search_business_terms", "search_knowledge_pairs", "search_column_values"] + for name in names: + if fail: + setattr(client, name, AsyncMock(side_effect=JeenMetadataError(f"{name} exploded"))) + else: + setattr(client, name, AsyncMock(return_value={"values": [{"value": "v"}]} if name == "search_column_values" + else "# catalog" if name == "get_catalog_prompt" else [{"x": 1}])) + return client + + +@pytest.fixture(autouse=True) +def _reset_capabilities(): + tools._connection_capabilities.update(has_knowledge_pairs=True, has_business_terms=True, has_relationships=True) + + +@pytest.fixture +def patched(request): + fail = request.param + trino_res = (TrinoExecutionResult(success=False, error_message="boom", error_name="GENERIC_INTERNAL_ERROR", + error_type="INTERNAL_ERROR") + if fail else TrinoExecutionResult(success=True, rows=[[1]], columns=["a"], row_count=1)) + enrich = (AsyncMock(side_effect=RuntimeError("llm down")) if fail + else AsyncMock(return_value=("SELECT 1 FROM t WHERE a = 'X'", SimpleNamespace(enrichment_details=[]), True))) + with patch.object(tools, "get_jeen_metadata_client", return_value=_client(fail)), \ + patch.object(tools, "execute_query_sync", return_value=trino_res), \ + patch.object(tools, "get_geojson_polygon", return_value=None if fail else {"type": "Polygon"}), \ + patch.object(tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"), \ + patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=("s", ["t"])), \ + patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", enrich): + yield fail + + +def test_every_tool_is_covered(): + assert {t.name for t in DEEP_AGENT_TOOLS} == set(TOOL_ARGS) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("patched", [False, True], ids=["success", "failure"], indirect=True) +@pytest.mark.parametrize("tool", DEEP_AGENT_TOOLS, ids=lambda t: t.name) +async def test_tool_returns_envelope(tool, patched): + raw = await tool.ainvoke(TOOL_ARGS[tool.name]) + if tool.name == "get_database_catalog" and not patched: + assert raw.startswith("# catalog") # the catalog itself, as plain text + return + out = json.loads(raw) + assert set(out) == {"ok", "data", "error"}, raw + assert out["ok"] is (not patched), raw + if patched: + assert out["data"] is None + assert {"name", "message"} <= set(out["error"]) + assert "hint" not in out["error"] and "category" not in out["error"] + else: + assert out["error"] is None + assert "\n " not in raw, "envelope must be compact (no indentation)" + + +@pytest.mark.asyncio +async def test_catalog_is_plain_text_with_capabilities_note(): + client = MagicMock(get_catalog_prompt=AsyncMock(return_value='"postgres"."public"."t": desc\n(no knowledge pairs)')) + with patch.object(tools, "get_jeen_metadata_client", return_value=client): + raw = await tools.get_database_catalog.ainvoke({}) + assert raw.startswith('"postgres"."public"."t"') # quotes not JSON-escaped + assert "Knowledge Pairs: None (skip search_knowledge_pairs)" in raw + assert tools._connection_capabilities["has_knowledge_pairs"] is False + + +@pytest.mark.asyncio +async def test_metadata_failure_says_data_is_not_empty(): + client = MagicMock(get_tables=AsyncMock(side_effect=JeenMetadataError("auth expired"))) + with patch.object(tools, "get_jeen_metadata_client", return_value=client): + out = json.loads(await tools.get_database_tables.ainvoke({})) + assert out["error"]["name"] == "METADATA_ERROR" + assert "does not mean the data is empty" in out["error"]["message"] + + +@pytest.mark.asyncio +async def test_mcp_is_error_flag_raises(): + result = SimpleNamespace(isError=True, content=[SimpleNamespace(text="connection_id 999 not found")]) + session = MagicMock() + session.initialize = AsyncMock() + session.call_tool = AsyncMock(return_value=result) + session_cm = MagicMock(__aenter__=AsyncMock(return_value=session), __aexit__=AsyncMock(return_value=False)) + transport_cm = MagicMock(__aenter__=AsyncMock(return_value=(None, None, None)), __aexit__=AsyncMock(return_value=False)) + with patch.object(jmc, "streamablehttp_client", return_value=transport_cm), \ + patch.object(jmc, "ClientSession", return_value=session_cm): + with pytest.raises(JeenMetadataError, match="connection_id 999 not found"): + await jmc._call_mcp_tool("http://x", "k", "get_relationships", {}) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["get_tables", "get_columns", "get_relationships"]) +async def test_unexpected_payload_is_an_error_not_empty(method): + client = JeenMetadataClient() + with patch.object(client, "_call", AsyncMock(return_value="Error: auth expired")): + with pytest.raises(JeenMetadataError, match="auth expired"): + await getattr(client, method)() + + +@pytest.mark.asyncio +async def test_relationships_tool_surfaces_mcp_error(): + client = MagicMock(get_relationships=AsyncMock(side_effect=JeenMetadataError("auth expired"))) + with patch.object(tools, "get_jeen_metadata_client", return_value=client): + out = json.loads(await tools.get_table_relationships.ainvoke({})) + assert out["ok"] is False + assert out["error"]["name"] == "METADATA_ERROR" + assert "auth expired" in out["error"]["message"] + + +async def _search(values): + client = MagicMock(search_column_values=AsyncMock(return_value={"values": values})) + with patch.object(tools, "get_jeen_metadata_client", return_value=client): + return json.loads(await tools.search_column_values.ainvoke({"search_term": "x"})) + + +@pytest.mark.asyncio +async def test_search_values_handles_nulls_and_numbers(): + out = await _search([ + {"value": 12345, "table_name": "t", "column_name": "unit_id", "keyword_similarity": None, "semantic_distance": None}, + {"value": None, "keyword_similarity": "n/a"}, + "bare-string", + ]) + assert out["ok"] is True + m = out["data"]["matches"] + assert m[0] == {"value": 12345, "table": "t", "column": "unit_id", "keyword_similarity": None, "semantic_distance": None} + assert m[1]["value"] is None + assert m[2] == {"value": "bare-string"} + + +@pytest.mark.asyncio +async def test_search_values_returns_every_match_without_prefix_guessing(): + values = [f"תל אביב {i}" for i in range(15)] + out = await _search([{"value": v, "keyword_similarity": 0.9, "semantic_distance": 0.1} for v in values]) + assert [m["value"] for m in out["data"]["matches"]] == values + assert "prefix_pattern" not in out["data"] + + +@pytest.mark.asyncio +async def test_search_values_passes_limit_through_unclamped(): + client = MagicMock(search_column_values=AsyncMock(return_value={"values": []})) + with patch.object(tools, "get_jeen_metadata_client", return_value=client): + await tools.search_column_values.ainvoke({"search_term": "x", "limit": 500}) + assert client.search_column_values.call_args.kwargs["limit"] == 500 + + +@pytest.mark.asyncio +async def test_location_returns_the_polygon_once(): + with patch.object(tools, "get_geojson_polygon", return_value={"type": "Polygon"}), \ + patch.object(tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"): + out = json.loads(tools.resolve_location_to_wkt.invoke({"location_name": "חיפה"})) + assert out["data"] == {"location": "חיפה", "wkt": "POLYGON((0 0, 1 0, 1 1, 0 0))"} + + +def _old_search_column_values_output(search_term: str, res: dict) -> str: + """The pre-#45 output format (summary + indent=2 full payload), reproduced for comparison.""" + lines = [f"TOP MATCHES for '{search_term}' (use these exact strings in SQL):"] + for v in res["values"][:5]: + lines.append(f" - '{v['value']}' (table: {v['table_name']}, column: {v['column_name']}, " + f"keyword_sim: {round(v['keyword_similarity'], 3)}, sem_dist: {round(v['semantic_distance'], 3)})") + return "\n".join(lines) + "\n\nFull payload:\n" + json.dumps(res, indent=2, ensure_ascii=False) + + +@pytest.mark.asyncio +async def test_search_values_output_is_at_least_40_percent_smaller(): + res = {"values": [ + {"value": f"תל אביב {i}", "table_name": "city_info_table", "column_name": "city_name", + "keyword_similarity": 0.912345 - i / 100, "semantic_distance": 0.123456 + i / 100, + "semantic_type": "large_categorical", "connection_id": 89, "embedding_model": "nomic-embed-text"} + for i in range(10) + ]} + client = MagicMock(search_column_values=AsyncMock(return_value=res)) + with patch.object(tools, "get_jeen_metadata_client", return_value=client): + new = await tools.search_column_values.ainvoke({"search_term": "תל אביב"}) + enc = tiktoken.get_encoding("o200k_base") + old_tokens = len(enc.encode(_old_search_column_values_output("תל אביב", res))) + new_tokens = len(enc.encode(new)) + assert new_tokens <= 0.6 * old_tokens, (old_tokens, new_tokens) diff --git a/agent/tests/deep_agent/test_trino_errors.py b/agent/tests/deep_agent/test_trino_errors.py index c1d4bfa..8497752 100644 --- a/agent/tests/deep_agent/test_trino_errors.py +++ b/agent/tests/deep_agent/test_trino_errors.py @@ -33,14 +33,14 @@ def test_trino_errors_are_passed_through_unchanged(error): assert res.query_id == "20261020_000000_00001_abcde" out = trino_errors.from_result(res) - assert out["error_name"] == error["errorName"] - assert out["error_type"] == error["errorType"] - assert out["error_message"] == error["message"] + assert out["name"] == error["errorName"] + assert out["type"] == error["errorType"] + assert out["message"] == error["message"] location = error.get("errorLocation") if location: - assert out["error_location"] == {"line": location["lineNumber"], "column": location["columnNumber"]} + assert out["location"] == {"line": location["lineNumber"], "column": location["columnNumber"]} else: - assert "error_location" not in out + assert "location" not in out def test_connection_failure_is_reported_as_connection_error(): @@ -49,9 +49,9 @@ def test_connection_failure_is_reported_as_connection_error(): patch.object(core_trino, "get_trino_connection", return_value=_failing_connection(exc)): res = core_trino.execute_query_sync("SELECT 1") out = trino_errors.from_result(res) - assert out["error_name"] == "CONNECTION_ERROR" - assert out["error_type"] is None - assert "Max retries exceeded" in out["error_message"] + assert out["name"] == "CONNECTION_ERROR" + assert "type" not in out + assert "Max retries exceeded" in out["message"] def test_execute_tool_returns_trinos_error(): @@ -62,20 +62,23 @@ def test_execute_tool_returns_trinos_error(): with patch.object(tools, "execute_query_sync", return_value=res): out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT ST_GeomFromText('POINT(1 1)')"})) assert out == { - "success": False, - "error_name": "FUNCTION_NOT_FOUND", - "error_type": "USER_ERROR", - "error_message": "line 1:8: Function 'st_geomfromtext' not registered", - "error_location": {"line": 1, "column": 8}, - "query_id": "q1", + "ok": False, + "data": None, + "error": { + "name": "FUNCTION_NOT_FOUND", + "message": "line 1:8: Function 'st_geomfromtext' not registered", + "type": "USER_ERROR", + "location": {"line": 1, "column": 8}, + "query_id": "q1", + }, } def test_execute_tool_reports_exceptions_as_connection_error(): with patch.object(tools, "execute_query_sync", side_effect=OSError("connection refused")): out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT 1"})) - assert out["error_name"] == "CONNECTION_ERROR" - assert out["error_message"] == "connection refused" + assert out["error"]["name"] == "CONNECTION_ERROR" + assert out["error"]["message"] == "connection refused" def test_validate_returns_trinos_error(): @@ -85,11 +88,9 @@ def test_validate_returns_trinos_error(): ) with patch.object(tools, "execute_query_sync", return_value=res): out = json.loads(tools.validate_sql.invoke({"sql": "SELECT x FROM t"})) - assert out["valid"] is False - assert out["error_name"] == "COLUMN_NOT_FOUND" - assert out["error_type"] == "USER_ERROR" - assert "success" not in out - + assert out["ok"] is False + assert out["error"]["name"] == "COLUMN_NOT_FOUND" + assert out["error"]["type"] == "USER_ERROR" def test_validate_reports_location_against_the_callers_sql(): @@ -100,8 +101,8 @@ def test_validate_reports_location_against_the_callers_sql(): ) with patch.object(tools, "execute_query_sync", return_value=res): out = json.loads(tools.validate_sql.invoke({"sql": "SELECT x FROM t"})) - assert out["error_location"] == {"line": 1, "column": 8} - assert out["error_message"] == "line 1:32: Column 'x' cannot be resolved" # Trino's message stays raw + assert out["error"]["location"] == {"line": 1, "column": 8} + assert out["error"]["message"] == "line 1:32: Column 'x' cannot be resolved" # Trino's message stays raw def test_validate_leaves_later_lines_alone(): @@ -111,4 +112,4 @@ def test_validate_leaves_later_lines_alone(): ) with patch.object(tools, "execute_query_sync", return_value=res): out = json.loads(tools.validate_sql.invoke({"sql": "SELECT a\nFROM t\nWHERE x = 1"})) - assert out["error_location"] == {"line": 3, "column": 7} + assert out["error"]["location"] == {"line": 3, "column": 7} diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py index 90bf0ed..a275ee7 100644 --- a/agent/tests/deep_agent/test_trino_tools.py +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -22,8 +22,8 @@ def trino(): @pytest.mark.parametrize("sql", ["DROP TABLE t", "DELETE FROM t", "SELECT 1; DROP TABLE t", "SELECT 1 -- x"]) def test_forbidden_sql_never_reaches_trino(trino, sql): out = json.loads(tools.execute_trino_query.invoke({"sql": sql})) - assert out["success"] is False - assert out["error_name"] == "FORBIDDEN_STATEMENT" + assert out["ok"] is False + assert out["error"]["name"] == "FORBIDDEN_STATEMENT" trino.assert_not_called() @@ -32,8 +32,8 @@ def test_limit_argument_is_clamped_and_truncation_reported(trino): out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t", "limit": 1_000_000})) executed = trino.call_args.args[0] assert executed.endswith("LIMIT 101") - assert out["row_count"] == 100 - assert out["truncated"] is True + assert out["data"]["row_count"] == 100 + assert out["data"]["truncated"] is True def test_omitted_limit_uses_the_configured_ceiling(trino, monkeypatch): @@ -48,8 +48,8 @@ def test_no_ceiling_runs_sql_as_written_and_returns_every_row(trino, monkeypatch trino.return_value = _ok(5000) out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t;"})) assert trino.call_args.args[0] == "SELECT id FROM t" - assert out["row_count"] == 5000 - assert out["truncated"] is False + assert out["data"]["row_count"] == 5000 + assert out["data"]["truncated"] is False def test_no_ceiling_still_honours_an_explicit_limit(trino, monkeypatch): @@ -57,8 +57,8 @@ def test_no_ceiling_still_honours_an_explicit_limit(trino, monkeypatch): trino.return_value = _ok(11) out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t", "limit": 10})) assert trino.call_args.args[0] == "SELECT id FROM t LIMIT 11" - assert out["row_count"] == 10 - assert out["truncated"] is True + assert out["data"]["row_count"] == 10 + assert out["data"]["truncated"] is True @pytest.mark.parametrize("raw", ["none", "None", "", "unlimited"]) @@ -85,8 +85,8 @@ def test_speed_limit_column_still_gets_limit(trino): trino.return_value = _ok(3) out = json.loads(tools.execute_trino_query.invoke({"sql": "```sql\nSELECT speed_limit FROM t;\n```", "limit": 10})) assert trino.call_args.args[0] == "SELECT speed_limit FROM t LIMIT 11" - assert out["truncated"] is False - assert out["row_count"] == 3 + assert out["data"]["truncated"] is False + assert out["data"]["row_count"] == 3 def test_trino_error_is_reported(trino): @@ -95,7 +95,7 @@ def test_trino_error_is_reported(trino): error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", ) out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT x FROM t"})) - assert out["error_name"] == "COLUMN_NOT_FOUND" + assert out["error"]["name"] == "COLUMN_NOT_FOUND" def test_sample_rows_handles_hebrew_quoted_table(trino): @@ -106,7 +106,7 @@ def test_sample_rows_handles_hebrew_quoted_table(trino): def test_sample_rows_rejects_injection(trino): out = json.loads(tools.get_sample_rows.invoke({"table_name": "t; DROP TABLE t"})) - assert out["error_name"] == "FORBIDDEN_STATEMENT" + assert out["error"]["name"] == "FORBIDDEN_STATEMENT" trino.assert_not_called() @@ -118,12 +118,12 @@ def test_distinct_values_quotes_hebrew_column(trino): def test_validate_rejects_writes_without_calling_trino(trino): out = json.loads(tools.validate_sql.invoke({"sql": "DELETE FROM t"})) - assert out["valid"] is False - assert out["error_name"] == "FORBIDDEN_STATEMENT" + assert out["ok"] is False + assert out["error"]["name"] == "FORBIDDEN_STATEMENT" trino.assert_not_called() def test_validate_runs_explain_for_reads(trino): trino.return_value = _ok(0) - assert json.loads(tools.validate_sql.invoke({"sql": "SELECT 1"})) == {"valid": True} + assert json.loads(tools.validate_sql.invoke({"sql": "SELECT 1"}))["data"] == {"valid": True} assert trino.call_args.args[0] == "EXPLAIN (TYPE VALIDATE) SELECT 1" diff --git a/package.json b/package.json index f179865..e984f88 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,9 @@ "backend/app/**/*.py": [ "backend/.venv/bin/ruff check --fix", "backend/.venv/bin/ruff format" + ], + "agent/src/deep_agent/**/*.py": [ + "agent/.venv/bin/ruff check --extend-select F --config agent/pyproject.toml" ] }, "devDependencies": { From 955d228755828a37a2ba1cfa69f6c1d3ebe2af5a Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 26 Oct 2026 16:26:05 +0200 Subject: [PATCH 11/37] fix(deep-agent): request-scoped runtime context instead of process globals (#38) Based on deep-agent/38-runtime-context (06e28d3), adapted to the revised stack: - DeepAgentContext (connection_id, user_id, timezone) passed per invocation via context_schema; tools read it through a hidden ToolRuntime parameter and pass connection_id to every Jeen client call - connection capabilities written to the thread's graph state by get_database_catalog (Command update, plain-text catalog kept); module global removed - today's date injected per model call (Asia/Jerusalem) as a transient prefix on the latest human message; system prompt no longer formatted - JeenMetadataClient: per-call connection_id on search*/column profile - CLI passes context instead of mutating client._connection_id Co-Authored-By: Claude Opus 5.5 --- agent/src/agent/utils/jeen_metadata_client.py | 45 +++---- agent/src/deep_agent/agent.py | 15 ++- agent/src/deep_agent/cli.py | 24 ++-- agent/src/deep_agent/context.py | 92 ++++++++++++++ agent/src/deep_agent/tools.py | 74 ++++++----- agent/tests/deep_agent/conftest.py | 26 +++- .../tests/deep_agent/test_runtime_context.py | 120 ++++++++++++++++++ agent/tests/deep_agent/test_tool_contracts.py | 6 - 8 files changed, 317 insertions(+), 85 deletions(-) create mode 100644 agent/src/deep_agent/context.py create mode 100644 agent/tests/deep_agent/test_runtime_context.py diff --git a/agent/src/agent/utils/jeen_metadata_client.py b/agent/src/agent/utils/jeen_metadata_client.py index 84023c5..e34d254 100644 --- a/agent/src/agent/utils/jeen_metadata_client.py +++ b/agent/src/agent/utils/jeen_metadata_client.py @@ -160,6 +160,10 @@ def __init__(self) -> None: # ── internal helper ──────────────────────────────────────────────────── + def _cid(self, connection_id: int | None) -> int: + """Per-call connection override, falling back to the configured default.""" + return connection_id if connection_id is not None else self._connection_id + async def _call(self, tool_name: str, arguments: dict[str, Any]) -> Any: """Thin wrapper so individual methods don't repeat the URL/key/timeout.""" return await _call_mcp_tool( @@ -181,6 +185,7 @@ async def search_column_values( column: str | None = None, limit: int | None = None, raw: bool = False, + connection_id: int | None = None, ) -> list[str] | dict[str, Any]: """ Looks up real values a column contains using semantic and keyword matching via MCP. @@ -193,7 +198,7 @@ async def search_column_values( lim = limit if limit is not None else self._search_limit args: dict[str, Any] = { - "connection_id": self._connection_id, + "connection_id": self._cid(connection_id), "search_term": search_term, "limit": lim, } @@ -360,7 +365,9 @@ async def get_table_profile(self, table_name: str, connection_id: int | None = N ) return None - async def get_column_profile(self, table_name: str, column_name: str) -> dict[str, Any] | None: + async def get_column_profile( + self, table_name: str, column_name: str, connection_id: int | None = None + ) -> dict[str, Any] | None: """ Returns the latest stored statistics for a single column: role, null ratio, distinct count, min/max, and example values. """ @@ -368,7 +375,7 @@ async def get_column_profile(self, table_name: str, column_name: str) -> dict[st res = await self._call( "get_column_profile", { - "connection_id": self._connection_id, + "connection_id": self._cid(connection_id), "table_name": table_name, "column_name": column_name, }, @@ -382,26 +389,6 @@ async def get_column_profile(self, table_name: str, column_name: str) -> dict[st raise JeenMetadataError(f"get_column_profile returned unexpected payload: {res[:300]}") return None - # ------------------------------------------------------------------ - # Prompt & Scoping Tools - # ------------------------------------------------------------------ - - # async def get_filtered_prompt(self, question: str, connection_id: int | None = None) -> dict[str, Any]: - # """ - # Returns metadata prompt narrowed to the question: the most relevant columns, - # knowledge pairs, and business terms. Returns { 'prompt': str, 'meta': dict }. - # """ - # cid = connection_id if connection_id is not None else self._connection_id - # return await self._call("get_filtered_prompt", {"connection_id": cid, "question": question}) - - # async def resolve_question(self, question: str, connection_id: int | None = None) -> dict[str, Any]: - # """ - # Explains how a question maps onto this connection's curated vocabulary: - # glossary terms, synonyms, acronyms, tables, and columns. - # """ - # cid = connection_id if connection_id is not None else self._connection_id - # return await self._call("resolve_question", {"connection_id": cid, "question": question}) - # ------------------------------------------------------------------ # Tables, Columns & Relationships Structure # ------------------------------------------------------------------ @@ -494,26 +481,26 @@ async def list_tables_rich(self, connection_id: int | None = None) -> list[dict[ # MCP Search Tools # ------------------------------------------------------------------ - async def search(self, query: str, limit: int = 10) -> Any: + async def search(self, query: str, limit: int = 10, connection_id: int | None = None) -> Any: """Search metadata for a connection across tables, columns, etc.""" try: - return await self._call("search", {"connection_id": self._connection_id, "query": query, "limit": limit}) + return await self._call("search", {"connection_id": self._cid(connection_id), "query": query, "limit": limit}) except Exception as exc: logger.error("search failed: %s", exc) _reraise_as_metadata_error(exc) - async def search_business_terms(self, query: str, limit: int = 10) -> Any: + async def search_business_terms(self, query: str, limit: int = 10, connection_id: int | None = None) -> Any: """Finds business glossary terms relevant to a question.""" try: - return await self._call("search_business_terms", {"connection_id": self._connection_id, "query": query, "limit": limit}) + return await self._call("search_business_terms", {"connection_id": self._cid(connection_id), "query": query, "limit": limit}) except Exception as exc: logger.error("search_business_terms failed: %s", exc) _reraise_as_metadata_error(exc) - async def search_knowledge_pairs(self, query: str, limit: int = 10) -> Any: + async def search_knowledge_pairs(self, query: str, limit: int = 10, connection_id: int | None = None) -> Any: """Finds saved question-and-query examples.""" try: - return await self._call("search_knowledge_pairs", {"connection_id": self._connection_id, "query": query, "limit": limit}) + return await self._call("search_knowledge_pairs", {"connection_id": self._cid(connection_id), "query": query, "limit": limit}) except Exception as exc: logger.error("search_knowledge_pairs failed: %s", exc) _reraise_as_metadata_error(exc) diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 14cff85..b31ae13 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -2,21 +2,18 @@ Agent logic and LangGraph harness for the Deep Agent. """ -import datetime - from deepagents import create_deep_agent as create_harness_agent from langchain_core.language_models import BaseChatModel from langgraph.checkpoint.memory import MemorySaver from agent.llm import get_llm +from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware from deep_agent.resources import build_resources from deep_agent.tools import DEEP_AGENT_TOOLS SYSTEM_PROMPT = """You are an elite, autonomous Deep SQL Analyst. Your mission: translate Hebrew natural-language questions into verified Trino SQL that is **semantically correct** — not just syntactically valid or merely executable. -Today's date: {today}. - --- ## Non-negotiable Principle @@ -98,7 +95,7 @@ ## Phase 5 — Execute & Diagnose - `execute_trino_query` — always LIMIT exploratory queries -- Every tool returns `{{"ok", "data", "error"}}` — check `ok` first (`get_database_catalog` returns the catalog as plain text). **Read the error before retrying**: for SQL, `error.name` / `error.type` / `error.message` are Trino's own, and `error.location` points at the offending token: +- Every tool returns `{"ok", "data", "error"}` — check `ok` first (`get_database_catalog` returns the catalog as plain text). **Read the error before retrying**: for SQL, `error.name` / `error.type` / `error.message` are Trino's own, and `error.location` points at the offending token: - `SYNTAX_ERROR` → fix the specific line only, do not redesign - `TABLE_NOT_FOUND` / `COLUMN_NOT_FOUND` → re-verify exact identifiers from catalog - `TYPE_MISMATCH` → add `CAST(col AS type)` @@ -194,18 +191,22 @@ def create_deep_agent(model: BaseChatModel | None = None): Creates and returns a compiled LangGraph deep agent equipped with all exploration, enrichment, temporal, geospatial, and semantic validation tools. + Invoke with a per-request context, e.g. + agent.ainvoke(inputs, config, context=DeepAgentContext(connection_id=89, user_id="u1")) + Args: model: Chat model override (tests); defaults to the configured LLM. """ llm = model or get_llm() memory = MemorySaver() - today = datetime.date.today().isoformat() resources = build_resources() agent = create_harness_agent( model=llm, tools=DEEP_AGENT_TOOLS, - system_prompt=SYSTEM_PROMPT.format(today=today), + system_prompt=SYSTEM_PROMPT, + middleware=[DeepAgentContextMiddleware()], + context_schema=DeepAgentContext, checkpointer=memory, backend=resources.backend, memory=resources.memory, diff --git a/agent/src/deep_agent/cli.py b/agent/src/deep_agent/cli.py index 1484141..1ad9ee1 100644 --- a/agent/src/deep_agent/cli.py +++ b/agent/src/deep_agent/cli.py @@ -19,8 +19,9 @@ from langchain_core.messages import BaseMessage -from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from agent.config import settings from deep_agent.agent import create_deep_agent +from deep_agent.context import DeepAgentContext # ANSI Colors for terminal output CYAN = "\033[96m" @@ -144,7 +145,9 @@ def print_formatted_message(msg: BaseMessage) -> None: print(f"{WHITE}{_message_text(msg)}{RESET}\n") -async def run_query(agent, question: str, thread_id: str, log_file: Path | None = None) -> None: +async def run_query( + agent, question: str, thread_id: str, context: DeepAgentContext, log_file: Path | None = None +) -> None: print(f"\n{CYAN}{BOLD}{'='*80}{RESET}") print(f"{CYAN}{BOLD} Running Query: \"{question}\"{RESET}") print(f"{DIM} Thread: {thread_id}{RESET}") @@ -156,7 +159,9 @@ async def run_query(agent, question: str, thread_id: str, log_file: Path | None final_state = None printed_count = 0 - async for state in agent.astream({"messages": [("user", question)]}, config, stream_mode="values"): + async for state in agent.astream( + {"messages": [("user", question)]}, config, stream_mode="values", context=context + ): messages = state.get("messages", []) while printed_count < len(messages): print_formatted_message(messages[printed_count]) @@ -217,9 +222,8 @@ def build_parser() -> argparse.ArgumentParser: async def _amain(args: argparse.Namespace) -> None: - client = get_jeen_metadata_client() - if args.connection_id: - client._connection_id = args.connection_id + context = DeepAgentContext(connection_id=args.connection_id) + target_connection = args.connection_id or settings.JEEN_METADATA_CONNECTION_ID # Thread ID strategy: # - With --session-memory: all queries share one thread → agent sees prior Q&A in context @@ -232,8 +236,8 @@ def next_thread_id() -> str: print(f"\n{MAGENTA}{BOLD}================================================================{RESET}") print(f"{MAGENTA}{BOLD} DEEP AGENT CLI — TEXT2SQL RUNNER {RESET}") print(f"{MAGENTA}{BOLD}================================================================{RESET}") - print(f" {CYAN}Target Connection:{RESET} ID {client._connection_id}") - print(f" {CYAN}MCP Endpoint:{RESET} {client._mcp_url}") + print(f" {CYAN}Target Connection:{RESET} ID {target_connection}") + print(f" {CYAN}MCP Endpoint:{RESET} {settings.JEEN_METADATA_MCP_URL}") if args.session_memory: print(f" {CYAN}Memory mode:{RESET} Session (queries share context — agent learns within session)") print(f" {CYAN}Session thread:{RESET} {session_thread_id}") @@ -258,10 +262,10 @@ def next_thread_id() -> str: print(f"{MAGENTA}{BOLD}Goodbye!{RESET}") break - await run_query(agent, question, next_thread_id(), args.log_file) + await run_query(agent, question, next_thread_id(), context, args.log_file) elif args.query: - await run_query(agent, args.query, next_thread_id(), args.log_file) + await run_query(agent, args.query, next_thread_id(), context, args.log_file) def main() -> None: diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py new file mode 100644 index 0000000..d20f264 --- /dev/null +++ b/agent/src/deep_agent/context.py @@ -0,0 +1,92 @@ +""" +Request-scoped runtime context and state for the Deep Agent. + +Nothing request-specific lives in module globals: +- DeepAgentContext is passed per invocation (`agent.ainvoke(..., context=DeepAgentContext(...))`) + and read by tools through `ToolRuntime.context`. +- Connection capabilities discovered by get_database_catalog are written to graph state + (`connection_capabilities`) and read back by tools through `ToolRuntime.state`. +- Today's date is added to the latest human message on every model call, in the + context's timezone, so long-running processes never serve a stale date. +""" + +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from datetime import datetime +from typing import Any, NotRequired +from zoneinfo import ZoneInfo + +from langchain.agents.middleware import AgentMiddleware, AgentState, ModelRequest, ModelResponse +from langchain.tools import ToolRuntime +from langchain_core.messages import HumanMessage + +DEFAULT_TIMEZONE = "Asia/Jerusalem" + + +@dataclass(frozen=True) +class DeepAgentContext: + connection_id: int | None = None # Jeen metadata connection; None -> JEEN_METADATA_CONNECTION_ID + user_id: str | None = None + timezone: str = DEFAULT_TIMEZONE + + +class DeepAgentRuntimeState(AgentState): + connection_capabilities: NotRequired[dict[str, bool]] + + +def connection_id(runtime: ToolRuntime | None) -> int | None: + ctx = getattr(runtime, "context", None) + return getattr(ctx, "connection_id", None) + + +def capability(runtime: ToolRuntime | None, name: str) -> bool: + """Whether the connection has a discovery source; unknown (catalog not fetched yet) counts as available.""" + state = getattr(runtime, "state", None) or {} + return bool((state.get("connection_capabilities") or {}).get(name, True)) + + +def _now(tz: str) -> datetime: + return datetime.now(ZoneInfo(tz)) + + +def date_line(tz: str) -> str: + now = _now(tz) + return f"Today's date: {now.date().isoformat()} ({now.strftime('%A')}, timezone {tz})." + + +def _with_date(request: ModelRequest) -> ModelRequest: + """Prefix the latest human message with today's date for this model call only. + + The date is deliberately *not* put in the system message: deepagents appends memory + (AGENTS.md) after user middleware, so a date there would sit mid-prompt and invalidate + provider prompt caching for everything after it every day. Here the system prompt stays + byte-identical and the change is transient (never written to graph state). + """ + ctx = getattr(request.runtime, "context", None) + line = date_line(getattr(ctx, "timezone", None) or DEFAULT_TIMEZONE) + messages = list(request.messages) + for i in range(len(messages) - 1, -1, -1): + msg = messages[i] + if isinstance(msg, HumanMessage): + content: Any = msg.content + if isinstance(content, str): + new_content: Any = f"[{line}]\n\n{content}" + else: + new_content = [{"type": "text", "text": f"[{line}]"}, *content] + messages[i] = msg.model_copy(update={"content": new_content}) + return request.override(messages=messages) + return request + + +class DeepAgentContextMiddleware(AgentMiddleware): + """Registers the runtime state keys and gives every model call today's date.""" + + state_schema = DeepAgentRuntimeState + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(_with_date(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(_with_date(request)) diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index eed245b..b29f470 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -9,7 +9,10 @@ import logging from typing import Any, Optional +from langchain.tools import ToolRuntime +from langchain_core.messages import ToolMessage from langchain_core.tools import tool +from langgraph.types import Command from agent.config import settings from agent.services.geo_utils import geojson_to_simplified_wkt, get_geojson_polygon @@ -19,6 +22,7 @@ from agent.utils.sql_guard import effective_cap from core.trino import execute_query_sync from deep_agent import trino_errors +from deep_agent.context import DeepAgentContext, capability, connection_id from deep_agent.envelope import ( ENRICHMENT_ERROR, INVALID_INPUT, @@ -37,12 +41,7 @@ # Database Catalog & Schema # --------------------------------------------------------------------------- -# Connection capability flags dynamically inferred from the catalog prompt -_connection_capabilities: dict[str, bool] = { - "has_knowledge_pairs": True, - "has_business_terms": True, - "has_relationships": True, -} +Runtime = ToolRuntime[DeepAgentContext] def _metadata_failure(what: str, exc: Exception) -> str: @@ -54,7 +53,7 @@ def _metadata_failure(what: str, exc: Exception) -> str: @tool -async def get_database_catalog() -> str: +async def get_database_catalog(runtime: Runtime = None) -> str | Command: """ Retrieves the complete metadata catalog and structural overview for the database. @@ -74,7 +73,7 @@ async def get_database_catalog() -> str: Do NOT use this to fetch live data rows; this only retrieves metadata and schema definitions. """ try: - catalog_prompt = await get_jeen_metadata_client().get_catalog_prompt() + catalog_prompt = await get_jeen_metadata_client().get_catalog_prompt(connection_id=connection_id(runtime)) except Exception as e: return _metadata_failure("get_database_catalog", e) @@ -82,9 +81,6 @@ async def get_database_catalog() -> str: has_kp = "(no knowledge pairs)" not in lower_prompt has_bt = "(no business terms)" not in lower_prompt has_fk = "(no relationships)" not in lower_prompt - _connection_capabilities["has_knowledge_pairs"] = has_kp - _connection_capabilities["has_business_terms"] = has_bt - _connection_capabilities["has_relationships"] = has_fk footer_lines = [ "\n\n---", @@ -93,24 +89,31 @@ async def get_database_catalog() -> str: f"- Business Terms: {'Available' if has_bt else 'None (skip search_business_terms)'}", f"- Foreign Keys: {'Available' if has_fk else 'None (infer joins from column names)'}", ] - return catalog_prompt + "\n".join(footer_lines) + content = catalog_prompt + "\n".join(footer_lines) + if runtime is None or not runtime.tool_call_id: + return content + # Record capabilities in this thread's state so later tool calls in the thread can read them. + return Command(update={ + "connection_capabilities": {"knowledge_pairs": has_kp, "business_terms": has_bt, "relationships": has_fk}, + "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="get_database_catalog")], + }) @tool -async def get_database_tables() -> str: +async def get_database_tables(runtime: Runtime = None) -> str: """ Returns the list of all tables in the connection with their business descriptions and exact quoted identifiers ("catalog"."schema"."table") for querying. Use this for a quick, clean roster of available tables. """ try: - return ok(await get_jeen_metadata_client().get_tables()) + return ok(await get_jeen_metadata_client().get_tables(connection_id=connection_id(runtime))) except Exception as e: return _metadata_failure("get_database_tables", e) @tool -async def get_table_columns(table_name: str) -> str: +async def get_table_columns(table_name: str, runtime: Runtime = None) -> str: """ Returns the columns for a specific table: data type, primary key flag, business description, real example values, and profiling statistics. @@ -119,30 +122,31 @@ async def get_table_columns(table_name: str) -> str: table_name (str): The table identifier (e.g. '"postgres"."public"."flights_table"' or 'flights_table'). """ try: - return ok(await get_jeen_metadata_client().get_columns(table_name)) + return ok(await get_jeen_metadata_client().get_columns(table_name, connection_id=connection_id(runtime))) except Exception as e: return _metadata_failure(f"get_table_columns({table_name})", e) @tool -async def get_table_relationships() -> str: +async def get_table_relationships(runtime: Runtime = None) -> str: """ Returns the source-scoped foreign-key and semantic join relationships between tables. Use this to identify exact join paths and foreign key pairs. """ - if not _connection_capabilities.get("has_relationships", True): + if not capability(runtime, "relationships"): return ok({ "relationships": [], "notice": "This connection has NO foreign key relationships defined. Infer joins using matching column names, e.g. flight_id.", }) try: - return ok({"relationships": await get_jeen_metadata_client().get_relationships()}) + rels = await get_jeen_metadata_client().get_relationships(connection_id=connection_id(runtime)) + return ok({"relationships": rels}) except Exception as e: return _metadata_failure("get_table_relationships", e) @tool -async def get_table_profile(table_name: str) -> str: +async def get_table_profile(table_name: str, runtime: Runtime = None) -> str: """ Retrieves the latest stored schema and statistics for one specific table. @@ -155,7 +159,7 @@ async def get_table_profile(table_name: str) -> str: e.g., '"catalog"."schema"."table"'. """ try: - profile = await get_jeen_metadata_client().get_table_profile(table_name) + profile = await get_jeen_metadata_client().get_table_profile(table_name, connection_id=connection_id(runtime)) except Exception as e: return _metadata_failure(f"get_table_profile({table_name})", e) if not profile: @@ -164,7 +168,7 @@ async def get_table_profile(table_name: str) -> str: @tool -async def get_column_profile(table_name: str, column_name: str) -> str: +async def get_column_profile(table_name: str, column_name: str, runtime: Runtime = None) -> str: """ Retrieves the latest stored statistics for a single specific column. @@ -180,7 +184,9 @@ async def get_column_profile(table_name: str, column_name: str) -> str: column_name (str): The exact name of the column to profile. """ try: - profile = await get_jeen_metadata_client().get_column_profile(table_name, column_name) + profile = await get_jeen_metadata_client().get_column_profile( + table_name, column_name, connection_id=connection_id(runtime) + ) except Exception as e: return _metadata_failure(f"get_column_profile({table_name}.{column_name})", e) if not profile: @@ -351,7 +357,7 @@ def validate_sql(sql: str) -> str: # --------------------------------------------------------------------------- @tool -async def search_metadata(query: str, limit: int = 10) -> str: +async def search_metadata(query: str, limit: int = 10, runtime: Runtime = None) -> str: """ Searches the metadata catalog across all tables, columns, relationships, and business terms. @@ -365,13 +371,13 @@ async def search_metadata(query: str, limit: int = 10) -> str: limit (int): Maximum number of results to return. Defaults to 10. """ try: - return ok(await get_jeen_metadata_client().search(query, limit)) + return ok(await get_jeen_metadata_client().search(query, limit, connection_id=connection_id(runtime))) except Exception as e: return _metadata_failure("search_metadata", e) @tool -async def search_business_terms(query: str, limit: int = 10) -> str: +async def search_business_terms(query: str, limit: int = 10, runtime: Runtime = None) -> str: """ Searches the business glossary for terms relevant to a natural language question. @@ -383,16 +389,17 @@ async def search_business_terms(query: str, limit: int = 10) -> str: query (str): A natural language question or phrase (multilingual support). limit (int): Maximum number of results to return. Defaults to 10. """ - if not _connection_capabilities.get("has_business_terms", True): + if not capability(runtime, "business_terms"): return ok({"terms": [], "notice": "This connection has NO business terms defined. Do not call this tool again."}) try: - return ok(await get_jeen_metadata_client().search_business_terms(query, limit)) + terms = await get_jeen_metadata_client().search_business_terms(query, limit, connection_id=connection_id(runtime)) + return ok(terms) except Exception as e: return _metadata_failure("search_business_terms", e) @tool -async def search_knowledge_pairs(query: str, limit: int = 10) -> str: +async def search_knowledge_pairs(query: str, limit: int = 10, runtime: Runtime = None) -> str: """ Searches saved question-and-query examples that are semantically similar to the user's question. @@ -407,10 +414,11 @@ async def search_knowledge_pairs(query: str, limit: int = 10) -> str: query (str): The natural language user question (multilingual/Hebrew support). limit (int): Maximum number of results to return. Defaults to 10. """ - if not _connection_capabilities.get("has_knowledge_pairs", True): + if not capability(runtime, "knowledge_pairs"): return ok({"pairs": [], "notice": "This connection has NO knowledge pairs defined. Do not call this tool again."}) try: - return ok(await get_jeen_metadata_client().search_knowledge_pairs(query, limit)) + pairs = await get_jeen_metadata_client().search_knowledge_pairs(query, limit, connection_id=connection_id(runtime)) + return ok(pairs) except Exception as e: return _metadata_failure("search_knowledge_pairs", e) @@ -440,6 +448,7 @@ async def search_column_values( table: Optional[str] = None, column: Optional[str] = None, limit: int = 10, + runtime: Runtime = None, ) -> str: """ Searches for exact real values contained within indexed columns across the database. @@ -469,7 +478,8 @@ async def search_column_values( """ try: res = await get_jeen_metadata_client().search_column_values( - search_term=search_term, table=table, column=column, limit=limit, raw=True + search_term=search_term, table=table, column=column, limit=limit, raw=True, + connection_id=connection_id(runtime), ) except Exception as e: return _metadata_failure("search_column_values", e) diff --git a/agent/tests/deep_agent/conftest.py b/agent/tests/deep_agent/conftest.py index a452986..fa82162 100644 --- a/agent/tests/deep_agent/conftest.py +++ b/agent/tests/deep_agent/conftest.py @@ -1,8 +1,9 @@ -from collections.abc import Iterator +from collections.abc import Callable import pytest from langchain_core.language_models.fake_chat_models import GenericFakeChatModel from langchain_core.messages import AIMessage, BaseMessage +from langchain_core.outputs import ChatGeneration, ChatResult class ScriptedChatModel(GenericFakeChatModel): @@ -30,3 +31,26 @@ def _make(*replies: AIMessage) -> ScriptedChatModel: def system_text(messages: list[BaseMessage]) -> str: return "\n".join(m.text for m in messages if m.type == "system") + + +class PolicyChatModel(ScriptedChatModel): + """Fake chat model whose next reply is computed from the conversation so far. + + Safe to share across concurrent threads (unlike a scripted iterator). + """ + + policy: Callable[[list[BaseMessage]], AIMessage] | None = None + + def _generate(self, messages, stop=None, run_manager=None, **kwargs): + self.seen.append(list(messages)) + return ChatResult(generations=[ChatGeneration(message=self.policy(messages))]) + + +@pytest.fixture +def policy_model(): + def _make(policy: Callable[[list[BaseMessage]], AIMessage]) -> PolicyChatModel: + model = PolicyChatModel(messages=iter([]), policy=policy) + model.seen = [] + return model + + return _make diff --git a/agent/tests/deep_agent/test_runtime_context.py b/agent/tests/deep_agent/test_runtime_context.py new file mode 100644 index 0000000..5f4d390 --- /dev/null +++ b/agent/tests/deep_agent/test_runtime_context.py @@ -0,0 +1,120 @@ +import asyncio +import json +from datetime import datetime, timezone +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from langchain_core.messages import AIMessage + +import deep_agent.context as context_module +from deep_agent import tools +from deep_agent.agent import create_deep_agent +from deep_agent.context import DeepAgentContext, date_line +from tests.deep_agent.conftest import system_text + +NO_PAIRS_CATALOG = "# catalog for connection 1\n(no knowledge pairs)" +FULL_CATALOG = "# catalog for connection 2\nknowledge pairs: 3" + + +def _catalog_then_pairs_policy(messages): + """Thread-local behaviour: fetch catalog, then search knowledge pairs, then answer.""" + tool_msgs = [m for m in messages if m.type == "tool"] + if not tool_msgs: + return AIMessage("", tool_calls=[{"name": "get_database_catalog", "args": {}, "id": "c1"}]) + if tool_msgs[-1].name == "get_database_catalog": + return AIMessage("", tool_calls=[{"name": "search_knowledge_pairs", "args": {"query": "כמה טיסות"}, "id": "k1"}]) + return AIMessage("done") + + +def _metadata_client(): + async def catalog(connection_id=None): + await asyncio.sleep(0.01) # force interleaving between the two requests + return NO_PAIRS_CATALOG if connection_id == 1 else FULL_CATALOG + + async def pairs(query, limit=10, connection_id=None): + await asyncio.sleep(0.01) + return [{"question": query, "connection": connection_id}] + + return MagicMock(get_catalog_prompt=AsyncMock(side_effect=catalog), + search_knowledge_pairs=AsyncMock(side_effect=pairs)) + + +@pytest.mark.asyncio +async def test_concurrent_requests_for_different_connections_are_isolated(policy_model): + agent = create_deep_agent(model=policy_model(_catalog_then_pairs_policy)) + client = _metadata_client() + + with patch.object(tools, "get_jeen_metadata_client", return_value=client): + r1, r2 = await asyncio.gather( + agent.ainvoke({"messages": [("user", "q1")]}, {"configurable": {"thread_id": "conn-1"}}, + context=DeepAgentContext(connection_id=1)), + agent.ainvoke({"messages": [("user", "q2")]}, {"configurable": {"thread_id": "conn-2"}}, + context=DeepAgentContext(connection_id=2)), + ) + + # Each request fetched its own catalog... + assert sorted(c.kwargs["connection_id"] for c in client.get_catalog_prompt.await_args_list) == [1, 2] + # ...capabilities landed in each thread's own state... + assert r1["connection_capabilities"]["knowledge_pairs"] is False + assert r2["connection_capabilities"]["knowledge_pairs"] is True + # ...so only connection 2 actually searched knowledge pairs, with its own connection id. + client.search_knowledge_pairs.assert_awaited_once() + assert client.search_knowledge_pairs.await_args.kwargs["connection_id"] == 2 + + pairs_1 = json.loads(next(m for m in r1["messages"] if m.type == "tool" and m.name == "search_knowledge_pairs").text) + pairs_2 = json.loads(next(m for m in r2["messages"] if m.type == "tool" and m.name == "search_knowledge_pairs").text) + assert pairs_1["data"]["pairs"] == [] and "NO knowledge pairs" in pairs_1["data"]["notice"] + assert pairs_2["data"] == [{"question": "כמה טיסות", "connection": 2}] + + +@pytest.mark.asyncio +async def test_no_context_falls_back_to_default_connection(policy_model): + agent = create_deep_agent(model=policy_model(_catalog_then_pairs_policy)) + client = _metadata_client() + with patch.object(tools, "get_jeen_metadata_client", return_value=client): + await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "default"}}) + assert client.get_catalog_prompt.await_args.kwargs["connection_id"] is None # client uses its configured default + + +class _FrozenDatetime(datetime): + instant = datetime(2026, 10, 20, 20, 30, tzinfo=timezone.utc) + + @classmethod + def now(cls, tz=None): + return cls.instant.astimezone(tz) + + +def test_date_is_computed_in_jerusalem_time(monkeypatch): + monkeypatch.setattr(context_module, "datetime", _FrozenDatetime) + _FrozenDatetime.instant = datetime(2026, 10, 20, 21, 30, tzinfo=timezone.utc) # 00:30 on Oct 21 in Israel (UTC+3) + assert date_line("Asia/Jerusalem").startswith("Today's date: 2026-10-21 (Wednesday") + assert date_line("UTC").startswith("Today's date: 2026-10-20") + + +@pytest.mark.asyncio +async def test_date_is_injected_per_model_call_not_at_construction(scripted_model, monkeypatch): + monkeypatch.setattr(context_module, "datetime", _FrozenDatetime) + model = scripted_model(AIMessage("first"), AIMessage("second")) + agent = create_deep_agent(model=model) # built "yesterday" + + _FrozenDatetime.instant = datetime(2026, 10, 20, 20, 30, tzinfo=timezone.utc) # 23:30 Oct 20 in Israel + await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "d1"}}) + _FrozenDatetime.instant = datetime(2026, 10, 20, 21, 30, tzinfo=timezone.utc) # 00:30 Oct 21 in Israel + await agent.ainvoke({"messages": [("user", "b")]}, {"configurable": {"thread_id": "d2"}}) + + def last_human(messages): + return next(m for m in reversed(messages) if m.type == "human").text + + assert last_human(model.seen[0]).startswith("[Today's date: 2026-10-20") + assert last_human(model.seen[1]).startswith("[Today's date: 2026-10-21") + assert last_human(model.seen[1]).endswith("b") + # The system prompt is byte-identical across days, so provider prompt caching keeps working. + assert system_text(model.seen[0]) == system_text(model.seen[1]) + assert "Today's date" not in system_text(model.seen[1]) + + +@pytest.mark.asyncio +async def test_date_prefix_is_not_persisted_to_state(scripted_model): + agent = create_deep_agent(model=scripted_model(AIMessage("ok"))) + result = await agent.ainvoke({"messages": [("user", "שאלה")]}, {"configurable": {"thread_id": "p1"}}) + assert result["messages"][0].text == "שאלה" diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py index c48c711..4efd325 100644 --- a/agent/tests/deep_agent/test_tool_contracts.py +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -45,11 +45,6 @@ def _client(fail: bool) -> MagicMock: return client -@pytest.fixture(autouse=True) -def _reset_capabilities(): - tools._connection_capabilities.update(has_knowledge_pairs=True, has_business_terms=True, has_relationships=True) - - @pytest.fixture def patched(request): fail = request.param @@ -98,7 +93,6 @@ async def test_catalog_is_plain_text_with_capabilities_note(): raw = await tools.get_database_catalog.ainvoke({}) assert raw.startswith('"postgres"."public"."t"') # quotes not JSON-escaped assert "Knowledge Pairs: None (skip search_knowledge_pairs)" in raw - assert tools._connection_capabilities["has_knowledge_pairs"] is False @pytest.mark.asyncio From 1f7c702cf879d892b67c911b1c49d2ddfaacb94a Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 26 Oct 2026 16:32:32 +0200 Subject: [PATCH 12/37] perf(deep-agent): stop making the model re-emit the catalog for enrich_sql_filters (#36) Based on deep-agent/36-catalog-state (071782e), adapted to the revised stack: - get_database_catalog caches the raw catalog in the thread's state (jeen_catalog) - enrich_sql_filters takes only {sql}: the catalog comes from state (fetched once and cached if missing); the user request is every human message in the thread, oldest first, so a reply to a clarifying question is appended to the original question instead of replacing it - ToolRuntime.config forwarded to EnrichmentOrchestrator so enrichment LLM calls are children of the agent trace - INVALID_INPUT removed from the envelope (no longer used) Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/context.py | 22 +++- agent/src/deep_agent/envelope.py | 1 - agent/src/deep_agent/tools.py | 45 ++++--- agent/tests/deep_agent/test_catalog_state.py | 112 ++++++++++++++++++ agent/tests/deep_agent/test_tool_contracts.py | 2 +- 5 files changed, 163 insertions(+), 19 deletions(-) create mode 100644 agent/tests/deep_agent/test_catalog_state.py diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index d20f264..c525cc2 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -4,8 +4,9 @@ Nothing request-specific lives in module globals: - DeepAgentContext is passed per invocation (`agent.ainvoke(..., context=DeepAgentContext(...))`) and read by tools through `ToolRuntime.context`. -- Connection capabilities discovered by get_database_catalog are written to graph state - (`connection_capabilities`) and read back by tools through `ToolRuntime.state`. +- Connection capabilities and the raw catalog fetched by get_database_catalog are written to + graph state (`connection_capabilities`, `jeen_catalog`) and read back by tools through + `ToolRuntime.state`. - Today's date is added to the latest human message on every model call, in the context's timezone, so long-running processes never serve a stale date. """ @@ -32,6 +33,7 @@ class DeepAgentContext: class DeepAgentRuntimeState(AgentState): connection_capabilities: NotRequired[dict[str, bool]] + jeen_catalog: NotRequired[str] # raw catalog text, cached so tools never need the model to re-send it def connection_id(runtime: ToolRuntime | None) -> int | None: @@ -45,6 +47,22 @@ def capability(runtime: ToolRuntime | None, name: str) -> bool: return bool((state.get("connection_capabilities") or {}).get(name, True)) +def cached_catalog(runtime: ToolRuntime | None) -> str | None: + state = getattr(runtime, "state", None) or {} + return state.get("jeen_catalog") or None + + +def user_request(runtime: ToolRuntime | None) -> str: + """Every human message in the thread, oldest first, one per line. + + A reply to a clarifying question arrives as a new human message on the same thread, so the + request being answered is the original question plus those replies — not just the last one. + """ + state = getattr(runtime, "state", None) or {} + texts = [msg.text for msg in state.get("messages") or [] if isinstance(msg, HumanMessage) and msg.text.strip()] + return "\n".join(texts) + + def _now(tz: str) -> datetime: return datetime.now(ZoneInfo(tz)) diff --git a/agent/src/deep_agent/envelope.py b/agent/src/deep_agent/envelope.py index b811460..986bcab 100644 --- a/agent/src/deep_agent/envelope.py +++ b/agent/src/deep_agent/envelope.py @@ -15,7 +15,6 @@ METADATA_ERROR = "METADATA_ERROR" # the Jeen metadata service failed or returned an unexpected payload NOT_FOUND = "NOT_FOUND" # the metadata service has nothing stored for the requested object -INVALID_INPUT = "INVALID_INPUT" # the tool arguments could not be used ENRICHMENT_ERROR = "ENRICHMENT_ERROR" # filter enrichment failed; the SQL is unchanged LOCATION_NOT_FOUND = "LOCATION_NOT_FOUND" # the location could not be resolved to an area diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index b29f470..5678afd 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -22,10 +22,9 @@ from agent.utils.sql_guard import effective_cap from core.trino import execute_query_sync from deep_agent import trino_errors -from deep_agent.context import DeepAgentContext, capability, connection_id +from deep_agent.context import DeepAgentContext, cached_catalog, capability, connection_id, user_request from deep_agent.envelope import ( ENRICHMENT_ERROR, - INVALID_INPUT, LOCATION_NOT_FOUND, METADATA_ERROR, NOT_FOUND, @@ -92,9 +91,10 @@ async def get_database_catalog(runtime: Runtime = None) -> str | Command: content = catalog_prompt + "\n".join(footer_lines) if runtime is None or not runtime.tool_call_id: return content - # Record capabilities in this thread's state so later tool calls in the thread can read them. + # Record capabilities + the raw catalog in this thread's state so later tool calls in the thread can read them. return Command(update={ "connection_capabilities": {"knowledge_pairs": has_kp, "business_terms": has_bt, "relationships": has_fk}, + "jeen_catalog": catalog_prompt, "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="get_database_catalog")], }) @@ -498,11 +498,7 @@ async def search_column_values( # --------------------------------------------------------------------------- @tool -async def enrich_sql_filters( - user_request: str, - sql: str, - jeen_catalog: str, -) -> str: +async def enrich_sql_filters(sql: str, runtime: Runtime = None) -> str | Command: """ Automatically corrects categorical filter values in a draft SQL query to match exact database spellings using semantic search and LLM-guided AST transformation. @@ -514,6 +510,9 @@ async def enrich_sql_filters( 3. Use an LLM to select the best match 4. Rewrite the SQL with exact canonical values (AST-level, not string replacement) + The catalog and the user's question are taken from the conversation automatically — + pass only the SQL. + This is especially powerful for Hebrew→English column value resolution and large categorical columns where manually calling search_column_values for every filter would be tedious. @@ -523,26 +522,34 @@ async def enrich_sql_filters( data.changes (one entry per corrected filter). Args: - user_request (str): The original natural language request from the user (Hebrew). sql (str): The draft SQL query to enrich. - jeen_catalog (str): The full catalog string (output of get_database_catalog). """ from agent.nodes.refiner import parse_jeen_catalog_tables from agent.services.enrichment_orchestrator import EnrichmentOrchestrator sql_clean = clean_sql(sql) + + catalog = cached_catalog(runtime) + fetched_catalog = False + if not catalog: + try: + catalog = await get_jeen_metadata_client().get_catalog_prompt(connection_id=connection_id(runtime)) + except Exception as e: + return _metadata_failure("enrich_sql_filters (catalog fetch)", e) + fetched_catalog = True + try: - schema, tables = parse_jeen_catalog_tables(jeen_catalog) + schema, tables = parse_jeen_catalog_tables(catalog) if not tables: - return fail(error(INVALID_INPUT, "Could not parse any tables from jeen_catalog; pass the catalog unchanged.", + return fail(error(ENRICHMENT_ERROR, "No tables could be parsed from the connection catalog. The SQL is unchanged.", original_sql=sql_clean)) refined_sql, plan, enriched = await EnrichmentOrchestrator.enrich_query( - user_request=user_request, + user_request=user_request(runtime), initial_sql=sql_clean, schema=schema, tables=tables, - config=None, + config=runtime.config if runtime is not None else None, ) except Exception as e: logger.error("enrich_sql_filters failed: %s", e, exc_info=True) @@ -562,7 +569,15 @@ async def enrich_sql_filters( if tf.changed_filter ] is_enriched = bool(enriched and plan) - return ok({"enriched": is_enriched, "sql": refined_sql if is_enriched else sql_clean, "changes": changes}) + content = ok({"enriched": is_enriched, "sql": refined_sql if is_enriched else sql_clean, "changes": changes}) + + if fetched_catalog and runtime is not None and runtime.tool_call_id: + # Cache the catalog we had to fetch so the next call in this thread doesn't refetch it. + return Command(update={ + "jeen_catalog": catalog, + "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="enrich_sql_filters")], + }) + return content # --------------------------------------------------------------------------- diff --git a/agent/tests/deep_agent/test_catalog_state.py b/agent/tests/deep_agent/test_catalog_state.py new file mode 100644 index 0000000..6ec1272 --- /dev/null +++ b/agent/tests/deep_agent/test_catalog_state.py @@ -0,0 +1,112 @@ +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from langchain_core.callbacks import AsyncCallbackHandler +from langchain_core.messages import AIMessage + +from deep_agent import tools +from deep_agent.agent import create_deep_agent + +CATALOG = '# Jeen Catalog\n"postgres"."public"."flights_table"\n| launch_country | varchar | categorical |' +QUESTION = "כמה טיסות המריאו מצרפת" +DRAFT = "SELECT COUNT(*) FROM \"postgres\".\"public\".\"flights_table\" WHERE launch_country = 'צרפת'" + + +class Marker(AsyncCallbackHandler): + """A caller-supplied callback handler; it must reach the enrichment LLM calls.""" + + +def _policy(first_tool: str): + def policy(messages): + tool_msgs = [m for m in messages if m.type == "tool"] + steps = [first_tool, "enrich_sql_filters", "enrich_sql_filters"] if first_tool == "enrich_sql_filters" \ + else ["get_database_catalog", "enrich_sql_filters"] + if len(tool_msgs) < len(steps): + name = steps[len(tool_msgs)] + args = {"sql": DRAFT} if name == "enrich_sql_filters" else {} + return AIMessage("", tool_calls=[{"name": name, "args": args, "id": f"t{len(tool_msgs)}"}]) + return AIMessage("done") + return policy + + +@pytest.fixture +def enrichment(): + plan = SimpleNamespace(enrichment_details=[SimpleNamespace( + changed_filter=True, column="launch_country", original_value="צרפת", refined_values=["France"], + old_operator="=", new_operator="=", + )]) + enrich = AsyncMock(return_value=(DRAFT.replace("'צרפת'", "'France'"), plan, True)) + parse = MagicMock(return_value=({"flights_table": {"launch_country": "varchar"}}, ["flights_table"])) + client = MagicMock(get_catalog_prompt=AsyncMock(return_value=CATALOG)) + with patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", enrich), \ + patch("agent.nodes.refiner.parse_jeen_catalog_tables", parse), \ + patch.object(tools, "get_jeen_metadata_client", return_value=client): + yield SimpleNamespace(enrich=enrich, parse=parse, client=client) + + +@pytest.mark.asyncio +async def test_enrichment_uses_cached_catalog_question_and_parent_config(policy_model, enrichment): + agent = create_deep_agent(model=policy_model(_policy("get_database_catalog"))) + marker = Marker() + result = await agent.ainvoke( + {"messages": [("user", QUESTION)]}, + {"configurable": {"thread_id": "e1"}, "callbacks": [marker]}, + ) + + assert result["jeen_catalog"] == CATALOG + enrichment.client.get_catalog_prompt.assert_awaited_once() # fetched once, by the catalog tool + enrichment.parse.assert_called_once_with(CATALOG) # exact cached text, not a model re-typing + + kwargs = enrichment.enrich.await_args.kwargs + assert kwargs["user_request"] == QUESTION + assert kwargs["initial_sql"] == DRAFT + config = kwargs["config"] + assert config is not None + handlers = getattr(config.get("callbacks"), "handlers", config.get("callbacks")) or [] + assert marker in handlers, "caller callbacks (Langfuse) must propagate into enrichment" + + enrich_msg = next(m for m in result["messages"] if m.type == "tool" and m.name == "enrich_sql_filters") + assert "'France'" in enrich_msg.text + + +@pytest.mark.asyncio +async def test_enrichment_before_catalog_fetches_once_and_caches(policy_model, enrichment): + agent = create_deep_agent(model=policy_model(_policy("enrich_sql_filters"))) + result = await agent.ainvoke({"messages": [("user", QUESTION)]}, {"configurable": {"thread_id": "e2"}}) + + assert result["jeen_catalog"] == CATALOG + assert enrichment.enrich.await_count == 3 + enrichment.client.get_catalog_prompt.assert_awaited_once() # later calls hit the state cache + + +@pytest.mark.asyncio +async def test_catalog_fetch_failure_is_reported(policy_model, enrichment): + enrichment.client.get_catalog_prompt.side_effect = RuntimeError("mcp down") + out = await tools.enrich_sql_filters.ainvoke({"sql": DRAFT}) + assert '"name":"METADATA_ERROR"' in out + enrichment.enrich.assert_not_awaited() + + +def test_model_only_supplies_sql(): + props = tools.enrich_sql_filters.tool_call_schema.model_json_schema()["properties"] + assert list(props) == ["sql"] + + +@pytest.mark.asyncio +async def test_enrichment_after_clarification_gets_the_question_and_the_reply(policy_model, enrichment): + """The reply to a clarifying question arrives as a new user message; it must not replace the question.""" + def policy(messages): + humans = [m for m in messages if m.type == "human"] + if len(humans) == 1: + return AIMessage("לאיזה מחוז הכוונה?") # clarifying question, no tools + if messages[-1].type == "human": + return AIMessage("", tool_calls=[{"name": "enrich_sql_filters", "args": {"sql": DRAFT}, "id": "e"}]) + return AIMessage("done") + + agent = create_deep_agent(model=policy_model(policy)) + config = {"configurable": {"thread_id": "clarify"}} + await agent.ainvoke({"messages": [("user", "כמה טיסות המריאו מהמחוז הצפוני")]}, config) + await agent.ainvoke({"messages": [("user", "חיפה")]}, config) + + assert enrichment.enrich.await_args.kwargs["user_request"] == "כמה טיסות המריאו מהמחוז הצפוני\nחיפה" diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py index 4efd325..c82d2dd 100644 --- a/agent/tests/deep_agent/test_tool_contracts.py +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -28,7 +28,7 @@ "get_sample_rows": {"table_name": "t"}, "get_column_distinct_values": {"table_name": "t", "column_name": "c"}, "validate_sql": {"sql": "SELECT 1"}, - "enrich_sql_filters": {"user_request": "q", "sql": "SELECT 1 FROM t WHERE a = 'x'", "jeen_catalog": "cat"}, + "enrich_sql_filters": {"sql": "SELECT 1 FROM t WHERE a = 'x'"}, } From 9f5ac66951b7c03f822e139bbce2fa5e9edba8c7 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 26 Oct 2026 17:20:49 +0200 Subject: [PATCH 13/37] feat(deep-agent): end-to-end Langfuse tracing with span metadata and run scores (#37) Based on deep-agent/37-tracing (0253804), adapted to the revised stack: - observability.py: build_run_config() (Langfuse handler, session/user/tags, agent_version + connection_id metadata, run_name) so every run is one trace - Trino tools annotate their observation with trino_query_id, execution_time_ms, row_count, truncated, or Trino's raw error_name / error_type at level ERROR; execution_time_ms also in the envelope - run scores are plain facts only: model_calls, tool_calls, sql_executions, latency_s (no "any query succeeded" / text-heuristic final-SQL scores) - CLI uses build_run_config, scores the run, prints the trace id, flushes - DEEP_AGENT_TRACING_ENABLED setting; README tracing section Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 10 + agent/src/agent/config.py | 1 + agent/src/deep_agent/cli.py | 14 +- agent/src/deep_agent/observability.py | 144 +++++++++++++ agent/src/deep_agent/tools.py | 24 ++- agent/tests/deep_agent/test_observability.py | 216 +++++++++++++++++++ agent/tests/deep_agent/test_trino_errors.py | 1 + 7 files changed, 406 insertions(+), 4 deletions(-) create mode 100644 agent/src/deep_agent/observability.py create mode 100644 agent/tests/deep_agent/test_observability.py diff --git a/agent/README.md b/agent/README.md index e188a79..3d32294 100644 --- a/agent/README.md +++ b/agent/README.md @@ -60,3 +60,13 @@ Every SQL the deep agent runs goes through `agent/utils/sql_guard.py` (sqlglot, - table and column names in `get_sample_rows` / `get_column_distinct_values` are parsed and quoted by sqlglot, never string-interpolated The guard is an application-level control. The Trino principal used by the agent should also be SELECT-only. + +### Tracing (deep agent) + +Every deep-agent run is **one Langfuse trace** built by `deep_agent.observability.build_run_config()`: +- session = thread id, user = `user_id`, tag `deep-agent`, metadata `agent_version` (`DEEP_AGENT_VERSION` env, e.g. the git SHA, else the package version) and `connection_id` +- all model calls, tool calls, subagent calls and enrichment LLM calls are nested observations +- `execute_trino_query` / `get_sample_rows` / `get_column_distinct_values` observations carry `trino_query_id`, `execution_time_ms`, `row_count`, `truncated` (or Trino's `error_name` / `error_type`) as metadata +- run-level scores: `deep-agent.model_calls`, `.tool_calls`, `.sql_executions`, `.latency_s` + +In Langfuse, filter traces by **tag = `deep-agent`** (save it as a view). Disable tracing with `DEEP_AGENT_TRACING_ENABLED=false`. diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 5972609..398604d 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -51,6 +51,7 @@ class AgentSettings(BaseSettings): # Row ceilings for the deep agent's SQL tools. Set to "none" (or empty) to disable the ceiling. DEEP_AGENT_MAX_ROWS: int | None = Field(default=100, gt=0) # execute_trino_query / get_column_distinct_values DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows + DEEP_AGENT_TRACING_ENABLED: bool = True # Langfuse callbacks, span metadata and run scores # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" diff --git a/agent/src/deep_agent/cli.py b/agent/src/deep_agent/cli.py index 1ad9ee1..1e52328 100644 --- a/agent/src/deep_agent/cli.py +++ b/agent/src/deep_agent/cli.py @@ -21,6 +21,7 @@ from agent.config import settings from deep_agent.agent import create_deep_agent +from deep_agent import observability from deep_agent.context import DeepAgentContext # ANSI Colors for terminal output @@ -153,7 +154,9 @@ async def run_query( print(f"{DIM} Thread: {thread_id}{RESET}") print(f"{CYAN}{BOLD}{'='*80}{RESET}\n") - config = {"configurable": {"thread_id": thread_id}} + config = observability.build_run_config( + thread_id, user_id=context.user_id, connection_id=context.connection_id + ) start_time = time.time() final_state = None @@ -173,6 +176,8 @@ async def run_query( return final_sql, clean_answer = extract_final_sql_and_answer(final_state["messages"]) + trace_id = observability.langfuse_trace_id(config) + observability.score_run(trace_id, observability.run_metrics(final_state["messages"], execution_time)) if log_file is not None: append_run_record( @@ -191,6 +196,8 @@ async def run_query( f"\n{GREEN}{BOLD}[Run finished] Execution time: {execution_time}s, " f"Final SQL captured: {'Yes' if final_sql else 'None'}{RESET}" ) + if trace_id: + print(f"{DIM} Langfuse trace: {trace_id}{RESET}") if final_sql: print(f"\n{CYAN}{BOLD}{'='*30} FINAL GENERATED SQL {'='*30}{RESET}") print(f"{GREEN}{final_sql}{RESET}") @@ -275,7 +282,10 @@ def main() -> None: print(f"{RED}{BOLD}Error: You must provide a query or run with --interactive{RESET}\n") parser.print_help() raise SystemExit(2) - asyncio.run(_amain(args)) + try: + asyncio.run(_amain(args)) + finally: + observability.flush() if __name__ == "__main__": diff --git a/agent/src/deep_agent/observability.py b/agent/src/deep_agent/observability.py new file mode 100644 index 0000000..601263a --- /dev/null +++ b/agent/src/deep_agent/observability.py @@ -0,0 +1,144 @@ +""" +Langfuse tracing for the Deep Agent. + +- build_run_config(): the one RunnableConfig every deep-agent run (CLI and API) uses — + Langfuse CallbackHandler + session/user/tags metadata, so a run is exactly one trace. +- annotate_current_span(): structured metadata on the current tool observation. Only + reliable for *sync* tools: LangChain runs the (sync) Langfuse handler for async tools in + a copied context, so their span is not current inside the tool. Every tool therefore + also carries its telemetry in its envelope output, which Langfuse always records. +- run_metrics() / score_run(): end-of-run scores on the trace. +""" + +import logging +import os +from dataclasses import asdict, dataclass +from importlib.metadata import PackageNotFoundError, version +from typing import Any + +from langchain_core.callbacks import BaseCallbackHandler +from langchain_core.messages import BaseMessage +from langchain_core.runnables import RunnableConfig + +from agent.config import settings + +logger = logging.getLogger(__name__) + +AGENT_NAME = "deep-agent" + + +def agent_version() -> str: + """DEEP_AGENT_VERSION (e.g. the git SHA injected at build time), else the package version.""" + explicit = os.environ.get("DEEP_AGENT_VERSION") + if explicit: + return explicit + try: + return version("agent") + except PackageNotFoundError: + return "dev" + + +def _langfuse_handler() -> BaseCallbackHandler | None: + from core.langfuse import get_langfuse_handler + + return get_langfuse_handler() + + +def build_run_config( + thread_id: str, + *, + user_id: str | None = None, + connection_id: int | None = None, + callbacks: list[BaseCallbackHandler] | None = None, + tracing: bool | None = None, +) -> RunnableConfig: + """RunnableConfig for one deep-agent invocation: one Langfuse trace per run, grouped by thread.""" + handlers = list(callbacks or []) + if tracing if tracing is not None else settings.DEEP_AGENT_TRACING_ENABLED: + handler = _langfuse_handler() + if handler is not None: + handlers.append(handler) + + metadata: dict[str, Any] = { + "langfuse_session_id": thread_id, + "langfuse_tags": [AGENT_NAME], + "agent": AGENT_NAME, + "agent_version": agent_version(), + "connection_id": connection_id if connection_id is not None else settings.JEEN_METADATA_CONNECTION_ID, + } + if user_id: + metadata["langfuse_user_id"] = user_id + + return RunnableConfig( + configurable={"thread_id": thread_id}, + callbacks=handlers, + metadata=metadata, + tags=[AGENT_NAME], + run_name=AGENT_NAME, + ) + + +def langfuse_trace_id(config: RunnableConfig) -> str | None: + for handler in config.get("callbacks") or []: + trace_id = getattr(handler, "last_trace_id", None) + if trace_id: + return trace_id + return None + + +def annotate_current_span(metadata: dict[str, Any], level: str | None = None) -> None: + """Best-effort metadata on the current Langfuse observation (no-op without an active span).""" + if not settings.DEEP_AGENT_TRACING_ENABLED: + return + try: + from agent.langfuse_client import langfuse_client + + langfuse_client.update_current_span(metadata=metadata, level=level) + except Exception as exc: # telemetry must never break a tool + logger.debug("annotate_current_span skipped: %s", exc) + + +@dataclass(frozen=True) +class RunMetrics: + """Plain counts and timing for one run. Whether the *final* SQL ran is not known here: + the run ends in free text, with no structured final answer to check.""" + + model_calls: int + tool_calls: int + sql_executions: int + latency_s: float + + +def run_metrics(messages: list[BaseMessage], latency_s: float) -> RunMetrics: + ai = [m for m in messages if m.type == "ai"] + return RunMetrics( + model_calls=len(ai), + tool_calls=sum(len(getattr(m, "tool_calls", None) or []) for m in ai), + sql_executions=sum(1 for m in messages if m.type == "tool" and m.name == "execute_trino_query"), + latency_s=round(latency_s, 2), + ) + + +def score_run(trace_id: str | None, metrics: RunMetrics) -> None: + """Attach run-level scores to the Langfuse trace (no-op without a trace).""" + if not trace_id or not settings.DEEP_AGENT_TRACING_ENABLED: + return + try: + from agent.langfuse_client import langfuse_client + + for name, value in asdict(metrics).items(): + data_type = "BOOLEAN" if isinstance(value, bool) else "NUMERIC" + langfuse_client.create_score( + trace_id=trace_id, name=f"{AGENT_NAME}.{name}", value=float(value), data_type=data_type + ) + except Exception as exc: + logger.warning("score_run failed for trace %s: %s", trace_id, exc) + + +def flush() -> None: + try: + from agent.langfuse_client import langfuse_client + + langfuse_client.flush() + except Exception as exc: + logger.debug("langfuse flush skipped: %s", exc) diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 5678afd..43b57b6 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -32,6 +32,7 @@ fail, ok, ) +from deep_agent.observability import annotate_current_span logger = logging.getLogger(__name__) @@ -202,24 +203,43 @@ def _run_sql(sql: str, row_cap: int | None) -> str: """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation. row_cap=None means no ceiling: every returned row is passed through. + Telemetry (query id, timing, row count / Trino error) goes both into the envelope + and onto the current Langfuse tool observation. """ try: res = execute_query_sync(sql) except Exception as e: - return fail(trino_errors.from_exception(e)) + err = trino_errors.from_exception(e) + annotate_current_span({"error_name": err["name"]}, level="ERROR") + return fail(err) if not res.success: - return fail(trino_errors.from_result(res)) + err = trino_errors.from_result(res) + err["execution_time_ms"] = res.execution_time_ms + annotate_current_span({ + "trino_query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, + "error_name": err["name"], + "error_type": err.get("type"), + }, level="ERROR") + return fail(err) rows = res.rows or [] truncated = row_cap is not None and len(rows) > row_cap if truncated: rows = rows[:row_cap] + annotate_current_span({ + "trino_query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, + "row_count": len(rows), + "truncated": truncated, + }) return ok({ "columns": res.columns, "row_count": len(rows), "truncated": truncated, "rows": rows, "query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, }) diff --git a/agent/tests/deep_agent/test_observability.py b/agent/tests/deep_agent/test_observability.py new file mode 100644 index 0000000..72e87b4 --- /dev/null +++ b/agent/tests/deep_agent/test_observability.py @@ -0,0 +1,216 @@ +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch +from uuid import UUID + +import pytest +from langchain_core.callbacks import BaseCallbackHandler +from langchain_core.language_models.fake_chat_models import GenericFakeChatModel +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage + +from core.trino import TrinoExecutionResult +from deep_agent import observability, tools +from deep_agent.agent import create_deep_agent +from deep_agent.observability import RunMetrics, build_run_config, run_metrics + + +class RunTreeRecorder(BaseCallbackHandler): + """Records every run's id/parent so we can assert the trace is one tree with no orphans.""" + + def __init__(self): + self.runs: dict[UUID, dict] = {} + + def _add(self, kind, serialized, run_id, parent_run_id, **kwargs): + name = kwargs.get("name") or (serialized or {}).get("name") + self.runs[run_id] = {"kind": kind, "name": name, "parent": parent_run_id} + + def on_chain_start(self, serialized, inputs, *, run_id, parent_run_id=None, **kwargs): + self._add("chain", serialized, run_id, parent_run_id, **kwargs) + + def on_tool_start(self, serialized, input_str, *, run_id, parent_run_id=None, **kwargs): + self._add("tool", serialized, run_id, parent_run_id, **kwargs) + + def on_chat_model_start(self, serialized, messages, *, run_id, parent_run_id=None, **kwargs): + self._add("llm", serialized, run_id, parent_run_id, **kwargs) + + def roots(self): + return [rid for rid, r in self.runs.items() if r["parent"] is None] + + def reaches(self, run_id, root): + while run_id is not None: + if run_id == root: + return True + run_id = self.runs.get(run_id, {}).get("parent") + return False + + +STEPS = [ + ("get_database_catalog", {}), + ("get_sample_rows", {"table_name": '"postgres"."public"."flights_table"'}), + ("execute_trino_query", {"sql": "SELECT COUNT(*) FROM flights_table WHERE launch_country = 'France'"}), + ("enrich_sql_filters", {"sql": "SELECT 1 FROM flights_table WHERE launch_country = 'צרפת'"}), +] + + +def _policy(messages): + done = len([m for m in messages if m.type == "tool"]) + if done < len(STEPS): + name, args = STEPS[done] + return AIMessage("", tool_calls=[{"name": name, "args": args, "id": f"t{done}"}]) + return AIMessage("תשובה\n```sql\nSELECT 1\n```") + + +@pytest.mark.asyncio +async def test_one_trace_tree_with_no_orphans(policy_model): + enrichment_llm = GenericFakeChatModel(messages=iter([AIMessage("pick France")])) + + async def fake_enrich(**kwargs): + # Like the real orchestrator: an LLM call made with the forwarded config. + await enrichment_llm.ainvoke("choose canonical value", config=kwargs["config"]) + return kwargs["initial_sql"], None, False + + recorder = RunTreeRecorder() + client = MagicMock(get_catalog_prompt=AsyncMock(return_value="# catalog")) + trino = TrinoExecutionResult(success=True, rows=[[466]], columns=["c"], row_count=1, query_id="q-1", + execution_time_ms=12) + agent = create_deep_agent(model=policy_model(_policy)) + config = build_run_config("thread-obs", user_id="u-1", callbacks=[recorder], tracing=False) + + with patch.object(tools, "get_jeen_metadata_client", return_value=client), \ + patch.object(tools, "execute_query_sync", return_value=trino), \ + patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=({"t": {}}, ["t"])), \ + patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", side_effect=fake_enrich): + await agent.ainvoke({"messages": [("user", "כמה טיסות")]}, config) + + roots = recorder.roots() + assert len(roots) == 1, f"expected exactly one root run, got {[recorder.runs[r] for r in roots]}" + root = roots[0] + + tool_runs = {r["name"] for r in recorder.runs.values() if r["kind"] == "tool"} + assert {name for name, _ in STEPS} <= tool_runs + llm_runs = [rid for rid, r in recorder.runs.items() if r["kind"] == "llm"] + assert len(llm_runs) >= len(STEPS) + 2 # agent turns + the enrichment LLM call + for rid, run in recorder.runs.items(): + assert recorder.reaches(rid, root), f"orphan run: {run}" + + +def test_build_run_config_sets_langfuse_metadata(): + handler = object() + with patch.object(observability, "_langfuse_handler", return_value=handler): + config = build_run_config("thread-1", user_id="user-7", connection_id=89, tracing=True) + assert config["configurable"] == {"thread_id": "thread-1"} + assert config["callbacks"] == [handler] + assert config["metadata"]["langfuse_session_id"] == "thread-1" + assert config["metadata"]["langfuse_user_id"] == "user-7" + assert config["metadata"]["langfuse_tags"] == ["deep-agent"] + assert config["metadata"]["connection_id"] == 89 + assert config["metadata"]["agent_version"] + assert config["tags"] == ["deep-agent"] + assert config["run_name"] == "deep-agent" + + +def test_build_run_config_without_tracing_has_no_langfuse_handler(): + with patch.object(observability, "_langfuse_handler") as factory: + config = build_run_config("t", tracing=False) + factory.assert_not_called() + assert config["callbacks"] == [] + + +def test_agent_version_prefers_explicit_env(monkeypatch): + monkeypatch.setenv("DEEP_AGENT_VERSION", "b8e27c8") + assert observability.agent_version() == "b8e27c8" + + +def test_trino_tools_annotate_the_tool_span(): + ok_res = TrinoExecutionResult(success=True, rows=[[1], [2]], columns=["a"], row_count=2, query_id="q-9", + execution_time_ms=34) + with patch.object(tools, "execute_query_sync", return_value=ok_res), \ + patch.object(tools, "annotate_current_span") as annotate: + out = tools.execute_trino_query.invoke({"sql": "SELECT a FROM t", "limit": 1}) + annotate.assert_called_once_with({"trino_query_id": "q-9", "execution_time_ms": 34, "row_count": 1, "truncated": True}) + assert '"execution_time_ms":34' in out and '"query_id":"q-9"' in out + + err = TrinoExecutionResult(success=False, error_message="line 1:8: Column 'x' cannot be resolved", + error_name="COLUMN_NOT_FOUND", query_id="q-10", execution_time_ms=5) + with patch.object(tools, "execute_query_sync", return_value=err), \ + patch.object(tools, "annotate_current_span") as annotate: + tools.execute_trino_query.invoke({"sql": "SELECT x FROM t"}) + metadata, = annotate.call_args.args + assert metadata["error_name"] == "COLUMN_NOT_FOUND" and metadata["trino_query_id"] == "q-10" + assert annotate.call_args.kwargs["level"] == "ERROR" + + +def test_annotate_is_a_noop_without_active_span(): + observability.annotate_current_span({"x": 1}) # must not raise outside a trace + + +def test_run_metrics(): + messages = [ + HumanMessage("q"), + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {}, "id": "1"}, + {"name": "get_sample_rows", "args": {}, "id": "2"}]), + ToolMessage('{"ok":false,"data":null,"error":{}}', tool_call_id="1", name="execute_trino_query"), + ToolMessage('{"ok":true}', tool_call_id="2", name="get_sample_rows"), + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {}, "id": "3"}]), + ToolMessage('{"ok":true,"data":{},"error":null}', tool_call_id="3", name="execute_trino_query"), + AIMessage("answer\n```sql\nSELECT 1\n```"), + ] + assert run_metrics(messages, 12.345) == RunMetrics(model_calls=3, tool_calls=3, sql_executions=2, latency_s=12.35) + + +def test_score_run_posts_one_score_per_metric(): + fake_client = SimpleNamespace(create_score=MagicMock()) + with patch("agent.langfuse_client.langfuse_client", fake_client): + observability.score_run("trace-1", RunMetrics(4, 3, 1, 9.5)) + names = {c.kwargs["name"]: c.kwargs for c in fake_client.create_score.call_args_list} + assert set(names) == {f"deep-agent.{n}" for n in ("model_calls", "tool_calls", "sql_executions", "latency_s")} + assert all(kw["data_type"] == "NUMERIC" for kw in names.values()) + assert all(kw["trace_id"] == "trace-1" for kw in names.values()) + + +def test_score_run_without_trace_is_noop(): + with patch("agent.langfuse_client.langfuse_client") as client: + observability.score_run(None, RunMetrics(1, 1, 1, 1.0)) + client.create_score.assert_not_called() + + +@pytest.mark.asyncio +async def test_real_langfuse_handler_produces_a_single_trace(policy_model): + """End-to-end through the real Langfuse v4 CallbackHandler, exported to memory (no network).""" + from langfuse import Langfuse + from langfuse.langchain import CallbackHandler + from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter + + exporter = InMemorySpanExporter() + langfuse = Langfuse(public_key="pk-lf-unit-test", secret_key="sk-lf-unit-test", host="http://127.0.0.1:9", + span_exporter=exporter, flush_at=1, flush_interval=0.01) + + async def fake_enrich(**kwargs): + return kwargs["initial_sql"], None, False + + trino = TrinoExecutionResult(success=True, rows=[[1]], columns=["c"], row_count=1, query_id="q-77", + execution_time_ms=9) + agent = create_deep_agent(model=policy_model(_policy)) + with patch.object(observability, "_langfuse_handler", return_value=CallbackHandler(public_key="pk-lf-unit-test")), \ + patch.object(tools, "get_jeen_metadata_client", return_value=MagicMock(get_catalog_prompt=AsyncMock(return_value="# c"))), \ + patch.object(tools, "execute_query_sync", return_value=trino), \ + patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=({"t": {}}, ["t"])), \ + patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", side_effect=fake_enrich): + config = build_run_config("thread-lf", user_id="user-lf", tracing=True) + await agent.ainvoke({"messages": [("user", "q")]}, config) + langfuse.flush() + + spans = exporter.get_finished_spans() + assert spans + assert len({s.context.trace_id for s in spans}) == 1 + assert [s.name for s in spans if s.parent is None] == ["deep-agent"] + attrs = {k: v for s in spans for k, v in s.attributes.items()} + assert attrs["session.id"] == "thread-lf" + assert attrs["user.id"] == "user-lf" + assert "deep-agent" in attrs["langfuse.trace.tags"] + + trino_span = next(s for s in spans if s.name == "execute_trino_query") + meta = {k.removeprefix("langfuse.observation.metadata."): v for k, v in trino_span.attributes.items()} + assert meta["trino_query_id"] == "q-77" + assert meta["execution_time_ms"] == 9 + assert meta["row_count"] == 1 + assert observability.langfuse_trace_id(config) == format(spans[0].context.trace_id, "032x") diff --git a/agent/tests/deep_agent/test_trino_errors.py b/agent/tests/deep_agent/test_trino_errors.py index 8497752..e813687 100644 --- a/agent/tests/deep_agent/test_trino_errors.py +++ b/agent/tests/deep_agent/test_trino_errors.py @@ -70,6 +70,7 @@ def test_execute_tool_returns_trinos_error(): "type": "USER_ERROR", "location": {"line": 1, "column": 8}, "query_id": "q1", + "execution_time_ms": 0, }, } From cf7dd2015ecc0229d2ac1c2e1bc44209d2907ee5 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 26 Oct 2026 17:32:53 +0200 Subject: [PATCH 14/37] feat(deep-agent): structured final answer bound to the executed SQL (#41) Based on deep-agent/41-structured-answer (f2c3e80), revised in review: - DeepAgentAnswer (sql, explanation_he, assumptions, confidence) via ToolStrategy structured output (forced tool choice) - execute_trino_query records successful runs in state (executed_queries, append-only, with the row cap each ran under) - AnswerVerificationMiddleware binds the answer to evidence: matched / re_executed / rejected / re_execution_failed; final_result.executed means the final SQL ran and rows are Trino's (not a correctness check) - a "matched" execution that was only a smaller sample than the row ceiling is re-executed so users get the full result; re-execution honours an unset ceiling - clarifications behind DEEP_AGENT_CLARIFICATIONS_ENABLED (default off): no needs_clarification field, sql required, not mentioned in prompt/AGENTS.md - render_markdown builds the user table from real rows; run score final_sql_executed Co-Authored-By: Claude Opus 5.5 --- agent/src/agent/config.py | 1 + agent/src/deep_agent/agent.py | 31 ++- agent/src/deep_agent/answer.py | 200 +++++++++++++++++++ agent/src/deep_agent/cli.py | 53 ++--- agent/src/deep_agent/context.py | 5 +- agent/src/deep_agent/memory/AGENTS.md | 11 +- agent/src/deep_agent/observability.py | 8 +- agent/src/deep_agent/tools.py | 26 ++- agent/tests/deep_agent/test_answer.py | 177 ++++++++++++++++ agent/tests/deep_agent/test_cli.py | 50 +---- agent/tests/deep_agent/test_observability.py | 10 +- 11 files changed, 465 insertions(+), 107 deletions(-) create mode 100644 agent/src/deep_agent/answer.py create mode 100644 agent/tests/deep_agent/test_answer.py diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 398604d..1a69a0e 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -52,6 +52,7 @@ class AgentSettings(BaseSettings): DEEP_AGENT_MAX_ROWS: int | None = Field(default=100, gt=0) # execute_trino_query / get_column_distinct_values DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows DEEP_AGENT_TRACING_ENABLED: bool = True # Langfuse callbacks, span metadata and run scores + DEEP_AGENT_CLARIFICATIONS_ENABLED: bool = False # let the model ask a clarifying question instead of answering # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index b31ae13..2f1dc5e 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -3,10 +3,13 @@ """ from deepagents import create_deep_agent as create_harness_agent +from langchain.agents.structured_output import ToolStrategy from langchain_core.language_models import BaseChatModel from langgraph.checkpoint.memory import MemorySaver from agent.llm import get_llm +from agent.config import settings +from deep_agent.answer import AnswerVerificationMiddleware, answer_schema from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware from deep_agent.resources import build_resources from deep_agent.tools import DEEP_AGENT_TOOLS @@ -177,16 +180,24 @@ --- -## Final Response Format (Hebrew) +## Final Answer -Your response MUST be in Hebrew and include: -1. A brief explanation of what the SQL does -2. A markdown table of the actual query results -3. The exact successful SQL in a ```sql``` block at the very bottom +Finish by calling `DeepAgentAnswer` exactly once: +- `sql` — the exact final SQL you executed successfully with `execute_trino_query` (it is checked against your executions) +- `explanation_he` — a brief Hebrew explanation of what the SQL does and what the result means +- `assumptions` — interpretation choices you made (Hebrew) +- `confidence` — high / medium / low + +Do NOT type result tables — the rows shown to the user are taken directly from the executed query. +""" + +# Appended to the system prompt only when DEEP_AGENT_CLARIFICATIONS_ENABLED is on. +CLARIFICATION_PROMPT = """ +If the question is genuinely ambiguous, set `needs_clarification` (a short Hebrew question to the user) instead of `sql`. """ -def create_deep_agent(model: BaseChatModel | None = None): +def create_deep_agent(model: BaseChatModel | None = None, clarifications_enabled: bool | None = None): """ Creates and returns a compiled LangGraph deep agent equipped with all exploration, enrichment, temporal, geospatial, and semantic validation tools. @@ -196,7 +207,10 @@ def create_deep_agent(model: BaseChatModel | None = None): Args: model: Chat model override (tests); defaults to the configured LLM. + clarifications_enabled: Override DEEP_AGENT_CLARIFICATIONS_ENABLED (tests). """ + if clarifications_enabled is None: + clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED llm = model or get_llm() memory = MemorySaver() resources = build_resources() @@ -204,8 +218,9 @@ def create_deep_agent(model: BaseChatModel | None = None): agent = create_harness_agent( model=llm, tools=DEEP_AGENT_TOOLS, - system_prompt=SYSTEM_PROMPT, - middleware=[DeepAgentContextMiddleware()], + system_prompt=SYSTEM_PROMPT + CLARIFICATION_PROMPT if clarifications_enabled else SYSTEM_PROMPT, + middleware=[DeepAgentContextMiddleware(), AnswerVerificationMiddleware()], + response_format=ToolStrategy(answer_schema(clarifications_enabled)), context_schema=DeepAgentContext, checkpointer=memory, backend=resources.backend, diff --git a/agent/src/deep_agent/answer.py b/agent/src/deep_agent/answer.py new file mode 100644 index 0000000..7fc3d26 --- /dev/null +++ b/agent/src/deep_agent/answer.py @@ -0,0 +1,200 @@ +""" +Structured final answer for the Deep Agent, bound to SQL that actually ran. + +The model finishes by submitting a DeepAgentAnswer (ToolStrategy structured output). +AnswerVerificationMiddleware then binds it to evidence. `final_result.executed` says whether +the final SQL ran and the rows shown are Trino's — it does NOT mean the answer was checked +to be semantically correct. + +- "matched": answer.sql equals (sqlglot-normalised) a query that executed successfully in + this run -> the result rows are that execution's rows +- "re_executed": no match, or the match was only a smaller sample than the configured row + ceiling -> answer.sql is run once through the read-only guard; rows come from that run +- "rejected" / "re_execution_failed": the answer's SQL is forbidden or fails -> not executed +- "clarification": the model asked a clarifying question instead of answering + (only possible when DEEP_AGENT_CLARIFICATIONS_ENABLED is on) + +The result table shown to users is always built from Trino rows, never from model text. +""" + +import asyncio +import logging +from typing import Any, Literal + +import sqlglot +from langchain.agents.middleware import AgentMiddleware +from pydantic import BaseModel, Field, create_model +from sqlglot.errors import SqlglotError + +from agent.config import settings +from agent.utils import sql_guard +from agent.utils.sql import clean_sql +from core.trino import execute_query_sync + +logger = logging.getLogger(__name__) + +VerificationStatus = Literal["matched", "re_executed", "rejected", "re_execution_failed", "clarification", "no_answer"] + + +class DeepAgentAnswer(BaseModel): + """Submit the final answer. Call this exactly once, when you are done.""" + + sql: str = Field( + description="The exact final Trino SQL whose results answer the question — the same query you executed " + "successfully with execute_trino_query.", + ) + explanation_he: str = Field(description="Brief Hebrew explanation of what the SQL does and what the result means.") + assumptions: list[str] = Field( + default_factory=list, description="Interpretation choices you made (in Hebrew), e.g. which column means 'city'." + ) + confidence: Literal["high", "medium", "low"] = Field(description="Confidence that the SQL answers the question.") + + +# Same tool name ("DeepAgentAnswer"), plus the option to ask a clarifying question instead of answering. +DeepAgentAnswerWithClarification = create_model( + "DeepAgentAnswer", + __base__=DeepAgentAnswer, + __doc__=DeepAgentAnswer.__doc__, + sql=(str | None, Field( + default=None, + description="The exact final Trino SQL whose results answer the question — the same query you executed " + "successfully with execute_trino_query. Null only when asking for clarification.", + )), + needs_clarification=(str | None, Field( + default=None, description="If the question is ambiguous, the clarifying question to ask the user (Hebrew).", + )), +) + + +def answer_schema(clarifications_enabled: bool | None = None) -> type[DeepAgentAnswer]: + """The final-answer schema; without clarifications the model must always commit to a SQL answer.""" + enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED if clarifications_enabled is None else clarifications_enabled + return DeepAgentAnswerWithClarification if enabled else DeepAgentAnswer + + +def normalize_sql(sql: str | None) -> str | None: + """Canonical form for comparing two SQL strings (whitespace, keyword case, trailing ';', fences).""" + if not sql: + return None + cleaned = clean_sql(sql) + try: + return sqlglot.parse_one(cleaned, read="trino").sql(dialect="trino") + except SqlglotError: + return " ".join(cleaned.split()) + + +def executed_query_record( + submitted_sql: str, executed_sql: str, payload: dict[str, Any], row_cap: int | None +) -> dict[str, Any]: + """State entry for one successful execution (see DeepAgentRuntimeState.executed_queries). + + row_cap is the ceiling that execution ran under (None = none), so verification can tell an + exploration sample (e.g. limit=5) from the full answer. + """ + return { + "submitted_sql": clean_sql(submitted_sql), + "executed_sql": executed_sql, + "columns": payload["columns"], + "rows": payload["rows"], + "row_count": payload["row_count"], + "truncated": payload["truncated"], + "query_id": payload.get("query_id"), + "row_cap": row_cap, + } + + +def _match(answer_sql: str, executed: list[dict[str, Any]]) -> dict[str, Any] | None: + target = normalize_sql(answer_sql) + for record in reversed(executed): # latest execution wins + if target in (normalize_sql(record["submitted_sql"]), normalize_sql(record["executed_sql"])): + return record + return None + + +def _is_sample(record: dict[str, Any]) -> bool: + """The matched execution was cut short by a smaller limit than the configured row ceiling.""" + if not record.get("truncated"): + return False + ceiling = settings.DEEP_AGENT_MAX_ROWS + cap = record.get("row_cap") + return cap is not None and (ceiling is None or cap < ceiling) + + +def _re_execute(answer_sql: str) -> tuple[VerificationStatus, dict[str, Any] | None, str | None]: + row_cap = settings.DEEP_AGENT_MAX_ROWS + try: + guarded = sql_guard.prepare(clean_sql(answer_sql), row_cap) + except sql_guard.GuardError as e: + return "rejected", None, str(e) + res = execute_query_sync(guarded.sql) + if not res.success: + return "re_execution_failed", None, res.error_message + rows = res.rows or [] + truncated = row_cap is not None and len(rows) > row_cap + if truncated: + rows = rows[:row_cap] + payload = {"columns": res.columns, "rows": rows, "row_count": len(rows), "truncated": truncated, + "query_id": res.query_id} + return "re_executed", executed_query_record(answer_sql, guarded.sql, payload, row_cap), None + + +def _result_view(record: dict[str, Any]) -> dict[str, Any]: + return {k: record[k] for k in ("columns", "rows", "row_count", "truncated", "query_id")} + + +def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any]: + """Build `final_result` from the structured answer and the run's successful executions.""" + if not isinstance(answer, DeepAgentAnswer): + return {"status": "no_answer", "executed": False, "answer": None, "sql": None, "result": None, "error": None} + + base = {"answer": answer.model_dump(), "error": None} + if getattr(answer, "needs_clarification", None) or not answer.sql: + return {**base, "status": "clarification", "executed": False, "sql": None, "result": None} + + record = _match(answer.sql, executed) + if record is not None and not _is_sample(record): + return {**base, "status": "matched", "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} + + status, record, error = _re_execute(answer.sql) + if record is None: + return {**base, "status": status, "executed": False, "sql": clean_sql(answer.sql), "result": None, "error": error} + return {**base, "status": status, "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} + + +class AnswerVerificationMiddleware(AgentMiddleware): + """After the agent finishes, bind the structured answer to executed SQL and real rows.""" + + def after_agent(self, state, runtime) -> dict[str, Any] | None: + return {"final_result": verify_answer(state.get("structured_response"), state.get("executed_queries") or [])} + + async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: + return await asyncio.to_thread(self.after_agent, state, runtime) + + +def _cell(value: Any) -> str: + return "" if value is None else str(value).replace("|", "\\|").replace("\n", " ") + + +def render_markdown(final_result: dict[str, Any]) -> str: + """User-facing Hebrew answer: explanation, table from real rows, SQL block.""" + answer = final_result.get("answer") or {} + if final_result.get("status") == "clarification": + return answer.get("needs_clarification") or answer.get("explanation_he", "") + parts = [answer.get("explanation_he", "")] + if answer.get("assumptions"): + parts.append("**הנחות:**\n" + "\n".join(f"- {a}" for a in answer["assumptions"])) + + result = final_result.get("result") + if result: + header = "| " + " | ".join(_cell(c) for c in result["columns"]) + " |" + sep = "|" + "---|" * len(result["columns"]) + body = ["| " + " | ".join(_cell(v) for v in row) + " |" for row in result["rows"]] + parts.append("\n".join([header, sep, *body])) + if result.get("truncated"): + parts.append(f"_מוצגות {result['row_count']} השורות הראשונות בלבד._") + elif final_result.get("error"): + parts.append(f"⚠️ לא ניתן היה להריץ את השאילתה הסופית: {final_result['error']}") + + if final_result.get("sql"): + parts.append(f"```sql\n{final_result['sql']}\n```") + return "\n\n".join(p for p in parts if p) diff --git a/agent/src/deep_agent/cli.py b/agent/src/deep_agent/cli.py index 1e52328..83855e5 100644 --- a/agent/src/deep_agent/cli.py +++ b/agent/src/deep_agent/cli.py @@ -10,7 +10,6 @@ import argparse import asyncio import json -import re import time import uuid from dataclasses import asdict, dataclass @@ -22,6 +21,7 @@ from agent.config import settings from deep_agent.agent import create_deep_agent from deep_agent import observability +from deep_agent.answer import render_markdown from deep_agent.context import DeepAgentContext # ANSI Colors for terminal output @@ -36,10 +36,6 @@ DIM = "\033[2m" RESET = "\033[0m" -_SQL_BLOCK = re.compile(r"```(?:sql)?\n(.*?)\n?```", re.DOTALL | re.IGNORECASE) -_THOUGHT_BLOCK = re.compile(r".*?", re.DOTALL) - - @dataclass class RunRecord: """One CLI run, written as a single JSONL line when --log-file is set.""" @@ -50,6 +46,8 @@ class RunRecord: question: str final_sql: str | None final_answer: str + verification: str + executed: bool def _message_text(msg: BaseMessage) -> str: @@ -57,28 +55,6 @@ def _message_text(msg: BaseMessage) -> str: return msg.text if isinstance(msg, BaseMessage) else str(getattr(msg, "content", "")) -def extract_final_sql_and_answer(messages: list[BaseMessage]) -> tuple[str | None, str]: - """Return (last SQL block, answer text without SQL/thought blocks) from a finished run.""" - if not messages: - return None, "" - - final_answer = _message_text(messages[-1]) - sql_blocks = _SQL_BLOCK.findall(final_answer) - final_sql = sql_blocks[-1].strip() if sql_blocks else None - - # Fallback: if missing from final answer, search backward through history - if not final_sql: - for msg in reversed(messages): - fallback_blocks = _SQL_BLOCK.findall(_message_text(msg)) - if fallback_blocks: - final_sql = fallback_blocks[-1].strip() - break - - clean_answer = _THOUGHT_BLOCK.sub("", final_answer) - clean_answer = _SQL_BLOCK.sub("", clean_answer).strip() - return final_sql, clean_answer - - def append_run_record(log_file: Path, record: RunRecord) -> None: log_file.parent.mkdir(parents=True, exist_ok=True) with log_file.open("a", encoding="utf-8") as f: @@ -175,9 +151,13 @@ async def run_query( if not final_state or not final_state.get("messages"): return - final_sql, clean_answer = extract_final_sql_and_answer(final_state["messages"]) + final_result = final_state.get("final_result") or {"status": "no_answer", "executed": False} + final_sql = final_result.get("sql") + rendered = render_markdown(final_result) trace_id = observability.langfuse_trace_id(config) - observability.score_run(trace_id, observability.run_metrics(final_state["messages"], execution_time)) + observability.score_run( + trace_id, observability.run_metrics(final_state["messages"], execution_time, final_result) + ) if log_file is not None: append_run_record( @@ -188,20 +168,21 @@ async def run_query( thread_id=thread_id, question=question, final_sql=final_sql, - final_answer=clean_answer, + final_answer=rendered, + verification=final_result.get("status", "no_answer"), + executed=bool(final_result.get("executed")), ), ) + print(f"\n{GREEN}{BOLD}{'='*30} FINAL ANSWER {'='*30}{RESET}\n") + print(f"{WHITE}{rendered}{RESET}\n") + status_color = GREEN if final_result.get("executed") else YELLOW print( - f"\n{GREEN}{BOLD}[Run finished] Execution time: {execution_time}s, " - f"Final SQL captured: {'Yes' if final_sql else 'None'}{RESET}" + f"{status_color}{BOLD}[Run finished] Execution time: {execution_time}s, " + f"verification: {final_result.get('status')}{RESET}" ) if trace_id: print(f"{DIM} Langfuse trace: {trace_id}{RESET}") - if final_sql: - print(f"\n{CYAN}{BOLD}{'='*30} FINAL GENERATED SQL {'='*30}{RESET}") - print(f"{GREEN}{final_sql}{RESET}") - print(f"{CYAN}{BOLD}{'='*81}{RESET}\n") def build_parser() -> argparse.ArgumentParser: diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index c525cc2..870178b 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -11,10 +11,11 @@ context's timezone, so long-running processes never serve a stale date. """ +import operator from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import datetime -from typing import Any, NotRequired +from typing import Annotated, Any, NotRequired from zoneinfo import ZoneInfo from langchain.agents.middleware import AgentMiddleware, AgentState, ModelRequest, ModelResponse @@ -34,6 +35,8 @@ class DeepAgentContext: class DeepAgentRuntimeState(AgentState): connection_capabilities: NotRequired[dict[str, bool]] jeen_catalog: NotRequired[str] # raw catalog text, cached so tools never need the model to re-send it + executed_queries: NotRequired[Annotated[list[dict[str, Any]], operator.add]] # successful executions (append-only) + final_result: NotRequired[dict[str, Any]] # verified answer + rows (see deep_agent.answer) def connection_id(runtime: ToolRuntime | None) -> int | None: diff --git a/agent/src/deep_agent/memory/AGENTS.md b/agent/src/deep_agent/memory/AGENTS.md index 1e54717..abceff5 100644 --- a/agent/src/deep_agent/memory/AGENTS.md +++ b/agent/src/deep_agent/memory/AGENTS.md @@ -5,13 +5,12 @@ You are an elite, highly autonomous Deep SQL Analyst. You plan your own approach --- -## Output Format (Hebrew) -Your final response MUST be in Hebrew and include: -1. A brief explanation of what the SQL does -2. A markdown table of the actual query results -3. The exact, final, successful Trino SQL in a ` ```sql ``` ` block at the very bottom +## Output Format +Finish by calling `DeepAgentAnswer` once: the exact SQL you executed successfully, a brief Hebrew explanation, +your assumptions and your confidence. +Never type result tables — the user sees the rows of the executed query. -When you have the answer — stop calling tools. Respond. +When you have the answer — stop calling tools and submit it. --- diff --git a/agent/src/deep_agent/observability.py b/agent/src/deep_agent/observability.py index 601263a..89a38d6 100644 --- a/agent/src/deep_agent/observability.py +++ b/agent/src/deep_agent/observability.py @@ -100,22 +100,24 @@ def annotate_current_span(metadata: dict[str, Any], level: str | None = None) -> @dataclass(frozen=True) class RunMetrics: - """Plain counts and timing for one run. Whether the *final* SQL ran is not known here: - the run ends in free text, with no structured final answer to check.""" + """Plain counts and timing for one run, plus whether the submitted final SQL actually ran + (from the structured-answer verification in deep_agent.answer).""" model_calls: int tool_calls: int sql_executions: int latency_s: float + final_sql_executed: bool = False # the submitted final SQL ran and its rows are Trino's (not a correctness check) -def run_metrics(messages: list[BaseMessage], latency_s: float) -> RunMetrics: +def run_metrics(messages: list[BaseMessage], latency_s: float, final_result: dict | None = None) -> RunMetrics: ai = [m for m in messages if m.type == "ai"] return RunMetrics( model_calls=len(ai), tool_calls=sum(len(getattr(m, "tool_calls", None) or []) for m in ai), sql_executions=sum(1 for m in messages if m.type == "tool" and m.name == "execute_trino_query"), latency_s=round(latency_s, 2), + final_sql_executed=bool(final_result and final_result.get("executed")), ) diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 43b57b6..14afbfe 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -22,6 +22,7 @@ from agent.utils.sql_guard import effective_cap from core.trino import execute_query_sync from deep_agent import trino_errors +from deep_agent.answer import executed_query_record from deep_agent.context import DeepAgentContext, cached_catalog, capability, connection_id, user_request from deep_agent.envelope import ( ENRICHMENT_ERROR, @@ -200,8 +201,13 @@ async def get_column_profile(table_name: str, column_name: str, runtime: Runtime # --------------------------------------------------------------------------- def _run_sql(sql: str, row_cap: int | None) -> str: + return _execute(sql, row_cap)[0] + + +def _execute(sql: str, row_cap: int | None) -> tuple[str, dict | None]: """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation. + Returns (envelope, success payload or None). row_cap=None means no ceiling: every returned row is passed through. Telemetry (query id, timing, row count / Trino error) goes both into the envelope and onto the current Langfuse tool observation. @@ -211,7 +217,7 @@ def _run_sql(sql: str, row_cap: int | None) -> str: except Exception as e: err = trino_errors.from_exception(e) annotate_current_span({"error_name": err["name"]}, level="ERROR") - return fail(err) + return fail(err), None if not res.success: err = trino_errors.from_result(res) err["execution_time_ms"] = res.execution_time_ms @@ -221,7 +227,7 @@ def _run_sql(sql: str, row_cap: int | None) -> str: "error_name": err["name"], "error_type": err.get("type"), }, level="ERROR") - return fail(err) + return fail(err), None rows = res.rows or [] truncated = row_cap is not None and len(rows) > row_cap @@ -233,18 +239,19 @@ def _run_sql(sql: str, row_cap: int | None) -> str: "row_count": len(rows), "truncated": truncated, }) - return ok({ + payload = { "columns": res.columns, "row_count": len(rows), "truncated": truncated, "rows": rows, "query_id": res.query_id, "execution_time_ms": res.execution_time_ms, - }) + } + return ok(payload), payload @tool -def execute_trino_query(sql: str, limit: int | None = None) -> str: +def execute_trino_query(sql: str, limit: int | None = None, runtime: Runtime = None) -> str | Command: """ Executes a read-only Trino SQL query and returns the resulting rows. @@ -276,7 +283,14 @@ def execute_trino_query(sql: str, limit: int | None = None) -> str: guarded = sql_guard.prepare(clean_sql(sql), row_cap) except sql_guard.GuardError as e: return fail(trino_errors.forbidden(str(e))) - return _run_sql(guarded.sql, guarded.row_cap if guarded.is_query else settings.DEEP_AGENT_MAX_ROWS) + content, payload = _execute(guarded.sql, guarded.row_cap if guarded.is_query else settings.DEEP_AGENT_MAX_ROWS) + if payload is None or not guarded.is_query or runtime is None or not runtime.tool_call_id: + return content + # Record the successful execution so the final answer can be bound to it (deep_agent.answer). + return Command(update={ + "executed_queries": [executed_query_record(sql, guarded.sql, payload, row_cap)], + "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="execute_trino_query")], + }) @tool diff --git a/agent/tests/deep_agent/test_answer.py b/agent/tests/deep_agent/test_answer.py new file mode 100644 index 0000000..f43563b --- /dev/null +++ b/agent/tests/deep_agent/test_answer.py @@ -0,0 +1,177 @@ +from unittest.mock import patch + +import pytest +from langchain_core.messages import AIMessage + +from core.trino import TrinoExecutionResult +from deep_agent import answer as answer_module +from deep_agent import tools +from deep_agent.agent import create_deep_agent +from deep_agent.answer import DeepAgentAnswer, answer_schema, normalize_sql, render_markdown, verify_answer +from tests.deep_agent.conftest import system_text + +EXECUTED = "SELECT COUNT(DISTINCT flight_id) AS flights FROM \"postgres\".\"public\".\"flights_table\" WHERE launch_country = 'France'" +# Same query as the model might restate it: different whitespace/case and a trailing semicolon. +RESTATED = "select count(distinct flight_id) as flights\nfrom \"postgres\".\"public\".\"flights_table\"\nwhere launch_country = 'France';" + + +def _trino(rows): + return TrinoExecutionResult(success=True, rows=rows, columns=["flights"], row_count=len(rows), query_id="q-1") + + +def _policy(final_args, content=""): + def policy(messages): + tool_msgs = [m for m in messages if m.type == "tool"] + if not tool_msgs: + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED}, "id": "e1"}]) + return AIMessage(content, tool_calls=[{"name": "DeepAgentAnswer", "args": final_args, "id": "final"}]) + return policy + + +ANSWER = {"sql": RESTATED, "explanation_he": "סופרת טיסות ייחודיות שהמריאו מצרפת", "assumptions": ["טיסה = flight_id"], + "confidence": "high"} + + +async def _run(policy_model, policy, tool_results, reexecution_results=(), clarifications=False): + agent = create_deep_agent(model=policy_model(policy), clarifications_enabled=clarifications) + with patch.object(tools, "execute_query_sync", side_effect=list(tool_results)) as t1, \ + patch.object(answer_module, "execute_query_sync", side_effect=list(reexecution_results)) as t2: + result = await agent.ainvoke({"messages": [("user", "כמה טיסות המריאו מצרפת")]}, + {"configurable": {"thread_id": "a"}}) + return result, t1, t2 + + +@pytest.mark.asyncio +async def test_answer_is_bound_to_the_executed_query(policy_model): + result, _, reexec = await _run(policy_model, _policy(ANSWER), [_trino([[466]])]) + + final = result["final_result"] + assert final["status"] == "matched" and final["executed"] is True + assert final["sql"] == EXECUTED # the executed text, no trailing ';' + assert final["result"]["rows"] == [[466]] # rows from Trino, not model text + assert final["answer"]["confidence"] == "high" + reexec.assert_not_called() + assert len(result["executed_queries"]) == 1 + + +@pytest.mark.asyncio +async def test_unexecuted_answer_sql_is_re_executed(policy_model): + other = {**ANSWER, "sql": "SELECT COUNT(*) AS flights FROM \"postgres\".\"public\".\"flights_table\""} + result, _, reexec = await _run(policy_model, _policy(other), [_trino([[466]])], [_trino([[1000]])]) + + final = result["final_result"] + assert final["status"] == "re_executed" and final["executed"] is True + assert final["result"]["rows"] == [[1000]] + reexec.assert_called_once() + assert reexec.call_args.args[0].endswith("LIMIT 101") # re-execution goes through the guard + + +@pytest.mark.asyncio +async def test_forbidden_answer_sql_is_rejected(policy_model): + bad = {**ANSWER, "sql": "DELETE FROM \"postgres\".\"public\".\"flights_table\""} + result, _, reexec = await _run(policy_model, _policy(bad), [_trino([[466]])]) + + final = result["final_result"] + assert final["status"] == "rejected" and final["executed"] is False + assert final["result"] is None + reexec.assert_not_called() + + +@pytest.mark.asyncio +async def test_clarification_path_when_enabled(policy_model): + ask = {"sql": None, "explanation_he": "", "confidence": "low", "needs_clarification": "האם הכוונה לנחיתות או להמראות?"} + result, _, _ = await _run(policy_model, _policy(ask), [_trino([[466]])], clarifications=True) + + final = result["final_result"] + assert final["status"] == "clarification" + assert render_markdown(final) == "האם הכוונה לנחיתות או להמראות?" + + +@pytest.mark.asyncio +async def test_list_content_from_reasoning_models_is_fine(policy_model): + reasoning = [{"type": "reasoning", "reasoning": "thinking..."}, {"type": "text", "text": "submitting"}] + result, _, _ = await _run(policy_model, _policy(ANSWER, content=reasoning), [_trino([[466]])]) + assert result["final_result"]["status"] == "matched" + + +def test_render_markdown_builds_table_from_rows(): + final = { + "status": "matched", "executed": True, "sql": "SELECT a, b FROM t", + "answer": {"explanation_he": "הסבר", "assumptions": ["הנחה"], "confidence": "high"}, + "result": {"columns": ["a", "b"], "rows": [["x|y", None], [1, "line\nbreak"]], "row_count": 2, + "truncated": True, "query_id": "q"}, + } + md = render_markdown(final) + assert "| a | b |" in md + assert "| x\\|y | |" in md and "| 1 | line break |" in md + assert "**הנחות:**\n- הנחה" in md + assert "השורות הראשונות" in md + assert md.endswith("```sql\nSELECT a, b FROM t\n```") + + +def test_render_reports_failed_final_sql(): + final = {"status": "re_execution_failed", "executed": False, "sql": "SELECT x FROM t", "result": None, + "error": "Column 'x' cannot be resolved", "answer": {"explanation_he": "הסבר"}} + assert "לא ניתן היה להריץ" in render_markdown(final) + + +def test_normalize_sql_equivalence(): + assert normalize_sql(EXECUTED) == normalize_sql(RESTATED) + assert normalize_sql("```sql\nSELECT 1;\n```") == normalize_sql("select 1") + assert normalize_sql("SELECT 1") != normalize_sql("SELECT 2") + + +def test_verify_without_structured_answer(): + assert verify_answer(None, [])["status"] == "no_answer" + + +def test_answer_schema_requires_explanation_and_confidence(): + with pytest.raises(ValueError): + DeepAgentAnswer(sql="SELECT 1") + + +def test_clarifications_are_off_by_default(): + schema = answer_schema() + assert schema.__name__ == "DeepAgentAnswer" + assert "needs_clarification" not in schema.model_fields + assert schema.model_fields["sql"].is_required() # the model must always commit to a SQL answer + enabled = answer_schema(True) + assert enabled.__name__ == "DeepAgentAnswer" # same tool name either way + assert "needs_clarification" in enabled.model_fields and not enabled.model_fields["sql"].is_required() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("enabled", [False, True]) +async def test_clarification_only_mentioned_in_prompt_when_enabled(scripted_model, enabled): + model = scripted_model(AIMessage("", tool_calls=[{"name": "DeepAgentAnswer", "args": {**ANSWER}, "id": "f"}])) + agent = create_deep_agent(model=model, clarifications_enabled=enabled) + with patch.object(answer_module, "execute_query_sync", return_value=_trino([[1]])): + await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": f"c{enabled}"}}) + assert ("needs_clarification" in system_text(model.seen[0])) is enabled + + +@pytest.mark.asyncio +async def test_matched_exploration_sample_is_re_executed_for_the_full_answer(policy_model): + """The model explored with limit=5 and submitted that same SQL: the user must get the full result, not the sample.""" + def policy(messages): + if not [m for m in messages if m.type == "tool"]: + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED, "limit": 5}, "id": "e1"}]) + return AIMessage("", tool_calls=[{"name": "DeepAgentAnswer", "args": ANSWER, "id": "final"}]) + + sample = _trino([[i] for i in range(6)]) # 5 + 1 rows -> truncated sample + full = _trino([[i] for i in range(40)]) + result, _, reexec = await _run(policy_model, policy, [sample], [full]) + + final = result["final_result"] + assert final["status"] == "re_executed" and final["executed"] is True + assert final["result"]["row_count"] == 40 and final["result"]["truncated"] is False + assert reexec.call_args.args[0].endswith("LIMIT 101") + + +def test_re_execution_without_a_row_ceiling(monkeypatch): + monkeypatch.setattr(answer_module.settings, "DEEP_AGENT_MAX_ROWS", None) + answer = DeepAgentAnswer(sql="SELECT a FROM t", explanation_he="הסבר", confidence="high") + with patch.object(answer_module, "execute_query_sync", return_value=_trino([[i] for i in range(500)])) as run: + final = verify_answer(answer, []) + assert run.call_args.args[0] == "SELECT a FROM t" # no LIMIT added + assert final["executed"] is True and final["result"]["row_count"] == 500 and final["result"]["truncated"] is False diff --git a/agent/tests/deep_agent/test_cli.py b/agent/tests/deep_agent/test_cli.py index 77f9ab4..1dfb4f5 100644 --- a/agent/tests/deep_agent/test_cli.py +++ b/agent/tests/deep_agent/test_cli.py @@ -1,59 +1,21 @@ import json -from langchain_core.messages import AIMessage, HumanMessage, ToolMessage +from langchain_core.messages import AIMessage, ToolMessage -from deep_agent.cli import RunRecord, append_run_record, extract_final_sql_and_answer, print_formatted_message - - -def test_extracts_last_sql_block_and_strips_it_from_answer(): - answer = "הסבר קצר\n```sql\nSELECT 1\n```\nעוד טקסט\n```sql\nSELECT 2\n```" - sql, text = extract_final_sql_and_answer([HumanMessage("q"), AIMessage(answer)]) - assert sql == "SELECT 2" - assert "SELECT" not in text - assert "הסבר קצר" in text - - -def test_handles_list_content_blocks_without_crashing(): - final = AIMessage(content=[ - {"type": "reasoning", "reasoning": "thinking..."}, - {"type": "text", "text": "תשובה\n```sql\nSELECT COUNT(*) FROM t\n```"}, - ]) - sql, text = extract_final_sql_and_answer([HumanMessage("q"), final]) - assert sql == "SELECT COUNT(*) FROM t" - assert text == "תשובה" - - -def test_falls_back_to_history_when_final_answer_has_no_sql(): - history = [ - HumanMessage("q"), - AIMessage("draft\n```sql\nSELECT 3\n```"), - ToolMessage("ok", tool_call_id="1"), - AIMessage("final answer, no sql"), - ] - sql, text = extract_final_sql_and_answer(history) - assert sql == "SELECT 3" - assert text == "final answer, no sql" - - -def test_strips_thought_blocks(): - sql, text = extract_final_sql_and_answer([AIMessage("hiddenvisible")]) - assert sql is None - assert text == "visible" - - -def test_empty_history(): - assert extract_final_sql_and_answer([]) == (None, "") +from deep_agent.cli import RunRecord, append_run_record, print_formatted_message def test_run_record_is_valid_jsonl(tmp_path): log = tmp_path / "runs" / "log.jsonl" for i in range(2): - append_run_record(log, RunRecord("2026-10-20T10:00:00", 1.5, f"t{i}", "שאלה\nשורה", "SELECT 1", "תשובה")) + append_run_record(log, RunRecord("2026-10-20T10:00:00", 1.5, f"t{i}", "שאלה\nשורה", "SELECT 1", "תשובה", + "matched", True)) lines = log.read_text(encoding="utf-8").splitlines() assert len(lines) == 2 rows = [json.loads(line) for line in lines] assert rows[0]["question"] == "שאלה\nשורה" - assert set(rows[1]) == {"timestamp", "execution_time_s", "thread_id", "question", "final_sql", "final_answer"} + assert set(rows[1]) == {"timestamp", "execution_time_s", "thread_id", "question", "final_sql", "final_answer", + "verification", "executed"} def test_print_formatted_message_handles_list_content(capsys): diff --git a/agent/tests/deep_agent/test_observability.py b/agent/tests/deep_agent/test_observability.py index 72e87b4..3cf0d7c 100644 --- a/agent/tests/deep_agent/test_observability.py +++ b/agent/tests/deep_agent/test_observability.py @@ -155,15 +155,19 @@ def test_run_metrics(): AIMessage("answer\n```sql\nSELECT 1\n```"), ] assert run_metrics(messages, 12.345) == RunMetrics(model_calls=3, tool_calls=3, sql_executions=2, latency_s=12.35) + assert run_metrics(messages, 1, {"status": "matched", "executed": True}).final_sql_executed is True + assert run_metrics(messages, 1, {"status": "re_execution_failed", "executed": False}).final_sql_executed is False def test_score_run_posts_one_score_per_metric(): fake_client = SimpleNamespace(create_score=MagicMock()) with patch("agent.langfuse_client.langfuse_client", fake_client): - observability.score_run("trace-1", RunMetrics(4, 3, 1, 9.5)) + observability.score_run("trace-1", RunMetrics(4, 3, 1, 9.5, final_sql_executed=True)) names = {c.kwargs["name"]: c.kwargs for c in fake_client.create_score.call_args_list} - assert set(names) == {f"deep-agent.{n}" for n in ("model_calls", "tool_calls", "sql_executions", "latency_s")} - assert all(kw["data_type"] == "NUMERIC" for kw in names.values()) + assert set(names) == {f"deep-agent.{n}" for n in + ("model_calls", "tool_calls", "sql_executions", "latency_s", "final_sql_executed")} + assert names["deep-agent.final_sql_executed"]["data_type"] == "BOOLEAN" + assert names["deep-agent.final_sql_executed"]["value"] == 1.0 assert all(kw["trace_id"] == "trace-1" for kw in names.values()) From b136c93204b192e090591dace03d7316fa28a009 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 26 Oct 2026 17:44:14 +0200 Subject: [PATCH 15/37] perf(deep-agent): cut per-call latency without hard loop caps (#42, revised) Based on deep-agent/42-loop-bounds (6590244), revised in review: - JeenMetadataClient: TTL + single-flight cache for read-only metadata tools (JEEN_METADATA_CACHE_TTL_S); persistent MCP session per event loop (JEEN_METADATA_REUSE_SESSION), closed once when the CLI/benchmark exits - core: opt-in per-thread Trino connection reuse (deep agent opts in) - BuiltinToolFilterMiddleware hides execute/write_file/edit_file/glob/grep - validate_sql optional, with accurate guidance (execute fails just as fast for invalid queries, reading no data) - deep-agent-bench: latency p50/p95, calls, tokens, executed rate - dropped from the PR: model/tool/SQL call caps, run wall-clock timeout, recursion-limit override, LLM timeout/retry override (it never reached the real client) and best-effort answers from the last executed query Co-Authored-By: Claude Opus 5.5 --- agent/benchmarks/deep_agent_questions.json | 42 ++++ agent/pyproject.toml | 1 + agent/src/agent/config.py | 2 + agent/src/agent/utils/jeen_metadata_client.py | 191 ++++++++++++++-- agent/src/deep_agent/agent.py | 7 +- agent/src/deep_agent/answer.py | 2 +- agent/src/deep_agent/benchmark.py | 155 +++++++++++++ agent/src/deep_agent/cli.py | 7 + agent/src/deep_agent/memory/AGENTS.md | 6 +- agent/src/deep_agent/tool_filter.py | 35 +++ agent/src/deep_agent/tools.py | 10 +- agent/tests/deep_agent/conftest.py | 4 + agent/tests/deep_agent/test_latency.py | 212 ++++++++++++++++++ core/src/core/trino.py | 41 +++- 14 files changed, 678 insertions(+), 37 deletions(-) create mode 100644 agent/benchmarks/deep_agent_questions.json create mode 100644 agent/src/deep_agent/benchmark.py create mode 100644 agent/src/deep_agent/tool_filter.py create mode 100644 agent/tests/deep_agent/test_latency.py diff --git a/agent/benchmarks/deep_agent_questions.json b/agent/benchmarks/deep_agent_questions.json new file mode 100644 index 0000000..d4f9852 --- /dev/null +++ b/agent/benchmarks/deep_agent_questions.json @@ -0,0 +1,42 @@ +[ + { + "id": "q01", + "question": "כמה טיסות המריאו מצרפת" + }, + { + "id": "q02", + "question": "what cities are in the Haifa district" + }, + { + "id": "q03", + "question": "חשב את מספר התראות הטיסה לנפש עבור כל מחוז. לאחר מכן, עבור 3 המחוזות עם כמות ההתראות הגבוהה ביותר, ציין את 3 הערים הגדולות ביותר בכל מחוז על בסיס שטח הפנים שלהן." + }, + { + "id": "q04", + "question": "כמה טיסות המריאו מצרפת ונחתו בתל אביב" + }, + { + "id": "q05", + "question": "מצא את אזורי ההנחיה שבהם מדיניות הטיסה אוסרת טיסה בגובה נמוך או סוגרת את המרחב האווירי לחלוטין, ובמקביל מדיניות הנחיתה מחייבת העברה לשדה חלופי. עבור כל אזור הצג את מדיניות הטיסה, את מדיניות הנחיתה ואת מועד העדכון האחרון. מיין מהעדכון החדש ביותר לישן ביותר." + }, + { + "id": "q06", + "question": "השווה בין ערים לפי מספר ההתרעות שהתקבלו בהן במהלך יוני 2026 ביחס לגודל האוכלוסייה שלהן. הצג רק ערים שיש להן לפחות 10 התרעות בתקופה, והצג את חמש הערים עם מספר ההתרעות הגבוה ביותר לכל 10,000 תושבים. הצג גם את מספר ההתרעות ואת גודל האוכלוסייה ששימשו לחישוב." + }, + { + "id": "q07", + "question": "מצא את הערים שבהן נרשמו לפחות 5 התרעות במהלך השבועיים הראשונים של יולי 2026, אך לא נרשמה בהן אף נחיתת חירום באותה תקופה. הצג את מספר ההתרעות בכל עיר, ומיין מהמספר הגבוה לנמוך." + }, + { + "id": "q08", + "question": "עבור טיסות שהמריאו במהלך יוני 2026, מצא את אזורי ההנחיה שבהם שיעור הטיסות ארוכות הטווח גבוה מהממוצע של כלל הטיסות בתקופה. הצג את מספר הטיסות בכל אזור, מספר הטיסות ארוכות הטווח, השיעור שלהן והפער בנקודות אחוז מהממוצע הכללי. מיין לפי הפער מהגבוה לנמוך." + }, + { + "id": "q09", + "question": "זהה את עשר הרשויות שבהן היחס בין מספר האנשים השוהים במתקני האירוח לבין מספר העובדים הוא הגבוה ביותר, בתנאי שיש בהן לפחות 500 אנשים. הצג גם את מספר החדרים, את מספר האנשים לכל חדר ואת מועד העדכון של נתוני האירוח. אל תכלול רשויות שבהן מספר העובדים הוא אפס." + }, + { + "id": "q10", + "question": "עבור כל אזור הנחיה, הצג את המדיניות העדכנית ביותר הידועה, את תאריך העדכון שלה ואת מספר הטיסות ששויכו לאזור במהלך יולי 2026. הצג גם אזורים שאין להם טיסות בתקופה, וודא שאזור שמופיעות עבורו כמה גרסאות של מדיניות נספר פעם אחת בלבד." + } +] diff --git a/agent/pyproject.toml b/agent/pyproject.toml index 9e9fb98..9b7296a 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -29,6 +29,7 @@ dependencies = [ [project.scripts] deep-agent = "deep_agent.cli:main" +deep-agent-bench = "deep_agent.benchmark:main" [tool.uv.sources] core = { path = "../core", editable = true } diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 1a69a0e..5e26b08 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -53,6 +53,8 @@ class AgentSettings(BaseSettings): DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows DEEP_AGENT_TRACING_ENABLED: bool = True # Langfuse callbacks, span metadata and run scores DEEP_AGENT_CLARIFICATIONS_ENABLED: bool = False # let the model ask a clarifying question instead of answering + JEEN_METADATA_CACHE_TTL_S: float = Field(default=300.0, ge=0) # metadata read cache (0 disables) + JEEN_METADATA_REUSE_SESSION: bool = True # keep one MCP session open per event loop # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" diff --git a/agent/src/agent/utils/jeen_metadata_client.py b/agent/src/agent/utils/jeen_metadata_client.py index e34d254..d22557f 100644 --- a/agent/src/agent/utils/jeen_metadata_client.py +++ b/agent/src/agent/utils/jeen_metadata_client.py @@ -41,8 +41,13 @@ from __future__ import annotations +import asyncio +import copy import json import logging +import time +import weakref +from datetime import timedelta from typing import Any, NoReturn from mcp import ClientSession @@ -57,10 +62,133 @@ class JeenMetadataError(RuntimeError): """The MCP server reported an error, or returned a payload of an unexpected shape.""" +# Read-only metadata tools whose results may be served from the client's TTL cache. +_CACHEABLE_TOOLS = frozenset({ + "get_catalog_prompt", "get_tables", "get_columns", "get_relationships", "get_table_profile", "get_column_profile", +}) + + # --------------------------------------------------------------------------- # Low-level MCP call helper # --------------------------------------------------------------------------- +class _PersistentSession: + """One long-lived MCP ClientSession, owned by a background task. + + anyio requires the transport/session context managers to be entered and exited in the + same task, so a dedicated task holds them open; callers in other tasks use + `session.call_tool(...)` concurrently (MCP multiplexes requests by id). A broken + session is invalidated and transparently re-created on the next call. + """ + + def __init__(self, url: str, api_key: str, timeout: float) -> None: + self._url, self._api_key, self._timeout = url, api_key, timeout + self._session: ClientSession | None = None + self._task: asyncio.Task | None = None + self._ready = asyncio.Event() + self._stop = asyncio.Event() + self._error: BaseException | None = None + self._lock = asyncio.Lock() + self.handshakes = 0 # number of initialize() handshakes performed (observability/tests) + + async def get(self) -> ClientSession: + async with self._lock: + if self._session is None or self._task is None or self._task.done(): + self._ready, self._stop, self._error = asyncio.Event(), asyncio.Event(), None + self._task = asyncio.create_task(self._run(), name="jeen-mcp-session") + await asyncio.wait_for(self._ready.wait(), timeout=self._timeout + 5) + if self._session is None: + raise JeenMetadataError(f"Could not open MCP session: {self._error}") + return self._session + + async def _run(self) -> None: + try: + async with streamablehttp_client( + self._url, + headers={"Authorization": f"Bearer {self._api_key}"}, + timeout=self._timeout, + sse_read_timeout=self._timeout + 30, + ) as (read, write, _get_session_id): + async with ClientSession(read, write) as session: + await session.initialize() + self.handshakes += 1 + self._session = session + self._ready.set() + await self._stop.wait() + except BaseException as exc: # noqa: BLE001 — recorded and surfaced to the caller + self._error = exc + if isinstance(exc, asyncio.CancelledError): + raise + finally: + self._session = None + self._ready.set() + + def invalidate(self) -> None: + self._session = None + self._stop.set() + + async def close(self) -> None: + self._stop.set() + if self._task is not None: + await asyncio.gather(self._task, return_exceptions=True) + + +# One persistent session per (event loop, url, key). +_sessions: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[tuple[str, str], _PersistentSession]]" = ( + weakref.WeakKeyDictionary() +) + + +def _persistent_session(url: str, api_key: str, timeout: float) -> _PersistentSession: + per_loop = _sessions.setdefault(asyncio.get_running_loop(), {}) + if (url, api_key) not in per_loop: + per_loop[(url, api_key)] = _PersistentSession(url, api_key, timeout) + return per_loop[(url, api_key)] + + +async def close_mcp_sessions() -> None: + """Close this event loop's persistent MCP sessions (call before the loop shuts down).""" + per_loop = _sessions.pop(asyncio.get_running_loop(), {}) + await asyncio.gather(*(s.close() for s in per_loop.values()), return_exceptions=True) + + +def _parse_tool_result(tool_name: str, result: Any) -> Any: + # result.content is a list of ContentBlock objects. + # We expect the first (and only) block to be a TextContent. + first = result.content[0] if result.content else None + text = getattr(first, "text", None) + + if getattr(result, "isError", False): + raise JeenMetadataError(f"MCP tool '{tool_name}' failed: {text or 'no error details'}") + if text is None: + return {} + + try: + return json.loads(text) + except json.JSONDecodeError: + return text + + +async def _call_with_persistent_session( + url: str, api_key: str, tool_name: str, arguments: dict[str, Any], timeout: float +) -> Any: + holder = _persistent_session(url, api_key, timeout) + for attempt in (1, 2): + session = await holder.get() + try: + result = await session.call_tool( + tool_name, arguments, read_timeout_seconds=timedelta(seconds=timeout) + ) + return _parse_tool_result(tool_name, result) + except JeenMetadataError: + raise + except Exception as exc: + holder.invalidate() # stale/broken session: reconnect once + if attempt == 2: + raise + logger.info("MCP session for %s failed (%s); reconnecting", url, exc) + + async def _call_mcp_tool( url: str, api_key: str, @@ -69,16 +197,19 @@ async def _call_mcp_tool( timeout: float = 15.0, ) -> Any: """ - Open an MCP session, run the full initialization handshake, call one - tool, and return the parsed payload from the first text content block. + Call one MCP tool and return the parsed payload from the first text content block. - Uses the official Python MCP SDK so the - initialize → notifications/initialized → tools/call sequence is handled - automatically. Returns parsed JSON (dict/list) or a raw string if the + With JEEN_METADATA_REUSE_SESSION (default) the MCP session is kept open per event loop, + so the initialize → notifications/initialized handshake happens once instead of on + every call. Otherwise (or if the persistent path cannot be set up) a session is opened + for this call only. Uses the official Python MCP SDK, which handles the handshake and + both JSON and SSE responses. Returns parsed JSON (dict/list) or a raw string if the content block is not JSON. """ - headers = {"Authorization": f"Bearer {api_key}"} + if settings.JEEN_METADATA_REUSE_SESSION: + return await _call_with_persistent_session(url, api_key, tool_name, arguments, timeout) + headers = {"Authorization": f"Bearer {api_key}"} async with streamablehttp_client( url, headers=headers, @@ -89,23 +220,8 @@ async def _call_mcp_tool( ) as (read, write, _get_session_id): async with ClientSession(read, write) as session: await session.initialize() - result = await session.call_tool(tool_name, arguments) - - # result.content is a list of ContentBlock objects. - # We expect the first (and only) block to be a TextContent. - first = result.content[0] if result.content else None - text = getattr(first, "text", None) - - if getattr(result, "isError", False): - raise JeenMetadataError(f"MCP tool '{tool_name}' failed: {text or 'no error details'}") - if text is None: - return {} - - try: - return json.loads(text) - except json.JSONDecodeError: - return text + return _parse_tool_result(tool_name, result) def _reraise_as_metadata_error(exc: Exception) -> NoReturn: @@ -145,6 +261,8 @@ def __init__(self) -> None: getattr(settings, "JEEN_METADATA_SEARCH_LIMIT", settings.HYBRID_SEARCH_MAX_TABLES) ) self._timeout: float = float(getattr(settings, "JEEN_METADATA_PROFILE_TIMEOUT", 15.0)) + self._cache: dict[tuple[str, str], tuple[float, Any]] = {} + self._inflight: dict[tuple[str, str], asyncio.Future] = {} self.is_configured: bool = bool( self._mcp_url and self._mcp_key and self._connection_id @@ -165,7 +283,30 @@ def _cid(self, connection_id: int | None) -> int: return connection_id if connection_id is not None else self._connection_id async def _call(self, tool_name: str, arguments: dict[str, Any]) -> Any: - """Thin wrapper so individual methods don't repeat the URL/key/timeout.""" + """Call an MCP tool; read-only metadata tools are served from a TTL cache (single-flight).""" + ttl = settings.JEEN_METADATA_CACHE_TTL_S + if tool_name not in _CACHEABLE_TOOLS or ttl <= 0: + return await self._call_uncached(tool_name, arguments) + + key = (tool_name, json.dumps(arguments, sort_keys=True, default=str)) + hit = self._cache.get(key) + if hit is not None and hit[0] > time.monotonic(): + return copy.deepcopy(hit[1]) + + inflight = self._inflight.get(key) + if inflight is None: + inflight = asyncio.ensure_future(self._call_uncached(tool_name, arguments)) + self._inflight[key] = inflight + try: + value = await asyncio.shield(inflight) # a cancelled caller must not cancel the shared fetch + self._cache[key] = (time.monotonic() + ttl, value) # errors are never cached + finally: + self._inflight.pop(key, None) + else: + value = await asyncio.shield(inflight) + return copy.deepcopy(value) + + async def _call_uncached(self, tool_name: str, arguments: dict[str, Any]) -> Any: return await _call_mcp_tool( self._mcp_url, self._mcp_key, @@ -174,6 +315,10 @@ async def _call(self, tool_name: str, arguments: dict[str, Any]) -> Any: self._timeout, ) + def clear_cache(self) -> None: + """Drop cached metadata (e.g. after a profiling run updates the catalog).""" + self._cache.clear() + # ------------------------------------------------------------------ # Search Column Values # ------------------------------------------------------------------ diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 2f1dc5e..616f6a8 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -12,6 +12,7 @@ from deep_agent.answer import AnswerVerificationMiddleware, answer_schema from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware from deep_agent.resources import build_resources +from deep_agent.tool_filter import BuiltinToolFilterMiddleware from deep_agent.tools import DEEP_AGENT_TOOLS @@ -90,7 +91,7 @@ - Break complex or multi-step logic into named CTE blocks (e.g. `WITH filtered_data AS (...), aggregated_counts AS (...)`). - CTEs make queries significantly cleaner to read, prevent join fan-out (by aggregating child tables in a CTE before joining), and make window rankings (`ROW_NUMBER() / RANK()`) and multi-stage metrics easy to organize. - SQL uses ONLY confirmed 3-part table names: `"catalog"."schema"."table"` -- `validate_sql` — Trino checks the draft without running it (syntax, table/column names, types, functions). Always call before `execute_trino_query` on a fresh draft. +- `validate_sql` — optional dry-run by Trino (syntax, names, types; reads no data). For an invalid query `execute_trino_query` fails at the same step, just as fast and with the same error, so validating first usually saves nothing — use it only to check a draft you don't want to run yet. - `enrich_sql_filters` — run on any SQL that filters text columns --- @@ -152,7 +153,7 @@ - `execute_trino_query` — runs SQL; on failure `error` carries Trino's own `name` / `type` / `message` - `get_sample_rows` — peek at raw data format, string casing, date format - `get_column_distinct_values` — live distinct values. Appropriate for standard low-cardinality `categorical` columns (e.g. `launch_country`) when not listed in catalog. -- `validate_sql` — dry-run check by Trino, reads no data. Call before every execute on a new draft. +- `validate_sql` — optional dry-run; not needed before executing. **Post-processing** - `enrich_sql_filters` — AST-level auto-correction of categorical filter values. Use after drafting SQL with text filters. @@ -219,7 +220,7 @@ def create_deep_agent(model: BaseChatModel | None = None, clarifications_enabled model=llm, tools=DEEP_AGENT_TOOLS, system_prompt=SYSTEM_PROMPT + CLARIFICATION_PROMPT if clarifications_enabled else SYSTEM_PROMPT, - middleware=[DeepAgentContextMiddleware(), AnswerVerificationMiddleware()], + middleware=[DeepAgentContextMiddleware(), AnswerVerificationMiddleware(), BuiltinToolFilterMiddleware()], response_format=ToolStrategy(answer_schema(clarifications_enabled)), context_schema=DeepAgentContext, checkpointer=memory, diff --git a/agent/src/deep_agent/answer.py b/agent/src/deep_agent/answer.py index 7fc3d26..b095559 100644 --- a/agent/src/deep_agent/answer.py +++ b/agent/src/deep_agent/answer.py @@ -126,7 +126,7 @@ def _re_execute(answer_sql: str) -> tuple[VerificationStatus, dict[str, Any] | N guarded = sql_guard.prepare(clean_sql(answer_sql), row_cap) except sql_guard.GuardError as e: return "rejected", None, str(e) - res = execute_query_sync(guarded.sql) + res = execute_query_sync(guarded.sql, reuse_connection=True) if not res.success: return "re_execution_failed", None, res.error_message rows = res.rows or [] diff --git a/agent/src/deep_agent/benchmark.py b/agent/src/deep_agent/benchmark.py new file mode 100644 index 0000000..203ca79 --- /dev/null +++ b/agent/src/deep_agent/benchmark.py @@ -0,0 +1,155 @@ +""" +Latency / cost benchmark for the Deep Agent. + + uv run deep-agent-bench # benchmarks/deep_agent_questions.json + uv run deep-agent-bench --questions my.json --out runs/bench.json --concurrency 2 + +Reports per question and in aggregate: wall-clock latency (p50/p95), model calls, tool +calls, SQL executions, input/output tokens (from provider usage metadata) and the answer +status of the final answer (executed or not). Accuracy against gold SQL is the evaluation harness's job (#44). +""" + +import argparse +import asyncio +import json +import math +import time +import uuid +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any + +from deep_agent import observability +from deep_agent.context import DeepAgentContext + +DEFAULT_QUESTIONS = Path(__file__).resolve().parents[2] / "benchmarks" / "deep_agent_questions.json" + + +@dataclass(frozen=True) +class QuestionRun: + id: str + question: str + latency_s: float + model_calls: int + tool_calls: int + sql_executions: int + input_tokens: int + output_tokens: int + status: str + executed: bool + error: str | None = None + + +def percentile(values: list[float], pct: float) -> float: + """Nearest-rank percentile (pct in 0–100).""" + if not values: + return 0.0 + ordered = sorted(values) + rank = max(1, math.ceil(pct / 100 * len(ordered))) + return ordered[rank - 1] + + +def _token_usage(messages: list) -> tuple[int, int]: + inp = out = 0 + for m in messages: + usage = getattr(m, "usage_metadata", None) or {} + inp += int(usage.get("input_tokens") or 0) + out += int(usage.get("output_tokens") or 0) + return inp, out + + +async def run_question(agent, item: dict[str, Any], context: DeepAgentContext) -> QuestionRun: + thread_id = f"bench_{item['id']}_{uuid.uuid4().hex[:6]}" + config = observability.build_run_config(thread_id, connection_id=context.connection_id) + start = time.perf_counter() + error = None + try: + state = await agent.ainvoke({"messages": [("user", item["question"])]}, config, context=context) + final_result = state.get("final_result") or {"status": "no_answer", "executed": False} + except Exception as exc: # one failing question must not abort the benchmark + state, final_result, error = {"messages": []}, {"status": "error", "executed": False}, repr(exc) + latency = time.perf_counter() - start + + messages = state.get("messages") or [] + metrics = observability.run_metrics(messages, latency, final_result) + observability.score_run(observability.langfuse_trace_id(config), metrics) + input_tokens, output_tokens = _token_usage(messages) + return QuestionRun( + id=item["id"], question=item["question"], latency_s=metrics.latency_s, model_calls=metrics.model_calls, + tool_calls=metrics.tool_calls, sql_executions=metrics.sql_executions, input_tokens=input_tokens, + output_tokens=output_tokens, status=final_result.get("status", "no_answer"), + executed=bool(final_result.get("executed")), error=error, + ) + + +async def run_benchmark( + agent, questions: list[dict[str, Any]], context: DeepAgentContext, concurrency: int = 1, +) -> list[QuestionRun]: + sem = asyncio.Semaphore(max(1, concurrency)) + + async def one(item): + async with sem: + return await run_question(agent, item, context) + + return list(await asyncio.gather(*(one(q) for q in questions))) + + +def summarize(runs: list[QuestionRun]) -> dict[str, Any]: + n = len(runs) or 1 + latencies = [r.latency_s for r in runs] + return { + "questions": len(runs), + "latency_p50_s": round(percentile(latencies, 50), 2), + "latency_p95_s": round(percentile(latencies, 95), 2), + "avg_model_calls": round(sum(r.model_calls for r in runs) / n, 2), + "avg_tool_calls": round(sum(r.tool_calls for r in runs) / n, 2), + "avg_sql_executions": round(sum(r.sql_executions for r in runs) / n, 2), + "avg_input_tokens": round(sum(r.input_tokens for r in runs) / n), + "avg_output_tokens": round(sum(r.output_tokens for r in runs) / n), + "executed_rate": round(sum(r.executed for r in runs) / n, 3), + "errors": sum(1 for r in runs if r.error), + } + + +def _print_report(runs: list[QuestionRun], summary: dict[str, Any]) -> None: + print(f"{'id':5} {'latency':>8} {'model':>6} {'tools':>6} {'sql':>4} {'in_tok':>8} {'out_tok':>8} status") + for r in runs: + print(f"{r.id:5} {r.latency_s:8.2f} {r.model_calls:6d} {r.tool_calls:6d} {r.sql_executions:4d} " + f"{r.input_tokens:8d} {r.output_tokens:8d} {r.status}{' (' + r.error + ')' if r.error else ''}") + print(json.dumps(summary, indent=2)) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Benchmark Deep Agent latency and cost.") + parser.add_argument("--questions", type=Path, default=DEFAULT_QUESTIONS) + parser.add_argument("--connection-id", type=int, default=None) + parser.add_argument("--concurrency", type=int, default=1) + parser.add_argument("--out", type=Path, default=None, help="Write per-question results + summary as JSON.") + args = parser.parse_args() + + from agent.utils.jeen_metadata_client import close_mcp_sessions + from deep_agent.agent import create_deep_agent + + questions = json.loads(args.questions.read_text(encoding="utf-8")) + + async def _run(): + try: + return await run_benchmark(create_deep_agent(), questions, DeepAgentContext(connection_id=args.connection_id), + concurrency=args.concurrency) + finally: + await close_mcp_sessions() + + try: + runs = asyncio.run(_run()) + finally: + observability.flush() + summary = summarize(runs) + _print_report(runs, summary) + if args.out: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps({"summary": summary, "runs": [asdict(r) for r in runs]}, + ensure_ascii=False, indent=2), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/agent/src/deep_agent/cli.py b/agent/src/deep_agent/cli.py index 83855e5..466f2b9 100644 --- a/agent/src/deep_agent/cli.py +++ b/agent/src/deep_agent/cli.py @@ -19,6 +19,7 @@ from langchain_core.messages import BaseMessage from agent.config import settings +from agent.utils.jeen_metadata_client import close_mcp_sessions from deep_agent.agent import create_deep_agent from deep_agent import observability from deep_agent.answer import render_markdown @@ -235,7 +236,13 @@ def next_thread_id() -> str: print(f"{MAGENTA}{BOLD}Initializing Deep Agent...{RESET}") agent = create_deep_agent() + try: + await _run_questions(agent, args, context, next_thread_id) + finally: + await close_mcp_sessions() # the persistent Jeen MCP session lives as long as this event loop + +async def _run_questions(agent, args: argparse.Namespace, context: DeepAgentContext, next_thread_id) -> None: if args.interactive: print(f"{GREEN}{BOLD}Starting Interactive Mode. Type 'quit', 'exit', or 'q' to stop.{RESET}") while True: diff --git a/agent/src/deep_agent/memory/AGENTS.md b/agent/src/deep_agent/memory/AGENTS.md index abceff5..6aa0d75 100644 --- a/agent/src/deep_agent/memory/AGENTS.md +++ b/agent/src/deep_agent/memory/AGENTS.md @@ -141,8 +141,10 @@ Before writing the final response, translate your SQL back to plain English and **Subagent delegation can keep your context clean.** If you need to explore many tables or profile many columns at once — delegate to a focused subagent via `task` and process the result. Don't exhaust your context on breadth-first exploration inline. -**`validate_sql` is cheap.** -Runs `EXPLAIN (TYPE VALIDATE)` — Trino checks syntax, names and types without touching data. Call it before every `execute_trino_query` on a fresh draft. +**`validate_sql` is optional.** +Runs `EXPLAIN (TYPE VALIDATE)` — Trino checks syntax, names and types without touching data. For an invalid query, +`execute_trino_query` fails at the same step, just as fast, without reading data and with the same error — so validating +first usually saves nothing. Use it only to check a draft you don't want to run yet. **Dumping distinct values on high-cardinality columns wastes latency and tokens.** For `large_categorical` or `large_unit_id` columns with hundreds or thousands of values, `get_column_distinct_values` returns a random slice of unrelated values. Always use `search_column_values` for targeted search on high-cardinality columns, and save `get_column_distinct_values` for low-cardinality categories. diff --git a/agent/src/deep_agent/tool_filter.py b/agent/src/deep_agent/tool_filter.py new file mode 100644 index 0000000..7350784 --- /dev/null +++ b/agent/src/deep_agent/tool_filter.py @@ -0,0 +1,35 @@ +""" +Hide deepagents built-in tools this agent never needs. + +Every model call carries the schema of every bound tool; dropping these saves ~1k prompt +tokens per call and removes off-task options: +- execute: always errors without a sandbox backend +- write_file / edit_file: skills and memory are read-only; planning goes through write_todos +- glob / grep: the skills are listed in the prompt with their paths and read with read_file +""" + +from collections.abc import Awaitable, Callable + +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse + +EXCLUDED_BUILTIN_TOOLS = frozenset({"execute", "write_file", "edit_file", "glob", "grep"}) + + +class BuiltinToolFilterMiddleware(AgentMiddleware): + """Remove excluded built-in tools from every model request.""" + + def __init__(self, excluded: frozenset[str] = EXCLUDED_BUILTIN_TOOLS) -> None: + super().__init__() + self.excluded = excluded + + def _filter(self, request: ModelRequest) -> ModelRequest: + tools = [t for t in request.tools if getattr(t, "name", None) not in self.excluded] + return request.override(tools=tools) + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(self._filter(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(self._filter(request)) diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 14afbfe..bd89f14 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -213,7 +213,7 @@ def _execute(sql: str, row_cap: int | None) -> tuple[str, dict | None]: and onto the current Langfuse tool observation. """ try: - res = execute_query_sync(sql) + res = execute_query_sync(sql, reuse_connection=True) except Exception as e: err = trino_errors.from_exception(e) annotate_current_span({"error_name": err["name"]}, level="ERROR") @@ -358,8 +358,10 @@ def validate_sql(sql: str) -> str: resolves it against the catalog: syntax, table and column names, types and function signatures. No data is read. - Use this to dry-run a new draft before execute_trino_query. It cannot tell you whether the - query returns rows. + Optional. For an invalid query, execute_trino_query fails at the same checking step, just as + fast and without reading data, with the same error fields — so validating first usually + saves nothing. Use it only to check a draft you do not want to run yet. It cannot tell you + whether the query returns rows. Returns ok=true with data.valid=true, or ok=false with the same error fields as execute_trino_query (error.name, error.type, error.message, error.location). @@ -373,7 +375,7 @@ def validate_sql(sql: str) -> str: except sql_guard.GuardError as e: return fail(trino_errors.forbidden(str(e))) try: - res = execute_query_sync(f"{_VALIDATE_PREFIX}{sql_clean}") + res = execute_query_sync(f"{_VALIDATE_PREFIX}{sql_clean}", reuse_connection=True) except Exception as e: return fail(trino_errors.from_exception(e)) if res.success: diff --git a/agent/tests/deep_agent/conftest.py b/agent/tests/deep_agent/conftest.py index fa82162..86a9726 100644 --- a/agent/tests/deep_agent/conftest.py +++ b/agent/tests/deep_agent/conftest.py @@ -10,8 +10,10 @@ class ScriptedChatModel(GenericFakeChatModel): """Fake chat model that replays scripted AIMessages and records every prompt it receives.""" seen: list[list[BaseMessage]] = [] + bound_tool_names: list[list[str]] = [] def bind_tools(self, tools, **kwargs): # deepagents binds tools; the script decides the calls + self.bound_tool_names.append([getattr(t, "name", None) or t.get("name") for t in tools]) return self def _generate(self, messages, stop=None, run_manager=None, **kwargs): @@ -24,6 +26,7 @@ def scripted_model(): def _make(*replies: AIMessage) -> ScriptedChatModel: model = ScriptedChatModel(messages=iter(replies)) model.seen = [] + model.bound_tool_names = [] return model return _make @@ -51,6 +54,7 @@ def policy_model(): def _make(policy: Callable[[list[BaseMessage]], AIMessage]) -> PolicyChatModel: model = PolicyChatModel(messages=iter([]), policy=policy) model.seen = [] + model.bound_tool_names = [] return model return _make diff --git a/agent/tests/deep_agent/test_latency.py b/agent/tests/deep_agent/test_latency.py new file mode 100644 index 0000000..c6399ab --- /dev/null +++ b/agent/tests/deep_agent/test_latency.py @@ -0,0 +1,212 @@ +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from langchain_core.messages import AIMessage + +import agent.utils.jeen_metadata_client as jmc +import core.trino as core_trino +from agent.config import settings +from agent.utils.jeen_metadata_client import JeenMetadataClient, JeenMetadataError, close_mcp_sessions +from core.trino import TrinoExecutionResult +from deep_agent import benchmark, tools +from deep_agent.agent import create_deep_agent +from deep_agent.tool_filter import EXCLUDED_BUILTIN_TOOLS + +OK = TrinoExecutionResult(success=True, rows=[[7]], columns=["n"], row_count=1, query_id="q") + + +@pytest.mark.asyncio +async def test_unused_builtin_tools_are_not_offered_to_the_model(scripted_model): + model = scripted_model(AIMessage("done")) + await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "t"}}) + offered = set(model.bound_tool_names[-1]) + assert not offered & EXCLUDED_BUILTIN_TOOLS + assert {"read_file", "write_todos", "execute_trino_query", "DeepAgentAnswer"} <= offered + + +# ── metadata cache ────────────────────────────────────────────────────────── + +@pytest.fixture +def client(): + c = JeenMetadataClient() + c.clear_cache() + return c + + +@pytest.mark.asyncio +async def test_metadata_reads_are_cached(client): + with patch.object(client, "_call_uncached", AsyncMock(return_value=[{"name": "t"}])) as fetch: + first = await client.get_tables(connection_id=1) + first.append({"name": "mutated"}) # callers can't corrupt the cache + second = await client.get_tables(connection_id=1) + await client.get_tables(connection_id=2) # different connection -> separate entry + assert second == [{"name": "t"}] + assert fetch.await_count == 2 + + +@pytest.mark.asyncio +async def test_concurrent_identical_reads_are_single_flight(client): + async def slow(*_): + await asyncio.sleep(0.05) + return [{"name": "t"}] + + with patch.object(client, "_call_uncached", AsyncMock(side_effect=slow)) as fetch: + results = await asyncio.gather(*(client.get_relationships(connection_id=1) for _ in range(5))) + assert fetch.await_count == 1 + assert all(r == [{"name": "t"}] for r in results) + + +@pytest.mark.asyncio +async def test_errors_are_not_cached_and_ttl_zero_disables(client, monkeypatch): + with patch.object(client, "_call_uncached", AsyncMock(side_effect=[JeenMetadataError("boom"), [{"x": 1}]])) as fetch: + with pytest.raises(JeenMetadataError): + await client.get_tables(connection_id=1) + assert await client.get_tables(connection_id=1) == [{"x": 1}] + assert fetch.await_count == 2 + + monkeypatch.setattr(settings, "JEEN_METADATA_CACHE_TTL_S", 0) + with patch.object(client, "_call_uncached", AsyncMock(return_value=[])) as fetch: + await client.get_tables(connection_id=1) + await client.get_tables(connection_id=1) + assert fetch.await_count == 2 + + +@pytest.mark.asyncio +async def test_search_results_are_not_cached(client): + with patch.object(client, "_call_uncached", AsyncMock(return_value={"values": []})) as fetch: + await client.search_column_values("x", raw=True) + await client.search_column_values("x", raw=True) + assert fetch.await_count == 2 + + +# ── persistent MCP session ────────────────────────────────────────────────── + +class FakeTransport: + """Counts MCP handshakes; call_tool can be told to fail once like a dropped session.""" + + def __init__(self, fail_first_call=False): + self.handshakes = 0 + self.calls = 0 + self.fail_first_call = fail_first_call + + def transport(self, *args, **kwargs): + return MagicMock(__aenter__=AsyncMock(return_value=(None, None, None)), __aexit__=AsyncMock(return_value=False)) + + def session(self, *args, **kwargs): + outer = self + + async def initialize(): + outer.handshakes += 1 + + async def call_tool(name, arguments, **kwargs): + outer.calls += 1 + await asyncio.sleep(0.01) + if outer.fail_first_call and outer.calls == 1: + raise ConnectionError("session expired") + return SimpleNamespace(isError=False, content=[SimpleNamespace(text='{"tables": []}')]) + + session = MagicMock(initialize=initialize, call_tool=call_tool) + return MagicMock(__aenter__=AsyncMock(return_value=session), __aexit__=AsyncMock(return_value=False)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fail_first_call, expected_handshakes", [(False, 1), (True, 2)]) +async def test_mcp_session_is_reused_across_calls(fail_first_call, expected_handshakes): + fake = FakeTransport(fail_first_call) + with patch.object(jmc, "streamablehttp_client", side_effect=fake.transport), \ + patch.object(jmc, "ClientSession", side_effect=fake.session): + for _ in range(3): + await jmc._call_mcp_tool("http://mcp", "k", "get_tables", {}) + await asyncio.gather(*(jmc._call_mcp_tool("http://mcp", "k", "get_tables", {}) for _ in range(5))) + await close_mcp_sessions() + assert fake.handshakes == expected_handshakes + assert fake.calls == 8 + int(fail_first_call) + + +@pytest.mark.asyncio +async def test_mcp_per_call_sessions_when_reuse_disabled(monkeypatch): + monkeypatch.setattr(settings, "JEEN_METADATA_REUSE_SESSION", False) + fake = FakeTransport() + with patch.object(jmc, "streamablehttp_client", side_effect=fake.transport), \ + patch.object(jmc, "ClientSession", side_effect=fake.session): + for _ in range(3): + await jmc._call_mcp_tool("http://mcp", "k", "get_tables", {}) + assert fake.handshakes == 3 + + +# ── Trino connection reuse ────────────────────────────────────────────────── + +def _fake_connection(fail=False): + conn = MagicMock() + cur = conn.cursor.return_value + cur.description = [("n",)] + cur.fetchall.return_value = [(1,)] + cur.query_id = "20261020_000000_00001_abcde" + if fail: + cur.execute.side_effect = RuntimeError("connection reset") + return conn + + +def test_trino_connection_is_reused_per_thread_and_dropped_on_error(monkeypatch): + monkeypatch.setattr(core_trino.settings, "TRINO_ENABLED", True) + core_trino._drop_reusable_connection() + conns = [_fake_connection(), _fake_connection(fail=True), _fake_connection()] + with patch.object(core_trino, "get_trino_connection", side_effect=conns) as connect: + for _ in range(3): + assert core_trino.execute_query_sync("SELECT 1", reuse_connection=True).success + assert connect.call_count == 1 # one connection for three queries + conns[0].cursor.return_value.execute.side_effect = RuntimeError("connection reset") + assert not core_trino.execute_query_sync("SELECT 1", reuse_connection=True).success + assert core_trino.execute_query_sync("SELECT 1", reuse_connection=True).success is False # conns[1] fails + assert core_trino.execute_query_sync("SELECT 1", reuse_connection=True).success # fresh conns[2] + assert connect.call_count == 3 + core_trino._drop_reusable_connection() + + +def test_default_execution_still_opens_and_closes_a_connection(monkeypatch): + monkeypatch.setattr(core_trino.settings, "TRINO_ENABLED", True) + conn = _fake_connection() + with patch.object(core_trino, "get_trino_connection", return_value=conn): + core_trino.execute_query_sync("SELECT 1") + conn.close.assert_called_once() + + +# ── benchmark ─────────────────────────────────────────────────────────────── + +def test_percentile_nearest_rank(): + assert benchmark.percentile([5, 1, 3, 2, 4], 50) == 3 + assert benchmark.percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 95) == 10 + assert benchmark.percentile([], 95) == 0.0 + + +@pytest.mark.asyncio +async def test_benchmark_reports_calls_tokens_and_status(policy_model): + def policy(messages): + if not [m for m in messages if m.type == "tool"]: + msg = AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": "SELECT 7 AS n"}, "id": "e"}]) + else: + msg = AIMessage("", tool_calls=[{"name": "DeepAgentAnswer", "id": "f", "args": { + "sql": "SELECT 7 AS n", "explanation_he": "שבע", "confidence": "high"}}]) + msg.usage_metadata = {"input_tokens": 100, "output_tokens": 10, "total_tokens": 110} + return msg + + agent = create_deep_agent(model=policy_model(policy)) + with patch.object(tools, "execute_query_sync", return_value=OK): + runs = await benchmark.run_benchmark(agent, [{"id": "q1", "question": "a"}, {"id": "q2", "question": "b"}], + benchmark.DeepAgentContext(), concurrency=2) + assert [r.status for r in runs] == ["matched", "matched"] + assert all(r.model_calls == 2 and r.sql_executions == 1 and r.input_tokens == 200 and r.output_tokens == 20 + for r in runs) + summary = benchmark.summarize(runs) + assert summary["questions"] == 2 and summary["executed_rate"] == 1.0 and summary["errors"] == 0 + + +def test_benchmark_question_set_is_valid(): + import json + + questions = json.loads(benchmark.DEFAULT_QUESTIONS.read_text(encoding="utf-8")) + assert len(questions) >= 10 + assert len({q["id"] for q in questions}) == len(questions) + assert all(q["question"].strip() for q in questions) diff --git a/core/src/core/trino.py b/core/src/core/trino.py index 13e356a..edfd571 100644 --- a/core/src/core/trino.py +++ b/core/src/core/trino.py @@ -3,6 +3,7 @@ """ import logging +import threading import time from typing import Any @@ -18,6 +19,27 @@ logger = logging.getLogger(__name__) +# Per-thread reusable connections for callers that opt in (execute_query_sync(reuse_connection=True)). +_thread_local = threading.local() + + +def _reusable_connection(): + conn = getattr(_thread_local, "connection", None) + if conn is None: + conn = get_trino_connection() + _thread_local.connection = conn + return conn + + +def _drop_reusable_connection() -> None: + conn = getattr(_thread_local, "connection", None) + _thread_local.connection = None + if conn is not None: + try: + conn.close() + except Exception: + pass + class TrinoExecutionResult(BaseModel): success: bool @@ -59,9 +81,17 @@ def get_trino_connection(): ) -def execute_query_sync(sql: str, table_id: str = "", params: tuple | dict | list | None = None) -> TrinoExecutionResult: +def execute_query_sync( + sql: str, + table_id: str = "", + params: tuple | dict | list | None = None, + reuse_connection: bool = False, +) -> TrinoExecutionResult: """ Execute a SQL query against the real Trino cluster. + + reuse_connection=True keeps one DBAPI connection per thread (no new HTTP/TLS setup per + query); a failed query drops it so the next call reconnects. """ start_time = time.time() log_sql = sql.strip().replace("\n", " ")[:300] @@ -78,7 +108,7 @@ def execute_query_sync(sql: str, table_id: str = "", params: tuple | dict | list conn = None cur = None try: - conn = get_trino_connection() + conn = _reusable_connection() if reuse_connection else get_trino_connection() cur = conn.cursor() if params is not None: cur.execute(sql, params) @@ -90,7 +120,8 @@ def execute_query_sync(sql: str, table_id: str = "", params: tuple | dict | list execution_time_ms = int((time.time() - start_time) * 1000) logger.info(f"[CoreTrinoClient] OK — {len(rows)} rows in {execution_time_ms}ms") cur.close() - conn.close() + if not reuse_connection: + conn.close() return TrinoExecutionResult( success=True, rows=[list(r) for r in rows], @@ -107,7 +138,9 @@ def execute_query_sync(sql: str, table_id: str = "", params: tuple | dict | list cur.close() except: pass - if conn is not None: + if reuse_connection: + _drop_reusable_connection() + elif conn is not None: try: conn.close() except: From f387f795cd4e8434df6855f4508de4e8e7a6c07b Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Wed, 28 Oct 2026 10:29:32 +0200 Subject: [PATCH 16/37] docs(deep-agent): one always-on prompt, general guidance, corrected skills (#40, revised) Based on deep-agent/40-guidance (800c031), revised in review: - system prompt moved to deep_agent/prompts/system.md: our full prompt plus the unique AGENTS.md content (CTE rules, grain/fan-out/intent checks, error table, lessons learned), each topic stated once; value-resolution policy has one owner; reconciled with Trino error fields, no prefix_pattern / sql_literal, clarifications only via the flag - AGENTS.md and the deepagents memory feature removed (static text framed as "may be outdated" + ~1.1k tokens of boilerplate); skills-only backend - skill fixes from the PR, verified on Trino: Sunday-based Hebrew week, half-open ranges, with_timezone, now()/date_format valid, areas-only spatial (data.wkt), optimizer-aware join advice, categorical policy, typo/example fixes - all catalog-specific examples replaced with general ones (prompt, skills, tool docstrings) - test_guidance_lint: tool refs exist, banned statements absent, no catalog-specific names, single policy owner, guidance SQL parses as Trino - always-on guidance per model call: 6,026 -> 3,074 tokens Co-Authored-By: Claude Opus 5.5 --- agent/src/agent/config.py | 1 - agent/src/deep_agent/agent.py | 180 +------------ agent/src/deep_agent/context.py | 4 +- agent/src/deep_agent/memory/AGENTS.md | 155 ----------- agent/src/deep_agent/prompts/system.md | 182 +++++++++++++ agent/src/deep_agent/resources.py | 39 +-- .../skills/semantic-validation/SKILL.md | 10 +- .../skills/spatial-analyst/SKILL.md | 51 ++-- .../skills/temporal-analyst/SKILL.md | 242 ++++++++---------- .../deep_agent/skills/trino-expert/SKILL.md | 57 +++-- agent/src/deep_agent/tools.py | 8 +- agent/tests/deep_agent/test_guidance_lint.py | 109 ++++++++ agent/tests/deep_agent/test_resources.py | 45 ++-- 13 files changed, 490 insertions(+), 593 deletions(-) delete mode 100644 agent/src/deep_agent/memory/AGENTS.md create mode 100644 agent/src/deep_agent/prompts/system.md create mode 100644 agent/tests/deep_agent/test_guidance_lint.py diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 5e26b08..124c852 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -47,7 +47,6 @@ class AgentSettings(BaseSettings): # ── Deep Agent ──────────────────────────────────────────────────────────── DEEP_AGENT_SKILLS_DIR: str | None = None # Override packaged skills dir (//SKILL.md) - DEEP_AGENT_MEMORY_DIR: str | None = None # Override packaged memory dir (must contain AGENTS.md) # Row ceilings for the deep agent's SQL tools. Set to "none" (or empty) to disable the ceiling. DEEP_AGENT_MAX_ROWS: int | None = Field(default=100, gt=0) # execute_trino_query / get_column_distinct_values DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 616f6a8..566307b 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -2,6 +2,8 @@ Agent logic and LangGraph harness for the Deep Agent. """ +from pathlib import Path + from deepagents import create_deep_agent as create_harness_agent from langchain.agents.structured_output import ToolStrategy from langchain_core.language_models import BaseChatModel @@ -16,181 +18,8 @@ from deep_agent.tools import DEEP_AGENT_TOOLS -SYSTEM_PROMPT = """You are an elite, autonomous Deep SQL Analyst. Your mission: translate Hebrew natural-language questions into verified Trino SQL that is **semantically correct** — not just syntactically valid or merely executable. - ---- - -## Non-negotiable Principle - -**Execution success ≠ correctness.** A query can run, return rows, and still be wrong. Semantic correctness — whether the SQL actually answers the user's question — is your responsibility. You must verify this, not just execute and hope. - ---- - -## Phase 1 — Understand (Discovery) - -Start here. Then move on — don't over-explore. - -- `get_database_catalog` — full schema with column stats and semantic types. **Call once, reuse the result.** - - If the catalog shows `(no knowledge pairs)`, do NOT call `search_knowledge_pairs`. - - If the catalog shows `(no business terms)`, do NOT call `search_business_terms`. - - If the catalog shows `(no relationships)`, do NOT call `get_table_relationships` (infer joins from matching column names like `flight_id`). -- `search_knowledge_pairs` — prior solved examples (use only when available in catalog). Check before exploring from scratch. -- `search_business_terms` / `search_metadata` — resolve ambiguous Hebrew/domain terms (use only when available in catalog). -- `get_table_relationships` — verified foreign keys and join paths (use only when available in catalog). - -Simple, unambiguous lookups may skip directly to Phase 2. - ---- - -## Phase 2 — Ground the Query Semantics (MANDATORY for any JOIN or aggregation) - -Before writing a single line of SQL, answer these: - -1. **Output grain**: What does ONE result row represent? (a flight? a city? a district count?) — state this explicitly -2. **Aggregation unit**: Am I counting *rows* or counting *distinct entities*? If there's a JOIN, which side? -3. **Fan-out risk**: Does any JOIN create a 1-to-many relationship? If yes, `COUNT(*)` will be inflated — plan to use `COUNT(DISTINCT id)` or aggregate in a CTE before joining -4. **String filters**: Every categorical filter value must be verified — use `search_column_values`, then `enrich_sql_filters` -5. **Date column type**: Is it a native DATE/TIMESTAMP or a VARCHAR string? Check `get_column_profile` — if string, you must parse it (see temporal-analyst skill) - -For complex or aggregation-heavy questions, write 1–2 lines stating the intent before drafting: -> *"Intent: count distinct flights (not rows) from France. The flights↔alerts join is 1-to-many, so I must use COUNT(DISTINCT flight_id), not COUNT(*)."* - ---- - -## Phase 3 — Value Resolution (By Semantic Type & Cardinality) - -Understand what each tool supports and choose based on the column's `semantic_type` and cardinality: - -> **Tool Capability Scope**: `search_column_values` works EXCLUSIVELY on **`large_categorical`** and **`large_unit_id`** columns. -> *(Standard `categorical` and `boolean` columns are NOT indexed in search and will return 0 matches. Numeric, date/timestamp, and geometry are also not indexed).* - -1. **High-Cardinality (`large_categorical` / `large_unit_id`)** (e.g., `city_name`, Company Name, Product SKU, Person Name): - - These columns contain hundreds or thousands of unique values that cannot fit in the system prompt. - - **`search_column_values` is the ideal tool**: Targeted hybrid search finds how the DB actually spells the specific entity (e.g., "Acme Corp" → "Acme Corporation LLC", or "Tel Aviv" → "Tel Aviv 1", "Tel Aviv 2"). - - If search reveals a composite pattern (e.g., "Tel Aviv 1", "Tel Aviv 57"), formulate a pattern filter like `LIKE 'Tel Aviv%'` or `IN (...)`. - - Avoid calling `get_column_distinct_values` on high-cardinality columns — dumping 50–100 random values into context is slow (10–20s) and will rarely hit the entity you need. - -2. **Standard `categorical` & `boolean`** (e.g., `launch_country`, Status, Priority, Flight Type, Gender, IsActive): - - **Do NOT call `search_column_values`** on standard `categorical` or `boolean` columns — they are not indexed in vector search and will return 0 results! - - Instead, check the catalog/profile first — when `domainIsComplete: true`, all valid values are already listed in the catalog without needing a tool call! - - If not listed in the catalog, call `get_column_distinct_values` to see the full set of valid options (usually just 5–20 rows, e.g. 7 countries in `launch_country`). - -3. **Numeric, Date, Timestamp, or Geometry columns**: - - `search_column_values` is NOT available for these types (not indexed). - - Use `get_sample_rows`, column profile min/max stats, or SQL casting/date parsing functions (see temporal-analyst skill). - -4. **AST Safety Net (`enrich_sql_filters`)**: - - After drafting SQL, call `enrich_sql_filters` — it automatically verifies and aligns your WHERE clause text filters against database metadata at the AST level before execution. - ---- - -## Phase 4 — Draft & Validate - -- **Use CTEs (`WITH ... AS (...)`) for clean, modular SQL**: - - Trino has first-class, highly optimized support for CTEs. - - Break complex or multi-step logic into named CTE blocks (e.g. `WITH filtered_data AS (...), aggregated_counts AS (...)`). - - CTEs make queries significantly cleaner to read, prevent join fan-out (by aggregating child tables in a CTE before joining), and make window rankings (`ROW_NUMBER() / RANK()`) and multi-stage metrics easy to organize. -- SQL uses ONLY confirmed 3-part table names: `"catalog"."schema"."table"` -- `validate_sql` — optional dry-run by Trino (syntax, names, types; reads no data). For an invalid query `execute_trino_query` fails at the same step, just as fast and with the same error, so validating first usually saves nothing — use it only to check a draft you don't want to run yet. -- `enrich_sql_filters` — run on any SQL that filters text columns - ---- - -## Phase 5 — Execute & Diagnose - -- `execute_trino_query` — always LIMIT exploratory queries -- Every tool returns `{"ok", "data", "error"}` — check `ok` first (`get_database_catalog` returns the catalog as plain text). **Read the error before retrying**: for SQL, `error.name` / `error.type` / `error.message` are Trino's own, and `error.location` points at the offending token: - - `SYNTAX_ERROR` → fix the specific line only, do not redesign - - `TABLE_NOT_FOUND` / `COLUMN_NOT_FOUND` → re-verify exact identifiers from catalog - - `TYPE_MISMATCH` → add `CAST(col AS type)` - - `FUNCTION_NOT_FOUND` → check Trino function spelling - - `0 rows` → investigate filter values, join keys, NULLs — do NOT just retry -- **NEVER retry an identical query without a meaningful change** - ---- - -## Phase 6 — Semantic Verification (MANDATORY for JOINs and aggregations) - -After a successful execution, validate before responding: - -**Fan-out check** — if you joined two tables and aggregated: -```sql --- Run this diagnostic if the count seems high: -SELECT COUNT(*) FROM left_table WHERE ; -- entity count before join -SELECT COUNT(*) FROM left_table JOIN right_table ON ...; -- row count after join --- If second > first → fan-out confirmed → use COUNT(DISTINCT id) -``` - -**Grain check** — does each row in your result represent the entity the user asked about? - -**Completeness check** — does the WHERE clause cover every condition the user mentioned? Did you accidentally add a condition they didn't ask for? - -**Sanity check** — does the number make intuitive sense? (e.g., "500 alerts from 3 districts" sounds plausible; "10,000 distinct flights from a 1,000-row table" does not) - -If any check fails or is uncertain, run a targeted diagnostic query. Do not guess. - ---- - -## Tool Reference - -**Schema & Metadata** -- `get_database_catalog` — complete schema. Use ONCE; reuse in context. -- `get_database_tables` — quick table roster with quoted identifiers -- `get_table_columns` — columns with types, examples, profiling stats -- `get_table_relationships` — verified foreign keys -- `get_table_profile` / `get_column_profile` — deep stats; `domainIsComplete: true` means listed values are the ENTIRE value set - -**Discovery** -- `search_metadata` — search all schema entities by concept -- `search_business_terms` — map Hebrew/domain vocabulary to DB terminology -- `search_knowledge_pairs` — prior solved examples (often reveals join paths) - -**Value Resolution** -- `search_column_values` — targeted search ONLY for high-cardinality entities (`large_categorical`, `large_unit_id`). Do NOT call on regular `categorical` or `boolean` (they are not indexed and return 0 matches). -- `resolve_location_to_wkt` — Hebrew location → WKT polygon for `ST_GeometryFromText(...)` - -**Execution** -- `execute_trino_query` — runs SQL; on failure `error` carries Trino's own `name` / `type` / `message` -- `get_sample_rows` — peek at raw data format, string casing, date format -- `get_column_distinct_values` — live distinct values. Appropriate for standard low-cardinality `categorical` columns (e.g. `launch_country`) when not listed in catalog. -- `validate_sql` — optional dry-run; not needed before executing. - -**Post-processing** -- `enrich_sql_filters` — AST-level auto-correction of categorical filter values. Use after drafting SQL with text filters. - -**Delegation** -- `task` — spawn a subagent for heavy exploration (many tables/columns) without consuming your context - ---- - -## Hard Constraints - -- NEVER guess or assume a string filter value — verify via tools -- NEVER reference a table or column not confirmed in the catalog -- ALWAYS use exact 3-part table names: `"catalog"."schema"."table"` -- ALWAYS LIMIT exploratory queries -- NEVER use `ST_GeomFromText()` — only `ST_GeometryFromText()` exists in Trino -- NEVER use `ILIKE` (unsupported in Trino) — use `LOWER(col) LIKE LOWER('val')` or `regexp_like(col, '(?i)...')` -- NEVER end queries with a semicolon `;` (Trino parser rejects trailing semicolons) -- NEVER wrap column identifiers in single quotes `'col'` (single quotes are for string literals only) -- NEVER include the literal token `'kill'` anywhere in SQL -- NEVER write SQL inline comments (`--` or `/* */`) -- NEVER use Hebrew as SQL identifiers or variable names -- NEVER return 0-row results without first investigating why -- NEVER retry an identical failed query without a meaningful change - ---- - -## Final Answer - -Finish by calling `DeepAgentAnswer` exactly once: -- `sql` — the exact final SQL you executed successfully with `execute_trino_query` (it is checked against your executions) -- `explanation_he` — a brief Hebrew explanation of what the SQL does and what the result means -- `assumptions` — interpretation choices you made (Hebrew) -- `confidence` — high / medium / low - -Do NOT type result tables — the rows shown to the user are taken directly from the executed query. -""" +PROMPTS_DIR = Path(__file__).resolve().parent / "prompts" +SYSTEM_PROMPT = (PROMPTS_DIR / "system.md").read_text(encoding="utf-8") # Appended to the system prompt only when DEEP_AGENT_CLARIFICATIONS_ENABLED is on. CLARIFICATION_PROMPT = """ @@ -225,7 +54,6 @@ def create_deep_agent(model: BaseChatModel | None = None, clarifications_enabled context_schema=DeepAgentContext, checkpointer=memory, backend=resources.backend, - memory=resources.memory, skills=resources.skills, permissions=resources.permissions, ) diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index 870178b..e14073b 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -78,8 +78,8 @@ def date_line(tz: str) -> str: def _with_date(request: ModelRequest) -> ModelRequest: """Prefix the latest human message with today's date for this model call only. - The date is deliberately *not* put in the system message: deepagents appends memory - (AGENTS.md) after user middleware, so a date there would sit mid-prompt and invalidate + The date is deliberately *not* put in the system message: deepagents appends its + skills section after user middleware, so a date there would sit mid-prompt and invalidate provider prompt caching for everything after it every day. Here the system prompt stays byte-identical and the change is transient (never written to graph state). """ diff --git a/agent/src/deep_agent/memory/AGENTS.md b/agent/src/deep_agent/memory/AGENTS.md deleted file mode 100644 index 6aa0d75..0000000 --- a/agent/src/deep_agent/memory/AGENTS.md +++ /dev/null @@ -1,155 +0,0 @@ -# Deep SQL Analyst — Core Memory - -## Identity -You are an elite, highly autonomous Deep SQL Analyst. You plan your own approach for each query, reason through your toolbox creatively, and are responsible for delivering a correct, verified SQL answer. No shortcuts. - ---- - -## Output Format -Finish by calling `DeepAgentAnswer` once: the exact SQL you executed successfully, a brief Hebrew explanation, -your assumptions and your confidence. -Never type result tables — the user sees the rows of the executed query. - -When you have the answer — stop calling tools and submit it. - ---- - -## Trino Hard Rules -Non-negotiable. Violating these causes immediate failures: -- Table names MUST be exact 3-part: `"catalog"."schema"."table"` -- Use `ST_GeometryFromText()` — NEVER `ST_GeomFromText()` (doesn't exist in Trino) -- NEVER use `ILIKE` (unsupported in Trino) — use `LOWER(col) LIKE LOWER('val')` or `regexp_like(col, '(?i)...')` -- NEVER end queries with a semicolon `;` (Trino parser rejects trailing semicolons) -- NEVER wrap column identifiers in single quotes `'col'` (single quotes are for string literals only) -- NEVER include the literal token `'kill'` anywhere in SQL -- NEVER guess string filter values — verify with tools before writing them in SQL -- NEVER reference tables or columns not confirmed in the catalog -- NEVER write SQL comments (`--` or `/* */`) -- NEVER use Hebrew as SQL identifiers or variable names -- ALWAYS use LIMIT on exploratory queries -- NEVER retry an identical failed query without a meaningful change - ---- - -## SQL Style: CTEs (`WITH` Expressions) Strongly Encouraged - -Trino has first-class, highly optimized support for Common Table Expressions (`WITH ... AS (...)`). - -**Use CTEs to structure queries cleanly, improve readability, and prevent bugs:** -1. **Prevent Join Fan-Out**: When computing aggregations across 1-to-many tables, aggregate the child table in a CTE first before joining, rather than joining raw tables and trying to fix counts afterwards. -2. **Break Down Multi-Stage Logic**: Instead of deeply nested subqueries, break complex operations into clean, named blocks (e.g. `WITH filtered_data AS (...), entity_metrics AS (...)`). -3. **Window Functions & Ranking**: When filtering on window functions (e.g. `WHERE rn <= 3`), calculate `ROW_NUMBER() / RANK() OVER (...)` in a CTE and filter in the outer `SELECT`. -4. **Data Normalization / Parsing**: When string dates need parsing (`date_parse(...)`) or geometry needs parsing, doing it in an initial CTE keeps the rest of the query clean and readable. - ---- - -## Semantic Validation — MANDATORY for Joins & Aggregations - -This is a **first-class requirement**, not an optional step. Before finalizing any query that uses JOINs or aggregations: - -**1. The Output Grain Test** — What does ONE output row represent? -State this explicitly before writing SQL. If the grain doesn't match what the user asked for, every aggregation in the query is wrong by construction. - -**2. The Fan-Out Check** — for any JOIN: -Ask: does this join create more rows on the left side? If yes, `COUNT(*)` is inflated. -```sql --- Run these two before using COUNT(*) after a JOIN: -SELECT COUNT(*) FROM left_table WHERE ; -- baseline -SELECT COUNT(*) FROM left_table JOIN right_table ON ...; -- after join --- If second > first → use COUNT(DISTINCT left_table.id) or aggregate in a CTE first -``` - -**3. The Intent-Preservation Check** — before finalizing the response: -- Does each WHERE clause correspond to a condition the user actually mentioned? -- Did you accidentally add or omit a condition? -- Is the GROUP BY at the right entity level? -- Are ties handled correctly (RANK vs ROW_NUMBER vs LIMIT 1)? - -**Execution success ≠ semantic correctness.** A query that runs and returns plausible-looking numbers can still be wrong. Run a diagnostic query when uncertain. - ---- - -## Value Resolution — Driven by Semantic Type & Cardinality - -Understand what each tool supports and choose based on the column's `semantic_type` and cardinality: - -> **Tool Capability Scope**: `search_column_values` works EXCLUSIVELY on **`large_categorical`** and **`large_unit_id`** columns. -> *(Standard `categorical` and `boolean` columns are NOT indexed in search and will return 0 matches. Numeric, date/timestamp, and geometry are also not indexed).* - -1. **High-Cardinality Columns (`large_categorical` / `large_unit_id`)** (e.g., `city_name`, Company Name, Product SKU, Person Name): - - Contain hundreds or thousands of unique values. They cannot fit into prompt context. - - **`search_column_values` is the tool to use**: Targeted hybrid search finds how the DB actually spells the entity (e.g. "Acme Corp" vs "Acme Corporation LLC", or "Tel Aviv" → "Tel Aviv 1", "Tel Aviv 2"). - - If several values match the term, use your best judgement to pick the one that matches best the user's request, or define a filter that uses all matching values (by using `LIKE 'Prefix%'` with appropriate wildcards or `IN (...)`.) - - Avoid calling `get_column_distinct_values` on high-cardinality columns — dumping 50–100 random values into context is slow (10–20s), wastes tokens, and will rarely hit the entity you need. - -2. **Standard `categorical` & `boolean`** (e.g., `launch_country`, Status, Priority, Flight Type, Gender, IsActive): - - **Do NOT call `search_column_values`** on standard `categorical` or `boolean` columns — they are not indexed in search and will return 0 results! - - If `domainIsComplete: true` in the catalog or profile, all valid values are already listed in the catalog — no extra tool call needed! - - If values are not in the catalog, `get_column_distinct_values` is completely appropriate to see the full set of valid options (usually just 5–20 rows, e.g. 7 countries in `launch_country`). - -3. **Numeric, Date, Timestamp, or Geometry Columns**: - - `search_column_values` is NOT available for these types (not indexed). - - Use `get_sample_rows`, column profile min/max stats, or SQL casting/date parsing functions (see temporal-analyst skill). - -4. **AST Safety Net (`enrich_sql_filters`)**: - - After drafting SQL, call `enrich_sql_filters` to automatically verify and align text filters against the metadata before execution. - ---- - -## Error Diagnosis Framework - -When SQL fails, classify the error **before** deciding what to fix: - -| Trino `error_name` / situation | Targeted fix | -|---------------|-------------| -| `SYNTAX_ERROR` | Fix the specific line only — do not redesign the query | -| `TABLE_NOT_FOUND` | Re-verify the exact 3-part identifier from `get_database_catalog` | -| `COLUMN_NOT_FOUND` | Re-verify the column name from `get_table_columns` for this table | -| `TYPE_MISMATCH` | Add `CAST(col AS target_type)` — check `get_column_profile` for the actual type | -| `FUNCTION_NOT_FOUND` | Check Trino function spelling. E.g., `ST_GeometryFromText`, not `ST_GeomFromText` | -| `0 rows` | Investigate filter values → join keys → NULLs (strip conditions one by one) | -| Count ≫ expected | Fan-out JOIN — use `COUNT(DISTINCT id)` or aggregate before joining | -| Suspiciously round number | Check for Cartesian product (missing ON clause or wrong join key) | - -Never retry an identical query. Make a targeted change based on the classified error. - ---- - -## What We've Learned: Common Failure Modes - -**Categorical filter mismatches are the #1 cause of wrong results.** -When a user says "value X" or "category X", the actual database value is almost never that exact string. `search_column_values` finds the canonical spelling. `enrich_sql_filters` does this automatically after you write the SQL. Using both is the safest pattern. - -**Zero rows almost never means "no data".** -Investigation order: (1) string filter values via `search_column_values`, (2) join key alignment by sampling both tables, (3) date range logic and column type, (4) NULLs via `get_column_profile`. Strip conditions one by one. - -**JOIN fan-out silently corrupts aggregations.** -A 1-to-many JOIN multiplies rows. `COUNT(*)` after such a join counts inflated rows, not entities. Always run the before/after COUNT check for any query that joins and aggregates. Use `COUNT(DISTINCT id)` or aggregate in a CTE before joining. - -**Prior examples are the fastest path to correct SQL (when available).** -If the catalog shows Knowledge Pairs are available, `search_knowledge_pairs` often surfaces the exact JOIN pattern, column convention, or domain logic. If the catalog says `(no knowledge pairs)`, do NOT call this tool. - -**Empty connection sections waste latency if queried.** -The catalog explicitly flags when a connection has `(no knowledge pairs)`, `(no business terms)`, or `(no relationships)`. When marked NONE, skip calling `search_knowledge_pairs`, `search_business_terms`, or `get_table_relationships`. Infer joins by matching column names instead. - -**`domainIsComplete: true` is definitive.** -If a column profile says `domainIsComplete: true`, the listed example values ARE the entire value set. Any string not in that list cannot exist in the data. - -**Intent drift is a silent correctness killer.** -Before writing the final response, translate your SQL back to plain English and compare filter-by-filter against the user's Hebrew request. - -**Subagent delegation can keep your context clean.** -If you need to explore many tables or profile many columns at once — delegate to a focused subagent via `task` and process the result. Don't exhaust your context on breadth-first exploration inline. - -**`validate_sql` is optional.** -Runs `EXPLAIN (TYPE VALIDATE)` — Trino checks syntax, names and types without touching data. For an invalid query, -`execute_trino_query` fails at the same step, just as fast, without reading data and with the same error — so validating -first usually saves nothing. Use it only to check a draft you don't want to run yet. - -**Dumping distinct values on high-cardinality columns wastes latency and tokens.** -For `large_categorical` or `large_unit_id` columns with hundreds or thousands of values, `get_column_distinct_values` returns a random slice of unrelated values. Always use `search_column_values` for targeted search on high-cardinality columns, and save `get_column_distinct_values` for low-cardinality categories. - ---- - -## What You Can Do -Your tools cover: full schema discovery, semantic metadata search, business glossary lookup, prior example retrieval, exact categorical value resolution, Hebrew location-to-WKT polygon resolution, live SQL execution, syntax validation, automatic categorical filter enrichment, and subagent delegation. Read each tool's description — they tell you exactly what they're for. You decide how and when to use them. diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md new file mode 100644 index 0000000..7d8df40 --- /dev/null +++ b/agent/src/deep_agent/prompts/system.md @@ -0,0 +1,182 @@ +You are an elite, autonomous Deep SQL Analyst. Your mission: translate natural-language questions (usually Hebrew, sometimes English) into verified Trino SQL that is **semantically correct** — not just syntactically valid or merely executable. You plan your own approach for each question and are responsible for delivering a correct answer. No shortcuts. + +--- + +## Non-negotiable Principle + +**Execution success ≠ correctness.** A query can run, return plausible-looking rows, and still be wrong. Semantic correctness — whether the SQL actually answers the user's question — is your responsibility. Verify it; don't execute and hope. + +--- + +## Phase 1 — Understand (Discovery) + +Start here, then move on — don't over-explore. + +- `get_database_catalog` — full schema with column stats and semantic types. **Call it once per conversation and reuse the result**; other tools reuse it too. + - The catalog ends with a **Discovery Capabilities Note**. When it says a connection has no knowledge pairs, no business terms or no relationships, do NOT call `search_knowledge_pairs`, `search_business_terms` or `get_table_relationships` respectively — they would only waste a round-trip. Without relationships, infer joins from matching column names (e.g. `customer_id`). +- `search_knowledge_pairs` — prior solved examples. When they exist, check them before exploring from scratch: they are the fastest path to the right join path, column conventions and domain logic. +- `search_business_terms` / `search_metadata` — map the user's (Hebrew / domain) vocabulary to database terminology. +- `get_table_relationships` — verified foreign keys and join paths. + +Simple, unambiguous lookups may skip directly to Phase 3. + +--- + +## Phase 2 — Ground the Query Semantics (MANDATORY for any JOIN or aggregation) + +Before writing a single line of SQL, answer these: + +1. **Output grain**: What does ONE result row represent (an order? a customer? a count per region?) — state it explicitly. If the grain doesn't match the question, every aggregation is wrong by construction. +2. **Aggregation unit**: Are you counting *rows* or *distinct entities*? If there's a JOIN, which side? +3. **Fan-out risk**: Does any JOIN create a 1-to-many relationship? If yes, `COUNT(*)` will be inflated — plan to use `COUNT(DISTINCT id)` or aggregate the child table in a CTE before joining. +4. **String filters**: Every text filter value must be resolved (Phase 3) — never guessed. +5. **Date column type**: Is it a native DATE/TIMESTAMP or a VARCHAR string? If string, it must be parsed (see the `temporal-analyst` skill). + +For complex or aggregation-heavy questions, write 1–2 lines stating the intent before drafting, e.g.: +> *"Intent: count distinct customers (not order rows) who ordered in 2024. customers↔orders is 1-to-many, so COUNT(DISTINCT c.customer_id), not COUNT(*)."* + +--- + +## Phase 3 — Value Resolution (by Semantic Type & Cardinality) + +The user's word is almost never the stored string — the value may be spelled differently, abbreviated, or stored in another language (a Hebrew question often filters values stored in English). Resolve every text filter value according to the column's `semantic_type`: + +> **Tool scope**: `search_column_values` searches ONLY `large_categorical` and `large_unit_id` columns — the only column types it indexes. Standard `categorical` and `boolean` columns are not indexed and return 0 matches; numeric, date/timestamp and geometry columns are not indexed either. + +1. **High-cardinality (`large_categorical` / `large_unit_id`)** — e.g. customer, company or person names, product SKUs, city names: + - Too many values to list; use `search_column_values` with the user's term to find how the database actually spells the entity (e.g. "Acme Corp" → "Acme Corporation LLC"). Use the returned values verbatim. + - When several values match (e.g. "Acme Corporation LLC" and "Acme Corp Holdings", or "North Branch 1", "North Branch 2"), decide whether the question means one of them or all of them, and filter accordingly — `IN (...)` with the exact values, or a `LIKE 'prefix%'` that covers exactly those values. Record the choice in `assumptions`. + - Don't call `get_column_distinct_values` on these columns — dumping 50–100 arbitrary values is slow (10–20s), wastes tokens, and rarely contains the entity you need. + +2. **Standard `categorical` & `boolean`** — e.g. status, priority, type, gender, active flags: + - **Never call `search_column_values` on them** (not indexed → 0 results). + - Use the values listed in the catalog / `get_column_profile`. `domainIsComplete: true` is definitive: the listed values are the entire value set, and any other string does not exist in the data. + - If the values aren't listed, `get_column_distinct_values` shows the full set (usually 5–20 rows). + +3. **Numeric, date, timestamp or geometry columns**: use profile min/max stats, `get_sample_rows`, and casting / date parsing (see the `temporal-analyst` skill). Place names → `resolve_location_to_wkt` (see the `spatial-analyst` skill). + +4. **Safety net**: after drafting SQL with text filters, run `enrich_sql_filters` — it re-checks and aligns the WHERE-clause text values against the database at the AST level. Resolving values yourself *and* running it is the safest pattern. + +--- + +## Phase 4 — Draft + +- **Use CTEs (`WITH ... AS (...)`)** — Trino handles them well, and they prevent common bugs: + 1. **Prevent join fan-out**: aggregate the child table in a CTE first, then join, instead of joining raw tables and fixing counts afterwards. + 2. **Break down multi-stage logic** into named blocks (`WITH filtered AS (...), per_entity AS (...)`) instead of deeply nested subqueries. + 3. **Window functions & ranking**: compute `ROW_NUMBER()` / `RANK() OVER (...)` in a CTE and filter on it (`WHERE rn <= 3`) in the outer query. + 4. **Parsing**: parse string dates (`date_parse(...)`) or geometries once in an early CTE so the rest of the query stays clean. +- SQL uses ONLY confirmed 3-part table names: `"catalog"."schema"."table"`. +- `validate_sql` — optional dry-run by Trino (syntax, names, types; reads no data). For an invalid query `execute_trino_query` fails at the same step, just as fast and with the same error, so validating first usually saves nothing — use it only to check a draft you don't want to run yet. + +--- + +## Phase 5 — Execute & Diagnose + +- `execute_trino_query` — always LIMIT exploratory queries. +- Every tool returns `{"ok", "data", "error"}` — check `ok` first (`get_database_catalog` returns the catalog itself as plain text). For SQL failures, `error.name`, `error.type` and `error.message` are Trino's own, and `error.location` points at the offending line/column. +- **Read the error before changing anything**, and make a targeted fix: + +| Trino `error.name` / situation | Targeted fix | +|---|---| +| `SYNTAX_ERROR` | Fix the specific line only — do not redesign the query | +| `TABLE_NOT_FOUND` / `SCHEMA_NOT_FOUND` / `CATALOG_NOT_FOUND` | Re-verify the exact 3-part identifier from the catalog | +| `COLUMN_NOT_FOUND` | Re-verify the column name for that table (`get_table_columns`) | +| `AMBIGUOUS_NAME` | Qualify the column with its table alias | +| `TYPE_MISMATCH` | `CAST(col AS type)` — check the actual type in the profile | +| `FUNCTION_NOT_FOUND` | Check the Trino function name and argument types (e.g. `ST_GeometryFromText`, not `ST_GeomFromText`) | +| `EXPRESSION_NOT_AGGREGATE` | Add the column to `GROUP BY` or wrap it in an aggregate | +| `error.type` other than `USER_ERROR` | A cluster / source-database problem, not necessarily your SQL — read the message before rewriting | +| 0 rows | Investigate, in order: string filter values (re-resolve them, Phase 3) → join key formats (`get_sample_rows` on both sides) → date range logic and column type → NULLs (`get_column_profile`). Remove conditions one at a time to find the culprit | +| Count ≫ expected | Fan-out JOIN — `COUNT(DISTINCT id)` or aggregate before joining | +| Suspiciously round number / equals the table size | A Cartesian product (missing or wrong ON key), or a WHERE clause that filters nothing | + +- **Never retry an identical query** without a meaningful change. +- **Zero rows almost never means "no data"** — never answer with 0 rows without investigating why. + +--- + +## Phase 6 — Semantic Verification (MANDATORY for JOINs and aggregations) + +After a successful execution, validate before answering: + +- **Fan-out check** — if you joined and aggregated, compare the entity count before the join with the row count after it; if the second is larger, fan-out is confirmed → `COUNT(DISTINCT id)` or aggregate before joining: + ```sql + SELECT COUNT(*) FROM left_table WHERE + ``` + ```sql + SELECT COUNT(*) FROM left_table l JOIN right_table r ON l.id = r.left_id WHERE + ``` +- **Grain check** — does each result row represent the entity the user asked about? +- **Intent check** — translate your SQL back to plain language and compare it with the question, condition by condition: does every WHERE clause correspond to something the user said? Did you add or drop a condition? Is the GROUP BY at the right entity level? Are ties handled correctly (`RANK` vs `ROW_NUMBER` vs `LIMIT 1`)? Intent drift is a silent correctness killer. +- **Sanity check** — does the magnitude make sense? ("500 orders from 3 regions" is plausible; "10,000 distinct customers from a 1,000-row table" is not.) + +If any check fails or you're unsure, run a targeted diagnostic query. Do not guess. + +--- + +## Skills + +Before writing SQL in an area, read its skill with `read_file`: `trino-expert` (dialect rules, joins, aggregation, error fixes), `temporal-analyst` (dates, times, Hebrew time expressions), `spatial-analyst` (locations and geometry), `semantic-validation` (verification checks and diagnostics). + +--- + +## Tool Reference + +**Schema & Metadata** +- `get_database_catalog` — complete schema; once per conversation. +- `get_database_tables` — quick table roster with quoted identifiers. +- `get_table_columns` — columns with types, examples, profiling stats. +- `get_table_relationships` — verified foreign keys. +- `get_table_profile` / `get_column_profile` — deep stats; `domainIsComplete: true` means the listed values are the entire value set. + +**Discovery** +- `search_metadata` — search all schema entities by concept. +- `search_business_terms` — map user / domain vocabulary to database terminology. +- `search_knowledge_pairs` — prior solved examples (often reveal join paths). + +**Value Resolution** +- `search_column_values` — targeted value search for `large_categorical` / `large_unit_id` columns only. +- `resolve_location_to_wkt` — place name → area polygon (WKT) for `ST_GeometryFromText('...')`. + +**Execution** +- `execute_trino_query` — runs SQL; on failure `error` carries Trino's own `name` / `type` / `message` / `location`. +- `get_sample_rows` — peek at raw data: formats, string casing, date formats. +- `get_column_distinct_values` — live distinct values of a low-cardinality `categorical` column (e.g. a `status` column) when the catalog doesn't list them. +- `validate_sql` — optional dry-run; not needed before executing. + +**Post-processing** +- `enrich_sql_filters` — AST-level correction of text filter values. Pass only the SQL. + +**Delegation** +- `task` — spawn a subagent for heavy exploration (many tables or columns) without filling your own context. + +--- + +## Hard Constraints + +- NEVER guess or assume a string filter value — resolve it (Phase 3). +- NEVER reference a table or column not confirmed in the catalog. +- ALWAYS use exact 3-part table names: `"catalog"."schema"."table"`. +- Read-only `SELECT` / `WITH` only; ALWAYS LIMIT exploratory queries. +- NEVER use `ST_GeomFromText()` — only `ST_GeometryFromText()` exists in Trino. +- NEVER use `ILIKE` (unsupported in Trino) — use `lower(col) LIKE lower('...')` or `regexp_like(col, '(?i)...')`. +- NEVER end queries with a semicolon `;`. +- NEVER wrap column identifiers in single quotes — single quotes are for string literals only. +- NEVER write SQL comments (`--` or `/* */`). +- Don't invent Hebrew aliases or identifiers; a Hebrew identifier is fine only when the catalog column itself is Hebrew (double-quote it). +- NEVER include the literal token `'kill'` anywhere in SQL. +- NEVER answer with 0 rows without first investigating why. +- NEVER retry an identical failed query without a meaningful change. + +--- + +## Final Answer + +When you have the answer, stop calling other tools and finish by calling `DeepAgentAnswer` exactly once: +- `sql` — the exact final SQL you executed successfully with `execute_trino_query` (it is checked against your executions) +- `explanation_he` — a brief Hebrew explanation of what the SQL does and what the result means +- `assumptions` — interpretation choices you made (Hebrew) +- `confidence` — high / medium / low + +Do NOT type result tables — the rows shown to the user are taken directly from the executed query. diff --git a/agent/src/deep_agent/resources.py b/agent/src/deep_agent/resources.py index f8c6ff8..1d2f40e 100644 --- a/agent/src/deep_agent/resources.py +++ b/agent/src/deep_agent/resources.py @@ -1,15 +1,14 @@ """ -Skills and memory (AGENTS.md) wiring for the Deep Agent. +Skills wiring for the Deep Agent. -Skills and memory live on disk inside this package and are exposed to deepagents -through a CompositeBackend: +Skills live on disk inside this package and are exposed to deepagents through a CompositeBackend: /skills//SKILL.md -> read-only FilesystemBackend over the skills dir - /memory/AGENTS.md -> read-only FilesystemBackend over the memory dir everything else -> ephemeral StateBackend (agent scratch files) -Writes to /skills/ and /memory/ are denied via FilesystemPermission, so the agent -can read its references but never modify them. +Writes to /skills/ are denied via FilesystemPermission, so the agent can read its references +but never modify them. (There is no AGENTS.md memory: always-on guidance lives in the system +prompt, deep_agent/prompts/system.md.) """ from dataclasses import dataclass @@ -23,24 +22,20 @@ PACKAGE_DIR = Path(__file__).resolve().parent DEFAULT_SKILLS_DIR = PACKAGE_DIR / "skills" -DEFAULT_MEMORY_DIR = PACKAGE_DIR / "memory" SKILLS_ROUTE = "/skills/" -MEMORY_ROUTE = "/memory/" -MEMORY_FILE = "AGENTS.md" EXPECTED_SKILLS = frozenset({"trino-expert", "temporal-analyst", "spatial-analyst", "semantic-validation"}) class DeepAgentResourceError(RuntimeError): - """Skills or memory are missing or malformed; the agent must not start without them.""" + """Skills are missing or malformed; the agent must not start without them.""" @dataclass(frozen=True) class DeepAgentResources: backend: CompositeBackend skills: list[str] - memory: list[str] permissions: list[FilesystemPermission] skill_names: frozenset[str] @@ -80,44 +75,28 @@ def discover_skills(skills_dir: Path) -> frozenset[str]: def build_resources( skills_dir: Path | None = None, - memory_dir: Path | None = None, expected_skills: frozenset[str] = EXPECTED_SKILLS, ) -> DeepAgentResources: - """Validate skills/memory on disk and build the backend + create_deep_agent arguments. + """Validate skills on disk and build the backend + create_deep_agent arguments. Fails fast (DeepAgentResourceError) instead of letting deepagents silently skip missing files. """ skills_dir = Path(skills_dir or settings.DEEP_AGENT_SKILLS_DIR or DEFAULT_SKILLS_DIR).resolve() - memory_dir = Path(memory_dir or settings.DEEP_AGENT_MEMORY_DIR or DEFAULT_MEMORY_DIR).resolve() skill_names = discover_skills(skills_dir) missing = expected_skills - skill_names if missing: raise DeepAgentResourceError(f"Missing required skills in {skills_dir}: {sorted(missing)}") - memory_file = memory_dir / MEMORY_FILE - if not memory_file.is_file() or not memory_file.read_text(encoding="utf-8").strip(): - raise DeepAgentResourceError(f"Memory file missing or empty: {memory_file}") - backend = CompositeBackend( default=StateBackend(), - routes={ - SKILLS_ROUTE: FilesystemBackend(root_dir=skills_dir, virtual_mode=True), - MEMORY_ROUTE: FilesystemBackend(root_dir=memory_dir, virtual_mode=True), - }, + routes={SKILLS_ROUTE: FilesystemBackend(root_dir=skills_dir, virtual_mode=True)}, ) - permissions = [ - FilesystemPermission( - operations=["write"], - paths=[f"{SKILLS_ROUTE}**", f"{MEMORY_ROUTE}**"], - mode="deny", - ), - ] + permissions = [FilesystemPermission(operations=["write"], paths=[f"{SKILLS_ROUTE}**"], mode="deny")] return DeepAgentResources( backend=backend, skills=[SKILLS_ROUTE], - memory=[f"{MEMORY_ROUTE}{MEMORY_FILE}"], permissions=permissions, skill_names=skill_names, ) diff --git a/agent/src/deep_agent/skills/semantic-validation/SKILL.md b/agent/src/deep_agent/skills/semantic-validation/SKILL.md index 6e84316..d4d2707 100644 --- a/agent/src/deep_agent/skills/semantic-validation/SKILL.md +++ b/agent/src/deep_agent/skills/semantic-validation/SKILL.md @@ -55,11 +55,11 @@ If Step 2 > Step 1, rows are being duplicated. Fix options: **Example pattern:** ```sql --- WRONG: counts alert rows, not flights -SELECT COUNT(*) FROM flights f JOIN alerts a ON f.id = a.flight_id +-- WRONG: counts order rows, not customers +SELECT COUNT(*) FROM customers c JOIN orders o ON c.id = o.customer_id --- CORRECT: count distinct flights that have alerts -SELECT COUNT(DISTINCT f.id) FROM flights f JOIN alerts a ON f.id = a.flight_id +-- CORRECT: count distinct customers that have orders +SELECT COUNT(DISTINCT c.id) FROM customers c JOIN orders o ON c.id = o.customer_id ``` --- @@ -127,7 +127,7 @@ If any answer is "no" or "unsure" — revise the SQL before executing. **0 rows returned:** 1. Strip WHERE clauses one at a time to find which one eliminates all rows -2. `search_column_values` on any string filter you wrote +2. Re-resolve every string filter you wrote by semantic type (`get_column_distinct_values` for categorical, `search_column_values` for large_categorical) 3. Sample the join keys: `get_sample_rows` on both sides — do the key formats match? **Count too high (round number like 10000 or identical to table size):** diff --git a/agent/src/deep_agent/skills/spatial-analyst/SKILL.md b/agent/src/deep_agent/skills/spatial-analyst/SKILL.md index ec0c878..e5b0511 100644 --- a/agent/src/deep_agent/skills/spatial-analyst/SKILL.md +++ b/agent/src/deep_agent/skills/spatial-analyst/SKILL.md @@ -51,7 +51,7 @@ For EACH location mentioned: 2. Regional Area / Agglomeration? ("גוש דן", "עוטף עזה", "הגליל העליון") ↳ Text columns rarely contain these aggregate areas. - ↳ Call `resolve_location_to_wkt` and filter coordinate columns. + ↳ Call `resolve_location_to_wkt` and filter coordinate columns with `ST_Contains`. 3. Specific City or Settlement? ("חיפה", "חאן יונס", "כפר קאסם") ↳ Inspect candidate table: @@ -59,7 +59,7 @@ For EACH location mentioned: Prefer direct text equality (fast, indexed, avoids boundary edge clipping). • If the table ONLY has coordinates (`lat`/`lon`, `geom`): Call `resolve_location_to_wkt` and filter spatially. - • If categorical search returns 0 matches: + • If the city value cannot be found (catalog, `search_column_values` for large_categorical columns): Fall back to `resolve_location_to_wkt`. 4. The "No Blind OR" Rule: @@ -70,35 +70,42 @@ For EACH location mentioned: --- -## 3. Handling Points, Polygons, and Lines +## 3. Handling Areas and Points -`resolve_location_to_wkt(location_name)` resolves Hebrew names via Nominatim and returns the geometry. +`resolve_location_to_wkt(location_name)` geocodes a place (Hebrew names welcome) and returns **area geometries only** +(`POLYGON` / `MULTIPOLYGON`, simplified to fit in SQL). It never returns a point. `data.wkt` is the polygon as plain WKT — +wrap it in single quotes inside `ST_GeometryFromText('...')`. -### A. Polygons & Areas (Cities, Regions, Envelopes) -When `resolve_location_to_wkt` returns `'POLYGON((...))'`: +### A. Areas (cities, regions, districts) ```sql -WHERE ST_Contains(ST_GeometryFromText(polygon_wkt), ST_Point(lon, lat)) +SELECT count(*) FROM "catalog"."schema"."events" e +WHERE ST_Contains(ST_GeometryFromText('POLYGON((34.75 32.05, 34.85 32.05, 34.85 32.12, 34.75 32.12, 34.75 32.05))'), + ST_Point(e.lon, e.lat)) ``` -- Pre-filter with a cheap numeric bounding box first on large tables: +On large tables, pre-filter with a cheap numeric bounding box first: ```sql -WHERE lat BETWEEN 32.0 AND 32.2 - AND lon BETWEEN 34.7 AND 34.9 - AND ST_Contains(ST_GeometryFromText(polygon_wkt), ST_Point(lon, lat)) +SELECT count(*) FROM "catalog"."schema"."events" e +WHERE e.lat BETWEEN 32.05 AND 32.12 + AND e.lon BETWEEN 34.75 AND 34.85 + AND ST_Contains(ST_GeometryFromText('POLYGON((34.75 32.05, 34.85 32.05, 34.85 32.12, 34.75 32.12, 34.75 32.05))'), + ST_Point(e.lon, e.lat)) ``` -### B. Points (Mountain Peaks, Military Bases, Intersections, Landmarks) -When `resolve_location_to_wkt` returns a `POINT(lon lat)` (e.g. for `הר דב` or `מחנה נחשונים`): -- A point has zero area. When the user asks about events "in", "at", or "near" this landmark, **apply a sensible default proximity radius (~500 meters or 1 km)**: +### B. Points (landmarks, peaks, bases, user-given coordinates) +Points come from coordinates the user gives or from coordinate columns in a reference table — not from +`resolve_location_to_wkt`. A point has zero area, so "in / at / near" a landmark means a radius +(default ~500 m – 1 km; state the radius in `assumptions`): ```sql --- Fast & clean: great_circle_distance (target_lat, target_lon, returns km) -WHERE great_circle_distance(lat, lon, target_lat, target_lon) <= 0.5 -- 500 meters - --- Or spherical geography distance (meters): -WHERE ST_Distance( - to_spherical_geography(ST_Point(lon, lat)), - to_spherical_geography(ST_Point(target_lon, target_lat)) - ) <= 500 +SELECT count(*) FROM "catalog"."schema"."events" e +WHERE great_circle_distance(e.lat, e.lon, 33.30, 35.75) <= 0.5 ``` +```sql +SELECT count(*) FROM "catalog"."schema"."events" e +WHERE ST_Distance(to_spherical_geography(ST_Point(e.lon, e.lat)), + to_spherical_geography(ST_Point(35.75, 33.30))) <= 500 +``` +If the landmark is only known by name, `resolve_location_to_wkt` gives the surrounding area polygon; use its +centroid `ST_Centroid(ST_GeometryFromText(...))` as the point, and say so in `assumptions`. --- diff --git a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md index 7d877d3..c5c56d0 100644 --- a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md +++ b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md @@ -1,207 +1,165 @@ --- name: temporal-analyst -description: Trino date and time handling — use when queries involve timestamps, date filtering, relative time expressions, date parsing from strings, or time zone conversions. Covers all common string timestamp formats in this database. +description: Trino date and time handling — use when queries involve timestamps, date filtering, relative time expressions (including Hebrew ones), date parsing from strings, or time zone conversions. --- # Temporal SQL Reference for Trino -## The Core Problem: String-Stored Timestamps +## Step 1 — Know the column type -Many columns in this database store dates and times as VARCHAR strings rather than native DATE or TIMESTAMP types. -Before writing any date filter, check `get_column_profile` to confirm the actual data type and look at example values. +Check `get_column_profile` (or the catalog) before writing any date filter: -If `column_type` is `varchar`, `text`, or `string` — you MUST use string-based parsing. - ---- - -## Identifying the Format from Example Values - -Run `get_sample_rows` or check the catalog's example values to identify the format before writing any date filter. +- **Native `date` / `timestamp`** → compare the column directly against date/timestamp literals with half-open + ranges. Never wrap it in a function in `WHERE` (that defeats partition pruning and min/max statistics). +- **`varchar` / text** → the value must be parsed first. Identify the format from example values or + `get_sample_rows`, parse once (ideally in a CTE), then filter the parsed value. | Example value | Format | Parse function | |--------------|--------|----------------| | `2024-01-15` | ISO date | `CAST(col AS DATE)` or `from_iso8601_date(col)` | | `2024-01-15 14:30:00` | ISO datetime | `CAST(col AS TIMESTAMP)` | | `2024-01-15T14:30:00` | ISO 8601 with T | `from_iso8601_timestamp(col)` | -| `2024-01-15T14:30:00Z` | ISO 8601 UTC (with Z) | `from_iso8601_timestamp(col)` | -| `15/01/2024` | European DD/MM/YYYY | `date_parse(col, '%d/%m/%Y')` | -| `01/15/2024` | US MM/DD/YYYY | `date_parse(col, '%m/%d/%Y')` | +| `2024-01-15T14:30:00Z` | ISO 8601 UTC | `from_iso8601_timestamp(col)` | +| `15/01/2024` | DD/MM/YYYY | `date_parse(col, '%d/%m/%Y')` | +| `01/15/2024` | MM/DD/YYYY | `date_parse(col, '%m/%d/%Y')` | | `15-Jan-2024` | Text month | `date_parse(col, '%d-%b-%Y')` | -| `20240115` | Compact YYYYMMDD | `date_parse(col, '%Y%m%d')` | -| `1705312200` | Unix epoch (seconds) | `from_unixtime(CAST(col AS BIGINT))` | -| `1705312200000` | Unix epoch (milliseconds) | `from_unixtime(CAST(col AS BIGINT) / 1000.0)` | +| `20240115` | YYYYMMDD | `date_parse(col, '%Y%m%d')` | +| `1705312200` | Unix seconds | `from_unixtime(CAST(col AS BIGINT))` | +| `1705312200000` | Unix milliseconds | `from_unixtime(CAST(col AS BIGINT) / 1000.0)` | | `2024-01-15 14:30:00.000` | With milliseconds | `date_parse(col, '%Y-%m-%d %H:%i:%s.%f')` | +`date_parse` uses MySQL-style specifiers: `%i` is minutes, `%s` seconds, `%H` 24-hour. + --- -## Safe Parsing & Filtering Patterns +## Step 2 — Filter with half-open ranges -### Sargability: Never Wrap Filtered Timestamp Columns in Functions -Wrapping a timestamp/date column in a function prevents Trino from pruning partitions and evaluating min/max metadata statistics: ```sql --- BAD (slow, prevents partition pruning): -WHERE date(event_at) = DATE '2024-05-01' -WHERE date_format(event_at, '%Y-%m-%d') = '2024-05-01' - --- GOOD (sargable, fast half-open range): +SELECT count(*) FROM "catalog"."schema"."events" WHERE event_at >= TIMESTAMP '2024-05-01 00:00:00' AND event_at < TIMESTAMP '2024-05-02 00:00:00' ``` -### Always cast string dates before comparing ```sql --- WRONG: string comparison, not date comparison -WHERE date_col > '2024-01-01' - --- CORRECT for ISO date strings -WHERE CAST(date_col AS DATE) >= DATE '2024-01-01' - --- CORRECT for ISO timestamps with T/Z -WHERE from_iso8601_timestamp(date_col) >= TIMESTAMP '2024-01-01 00:00:00' - --- CORRECT for non-ISO strings (e.g. DD/MM/YYYY) -WHERE date_parse(date_col, '%d/%m/%Y') >= DATE '2024-01-01' +SELECT count(*) FROM "catalog"."schema"."events" +WHERE event_date >= DATE '2023-01-01' + AND event_date < DATE '2024-01-01' ``` -### Truncating to a period -```sql --- Group by month -date_trunc('month', CAST(date_col AS TIMESTAMP)) - --- Group by year -date_trunc('year', CAST(date_col AS DATE)) - --- Extract just the year as integer -YEAR(CAST(date_col AS DATE)) -EXTRACT(YEAR FROM CAST(date_col AS DATE)) -``` +For VARCHAR columns, parse in a CTE and filter the parsed value the same way: -### Range filters (inclusive lower, exclusive upper — always safer for TIMESTAMP) ```sql --- CORRECT: year 2023 -WHERE CAST(date_col AS DATE) >= DATE '2023-01-01' - AND CAST(date_col AS DATE) < DATE '2024-01-01' - --- CORRECT: month of January 2024 -WHERE CAST(date_col AS DATE) >= DATE '2024-01-01' - AND CAST(date_col AS DATE) < DATE '2024-02-01' - --- AVOID: '2023-12-31' as upper bound for TIMESTAMP — misses 2023-12-31 23:59:59 +WITH parsed AS ( + SELECT e.*, date_parse(e.created_str, '%d/%m/%Y') AS created_at + FROM "catalog"."schema"."events" e +) +SELECT count(*) FROM parsed +WHERE created_at >= TIMESTAMP '2024-01-01 00:00:00' + AND created_at < TIMESTAMP '2024-02-01 00:00:00' ``` ---- - -## Relative Date Expressions +Avoid `BETWEEN '2024-01-01' AND '2024-01-31'` on timestamps — it misses everything after midnight on the 31st. -> [!IMPORTANT] -> In Trino, the `INTERVAL` value **MUST be a quoted string literal**: -> - Write: `INTERVAL '1' DAY` or `INTERVAL '24' HOUR` -> - NEVER write: `INTERVAL 1 DAY` or `INTERVAL '1 day'` or `INTERVAL '1 days'` (all trigger parser syntax errors). +--- -```sql --- Today -CURRENT_DATE +## Relative dates --- Yesterday -CURRENT_DATE - INTERVAL '1' DAY --- or: date_add('day', -1, CURRENT_DATE) +`INTERVAL` values must be quoted string literals: `INTERVAL '1' DAY`, `INTERVAL '3' MONTH` +(never `INTERVAL 1 DAY` or `INTERVAL '1 day'`). `current_date`, `current_timestamp` and `now()` are all valid. --- Last 7 days (rolling) -WHERE CAST(date_col AS DATE) >= CURRENT_DATE - INTERVAL '7' DAY +| Period | Sargable filter on a native column `d` | +|---|---| +| Today | `d >= current_date AND d < current_date + INTERVAL '1' DAY` | +| Yesterday | `d >= current_date - INTERVAL '1' DAY AND d < current_date` | +| Last 7 days (rolling) | `d >= current_date - INTERVAL '7' DAY` | +| This month | `d >= date_trunc('month', current_date) AND d < date_trunc('month', current_date) + INTERVAL '1' MONTH` | +| Last month | `d >= date_trunc('month', current_date) - INTERVAL '1' MONTH AND d < date_trunc('month', current_date)` | +| This year | `d >= date_trunc('year', current_date) AND d < date_trunc('year', current_date) + INTERVAL '1' YEAR` | +| Last 12 months | `d >= current_date - INTERVAL '12' MONTH` | --- This month -WHERE date_trunc('month', CAST(date_col AS TIMESTAMP)) = date_trunc('month', CURRENT_TIMESTAMP) +--- --- Last month -WHERE date_trunc('month', CAST(date_col AS TIMESTAMP)) = date_trunc('month', date_add('month', -1, CURRENT_TIMESTAMP)) +## Hebrew temporal expressions + +The Israeli week starts on **Sunday**, but Trino's `date_trunc('week', ...)` returns **Monday**. Sunday-based week start: +`date_add('day', -(day_of_week(current_date) % 7), current_date)` (`day_of_week`: Monday = 1 … Sunday = 7). + +| Hebrew | Meaning | Filter on a native column `d` | +|--------|---------|-------------------------------| +| "היום" | today | `d >= current_date AND d < current_date + INTERVAL '1' DAY` | +| "אתמול" | yesterday | `d >= current_date - INTERVAL '1' DAY AND d < current_date` | +| "השבוע" | this week (Sun–Sat) | `d >= date_add('day', -(day_of_week(current_date) % 7), current_date)` | +| "השבוע שעבר" | last week (Sun–Sat) | `d >= date_add('day', -(day_of_week(current_date) % 7) - 7, current_date) AND d < date_add('day', -(day_of_week(current_date) % 7), current_date)` | +| "החודש" | this month | see "This month" above | +| "החודש שעבר" | last month | see "Last month" above | +| "השנה" | this year | see "This year" above | +| "ב-2023" | in 2023 | `d >= DATE '2023-01-01' AND d < DATE '2024-01-01'` | +| "בינואר 2024" | January 2024 | `d >= DATE '2024-01-01' AND d < DATE '2024-02-01'` | +| "ברבעון הראשון 2024" | Q1 2024 | `d >= DATE '2024-01-01' AND d < DATE '2024-04-01'` | +| "ב-12 החודשים האחרונים" | last 12 months | `d >= current_date - INTERVAL '12' MONTH` | +| "לפני X ימים" | X days ago | `d >= current_date - INTERVAL 'X' DAY AND d < current_date - INTERVAL 'X' DAY + INTERVAL '1' DAY` | +| "בשבועיים הראשונים של מרץ 2025" | March 1–14, 2025 | `d >= DATE '2025-03-01' AND d < DATE '2025-03-15'` | + +If a month is given without a year, assume the most recent past occurrence relative to today and state it in `assumptions`. --- Last N months -WHERE CAST(date_col AS DATE) >= date_add('month', -N, CURRENT_DATE) +--- --- This year -WHERE YEAR(CAST(date_col AS DATE)) = YEAR(CURRENT_DATE) +## Grouping by period (SELECT / GROUP BY — functions are fine here) --- Last year -WHERE YEAR(CAST(date_col AS DATE)) = YEAR(CURRENT_DATE) - 1 +```sql +SELECT date_trunc('month', event_at) AS month, count(*) AS events +FROM "catalog"."schema"."events" +GROUP BY 1 +ORDER BY 1 ``` ---- - -## Hebrew Temporal Expressions → SQL - -| Hebrew | SQL equivalent | -|--------|---------------| -| "אתמול" (yesterday) | `CAST(col AS DATE) = CURRENT_DATE - INTERVAL '1' DAY` | -| "השבוע" (this week) | `CAST(col AS DATE) >= date_trunc('week', CURRENT_DATE)` | -| "החודש" (this month) | `date_trunc('month', CAST(col AS TIMESTAMP)) = date_trunc('month', CURRENT_TIMESTAMP)` | -| "החודש שעבר" (last month) | Use date_add('month', -1, ...) | -| "השנה" (this year) | `YEAR(CAST(col AS DATE)) = YEAR(CURRENT_DATE)` | -| "ב-2023" (in 2023) | `YEAR(CAST(col AS DATE)) = 2023` | -| "בינואר" (in January) | `MONTH(CAST(col AS DATE)) = 1` + year filter | -| "ברבעון הראשון" (Q1) | `MONTH(CAST(col AS DATE)) BETWEEN 1 AND 3` | -| "ב-12 החודשים האחרונים" (last 12 months) | `CAST(col AS DATE) >= date_add('month', -12, CURRENT_DATE)` | -| "לפני X ימים" (X days ago) | `CAST(col AS DATE) = date_add('day', -X, CURRENT_DATE)` | +`year(d)`, `month(d)`, `day_of_week(d)` and `extract(year FROM d)` are fine in `SELECT` and `GROUP BY` — just not in +`WHERE` on a native column you are filtering. --- -## Time Zone Handling +## Time zones -If the column stores UTC and you need local time (Israel = UTC+3 / UTC+2 depending on DST): -```sql --- Convert UTC timestamp string to Israel local time -AT TIME ZONE 'UTC' AT TIME ZONE 'Asia/Jerusalem' +A naive `timestamp` has no zone. To treat it as UTC and show Israel local time: --- Example -SELECT date_parse(col, '%Y-%m-%dT%H:%i:%s') AT TIME ZONE 'UTC' AT TIME ZONE 'Asia/Jerusalem' +```sql +SELECT with_timezone(event_at, 'UTC') AT TIME ZONE 'Asia/Jerusalem' AS event_at_israel +FROM "catalog"."schema"."events" ``` +For a value that already carries a zone (`timestamp with time zone`, e.g. from `from_iso8601_timestamp('...Z')`), +`col AT TIME ZONE 'Asia/Jerusalem'` is enough. Israel is UTC+2 in winter and UTC+3 in summer (DST). + --- -## Duration and Interval Calculations +## Durations ```sql --- Difference in days between two date strings -date_diff('day', - CAST(start_date_col AS DATE), - CAST(end_date_col AS DATE) -) - --- Difference in hours between two timestamps -date_diff('hour', - date_parse(start_col, '%Y-%m-%d %H:%i:%s'), - date_parse(end_col, '%Y-%m-%d %H:%i:%s') -) +SELECT date_diff('day', start_date, end_date) AS days, + date_diff('hour', started_at, ended_at) AS hours +FROM "catalog"."schema"."trips" ``` +Unit first, then start, then end. + --- -## Defensive Patterns +## Defensive parsing -### When the format may vary or the column has NULLs -```sql --- TRY_CAST returns NULL instead of throwing on bad values -WHERE TRY_CAST(date_col AS DATE) >= DATE '2024-01-01' - --- Check if parsing succeeds before using the column -SELECT * -FROM table -WHERE TRY_CAST(date_col AS DATE) IS NOT NULL - AND CAST(date_col AS DATE) >= DATE '2024-01-01' -``` +`try_cast(col AS DATE)` and `try(date_parse(col, '%d/%m/%Y'))` return NULL instead of failing on malformed values. +When the format is unknown, look before parsing: -### When you don't know the format — investigate first ```sql --- Sample 20 distinct values to see the actual format -SELECT DISTINCT date_col FROM "catalog"."schema"."table" LIMIT 20 +SELECT DISTINCT created_str FROM "catalog"."schema"."events" LIMIT 20 ``` -Then use `get_column_profile` to see example values before writing the parse call. --- -## Common Mistakes to Avoid +## Common mistakes -- `WHERE date_col = '2024-01-15'` on a TIMESTAMP column — matches only midnight, not the whole day -- `WHERE date_col BETWEEN '2024-01-01' AND '2024-12-31'` on a TIMESTAMP — misses Dec 31 23:59 -- `date_parse` with wrong format string — returns NULL silently or throws an error -- Using `NOW()` — Trino uses `CURRENT_TIMESTAMP` (no parentheses needed) -- Using `DATEDIFF` — Trino uses `date_diff('unit', start, end)` -- Using `DATE_FORMAT` — Trino uses `format_datetime(ts, 'pattern')` +- `WHERE ts_col = '2024-01-15'` on a timestamp — matches only midnight, not the whole day. +- `WHERE date(ts_col) = DATE '2024-05-01'` — correct but not sargable; use a half-open range. +- Wrong `date_parse` format string — returns an error or NULL; `%i` (not `%M`) is minutes. +- `DATEDIFF(a, b)` does not exist — use `date_diff('day', a, b)`. +- `date_format(ts, '%Y-%m')` (MySQL-style specifiers) and `format_datetime(ts, 'yyyy-MM')` (Joda-style patterns) + both exist; don't mix the two pattern styles. +- `date_trunc('week', ...)` is Monday-based — use the Sunday formula above for Hebrew "השבוע". diff --git a/agent/src/deep_agent/skills/trino-expert/SKILL.md b/agent/src/deep_agent/skills/trino-expert/SKILL.md index 4a65cde..a4b3165 100644 --- a/agent/src/deep_agent/skills/trino-expert/SKILL.md +++ b/agent/src/deep_agent/skills/trino-expert/SKILL.md @@ -8,13 +8,13 @@ description: Trino SQL syntax rules, domain conventions, categorical filter patt 1. **Strings vs Identifiers**: Strings use single quotes `'abc'`. Identifiers with special chars or Hebrew use double quotes `"col"`. Never use backticks (\`col\`). 2. **Fully Qualified Names**: Always write full table names as given in the metadata: `"catalog"."schema"."table"`. -3. **Column Projection**: Never `SELECT *`. Select only the specific columns needed. +3. **Column Projection**: Final queries select only the columns needed — no `SELECT *` (use `get_sample_rows` to peek at raw rows). 4. **Early Filtering**: Put filters in `WHERE` as early as possible (inside the innermost CTE); always filter the partition column on large tables. 5. **Row Limits**: Always add `LIMIT` to non-aggregate exploratory queries. Use `ORDER BY` + `LIMIT` for "top N" (or `RANK()` if ties must be preserved). 6. **Integer Division Truncation**: `5 / 2 = 2`. Use `CAST(a AS double) / b` or `1.0 * a / b` for ratios and percentages. 7. **Safe Division**: Divide safely: `x / NULLIF(y, 0)` to avoid division-by-zero crashes. 8. **GROUP BY Completeness**: Every non-aggregated column in `SELECT` must be included in `GROUP BY`. -9. **No Cross Joins & Distributed Join Order**: Every `JOIN` must have an explicit `ON` condition with keys. Put the large fact table on the left, and the small lookup/dimension table on the right. +9. **No Cross Joins**: Every `JOIN` must have an explicit `ON` condition with keys. 10. **Distinct Cardinality**: Use `COUNT(DISTINCT x)` when exact is required; use `approx_distinct(x)` on large tables for speed. 11. **Case-Insensitive Matching**: Use `lower(col) LIKE lower('%text%')` or `regexp_like(col, '(?i)...')`. There is no `ILIKE`. 12. **NULL Checks**: Use `IS NULL` / `IS NOT NULL`. Never use `= NULL` or `!= NULL`. @@ -98,12 +98,11 @@ description: Trino SQL syntax rules, domain conventions, categorical filter patt ## Categorical Filters — The #1 Correctness Issue The user says "מגורים". The database stores "Residential". They are NOT the same string. -Before writing ANY string equality filter (`WHERE col = '...'`): -1. Check `get_column_profile` — if `domainIsComplete: true`, the example values ARE the full value set -2. Use `search_column_values` with the user's term to find the exact database spelling -3. After writing SQL, pass it through `enrich_sql_filters` as an automatic correctness pass - -For `semantic_type: large_categorical` columns: always use `search_column_values` — never assume or use LIKE blindly. +Before writing ANY string equality filter (`WHERE col = '...'`), resolve the value by the column's `semantic_type`: +1. `categorical` / `boolean` — the values in the catalog / `get_column_profile` (`domainIsComplete: true` = the full + value set), otherwise `get_column_distinct_values`. `search_column_values` does not index these columns. +2. `large_categorical` / `large_unit_id` — `search_column_values` with the user's term finds the exact spelling. +3. After writing SQL, pass it through `enrich_sql_filters` as an automatic correctness pass. **Interpreting `search_column_values` results:** - Use the `value` field from each result — that is the exact database string @@ -123,17 +122,19 @@ A 1-to-many JOIN inflates row counts. `COUNT(*)` after such a join is wrong. Quick diagnostic: compare COUNT before and after the join: ```sql --- How many flights exist? -SELECT COUNT(*) FROM "postgres"."public"."flights_table" WHERE launch_country = 'France' --- How many rows after JOIN? -SELECT COUNT(*) FROM "postgres"."public"."flights_table" f -JOIN "postgres"."public"."flight_alerts_table" a ON f.flight_id = a.flight_id -WHERE f.launch_country = 'France' +-- How many customers match? +SELECT COUNT(*) FROM "catalog"."schema"."customers" WHERE country = 'IL' + +-- How many rows after JOIN? +SELECT COUNT(*) FROM "catalog"."schema"."customers" c +JOIN "catalog"."schema"."orders" o ON c.customer_id = o.customer_id +WHERE c.country = 'IL' ``` -If second > first → fan-out → use `COUNT(DISTINCT f.flight_id)` or aggregate before joining. +If second > first → fan-out → use `COUNT(DISTINCT c.customer_id)` or aggregate before joining. ### Join type selection & Distributed Execution Order -- **Big Table on Left, Small Table on Right**: In Trino distributed joins, the right table is broadcast to worker nodes. Always put the largest fact table on the LEFT and the smaller lookup/dimension table on the RIGHT. +- **Join order**: Trino's cost-based optimizer reorders joins when table statistics exist. Without statistics, keep the + large fact table on the LEFT (probe side) and the small lookup table on the RIGHT (build side, may be broadcast). - **No Cross Joins**: Every `JOIN` must have an explicit `ON` condition with matching keys. - **INNER JOIN**: only rows that exist in both tables — use when the relationship is guaranteed. - **LEFT JOIN**: keep all left-side rows even without a match — use for "per entity" metrics where some entities may have zero related records. @@ -148,14 +149,14 @@ If second > first → fan-out → use `COUNT(DISTINCT f.flight_id)` or aggregate ## Window Functions ```sql --- Rank within group (e.g., top 3 cities per district) -ROW_NUMBER() OVER (PARTITION BY district ORDER BY area_kmr DESC) AS rn +-- Rank within group (e.g., top 3 products per category) +ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn -- Then filter: WHERE rn <= 3 ``` ## Zero-Row Investigation If your query returns 0 rows unexpectedly, investigate in this order: -1. String filter values — `search_column_values` or `get_column_distinct_values` +1. String filter values — re-resolve them by semantic type (`get_column_distinct_values` for categorical, `search_column_values` for large_categorical) 2. Join key alignment — `get_sample_rows` on both tables to verify key format matches 3. Date range logic — is the column a `DATE` or `TIMESTAMP`? Are the casts correct? 4. NULL presence — `get_column_profile` shows null_ratio; high null columns often filter everything out @@ -167,21 +168,21 @@ When multiple logic paths seem plausible (INNER vs LEFT JOIN, different grouping When schema is ambiguous, map the user's Hebrew terms to English tables/columns mentally before drafting. ## Per-Capita / Per-Entity Patterns -Notice the franularity difference between the numerator and the denominator. For example in the question: -"alerts per person" = COUNT(alerts) / SUM(population) — not AVG(count_per_row). +Notice the granularity difference between the numerator and the denominator. For example in the question: +"orders per resident" = COUNT(orders) / SUM(population) — not AVG(count_per_row). When the denominator comes from a different table, aggregate it independently in a CTE, then divide: ```sql -WITH alert_counts AS ( - SELECT district, COUNT(*) AS alerts - FROM alert_table GROUP BY district +WITH order_counts AS ( + SELECT region, COUNT(*) AS orders + FROM orders GROUP BY region ), populations AS ( - SELECT district, SUM(population) AS pop - FROM city_table GROUP BY district + SELECT region, SUM(population) AS pop + FROM regions GROUP BY region ) -SELECT a.district, a.alerts * 1.0 / p.pop AS alerts_per_capita -FROM alert_counts a JOIN populations p ON a.district = p.district +SELECT o.region, o.orders * 1.0 / p.pop AS orders_per_resident +FROM order_counts o JOIN populations p ON o.region = p.region ``` ## Trino Error → Fix Diagnostic Reference diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index bd89f14..71ec558 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -121,7 +121,7 @@ async def get_table_columns(table_name: str, runtime: Runtime = None) -> str: real example values, and profiling statistics. Args: - table_name (str): The table identifier (e.g. '"postgres"."public"."flights_table"' or 'flights_table'). + table_name (str): The table identifier (e.g. '"catalog"."schema"."orders"' or 'orders'). """ try: return ok(await get_jeen_metadata_client().get_columns(table_name, connection_id=connection_id(runtime))) @@ -138,7 +138,7 @@ async def get_table_relationships(runtime: Runtime = None) -> str: if not capability(runtime, "relationships"): return ok({ "relationships": [], - "notice": "This connection has NO foreign key relationships defined. Infer joins using matching column names, e.g. flight_id.", + "notice": "This connection has NO foreign key relationships defined. Infer joins using matching column names, e.g. customer_id.", }) try: rels = await get_jeen_metadata_client().get_relationships(connection_id=connection_id(runtime)) @@ -493,13 +493,13 @@ async def search_column_values( Works exclusively on high-cardinality columns profiled as: - `large_categorical` - `large_unit_id` - ⚠️ Do NOT use on standard `categorical` or `boolean` columns (e.g. `launch_country`) — they are + ⚠️ Do NOT use on standard `categorical` or `boolean` columns (e.g. a `status` column) — they are not indexed in vector search and will return 0 matches! Use `get_column_distinct_values` or the catalog instead. Do NOT use on numeric, date/timestamp, or geometry columns. WHEN TO USE: - Use whenever you need to find how a high-cardinality entity is represented or spelled in the database - (e.g., finding 'Tel Aviv 1' from 'תל אביב' or 'Acme Corp' from 'Acme'). Multilingual, + (e.g., finding 'Acme Corporation LLC' from 'Acme Corp', or the stored spelling of a Hebrew term). Multilingual, keyword, and vector search finds the exact database spelling. Returns data.matches — every matching value (use each 'value' verbatim in SQL) with: diff --git a/agent/tests/deep_agent/test_guidance_lint.py b/agent/tests/deep_agent/test_guidance_lint.py new file mode 100644 index 0000000..38af0c5 --- /dev/null +++ b/agent/tests/deep_agent/test_guidance_lint.py @@ -0,0 +1,109 @@ +""" +Lint for the Deep Agent's guidance (system prompt, skills, tool docstrings). + +Catches drift: references to tools that don't exist, known contradictory/incorrect +statements creeping back, catalog-specific examples in what must be general text-to-SQL +guidance, and skill SQL that isn't valid Trino. +""" + +import re + +import pytest +import sqlglot + +from deep_agent.agent import SYSTEM_PROMPT +from deep_agent.resources import DEFAULT_SKILLS_DIR, EXPECTED_SKILLS +from deep_agent.tools import DEEP_AGENT_TOOLS + +DOMAIN_TOOLS = {t.name for t in DEEP_AGENT_TOOLS} +HARNESS_TOOLS = {"task", "write_todos", "read_file", "ls", "DeepAgentAnswer"} + +DOCS: dict[str, str] = { + "system prompt": SYSTEM_PROMPT, + **{f"skill {p.parent.name}": p.read_text(encoding="utf-8") for p in sorted(DEFAULT_SKILLS_DIR.glob("*/SKILL.md"))}, + **{f"docstring {t.name}": t.description for t in DEEP_AGENT_TOOLS}, +} + +# Backticked identifiers that look like tool names (verb_object). +_TOOL_REF = re.compile(r"`((?:get|search|execute|validate|enrich|resolve)_[a-z_]+)`") + +# Statements that were wrong, contradictory or removed, and must not come back. +BANNED = [ + (r"Every categorical filter value must be verified — use `search_column_values`", "categorical values are not indexed"), + (r"`categorical` — small finite value set; use search_column_values", "categorical values are not indexed"), + (r"Use `search_column_values` with the user's term", "only for large_categorical / large_unit_id"), + (r"`search_column_values` on any string filter", "only for large_categorical / large_unit_id"), + (r"Using `NOW\(\)` — Trino uses", "now() is valid Trino"), + (r"Using `DATE_FORMAT` — Trino uses", "date_format() is valid Trino"), + (r'"השבוע".*date_trunc\(\'week\'', "Trino weeks start Monday; Israeli weeks start Sunday"), + (r"returns a `POINT", "resolve_location_to_wkt returns area geometries only"), + (r"@location_name_wkt@|@[a-z_]+_wkt@", "WKT placeholders are a legacy-graph mechanism"), + (r"Call (it|this) before every `execute_trino_query`|Always call before `execute_trino_query`", "validation is optional (#42)"), + (r"NEVER use Hebrew as SQL identifiers", "Hebrew catalog columns are valid (double-quoted)"), + (r"jeen_catalog \(str\)", "enrich_sql_filters takes only sql (#36)"), + (r"prefix_pattern", "search_column_values returns all matches; no prefix guessing (#45)"), + (r"sql_literal", "resolve_location_to_wkt returns data.wkt (#45)"), + (r"error\.category|error\.hint|error_category", "SQL errors carry Trino's own error.name / error.type (#39)"), + (r"validate_sql_syntax", "the tool is validate_sql (#39)"), + (r"needs_clarification", "clarifications are off by default; only the flag adds them to the prompt (#41)"), + (r"AGENTS\.md|agent_memory", "there is no AGENTS.md memory; always-on guidance is the system prompt (#40)"), +] + +# Catalog-specific names: guidance must stay general text-to-SQL knowledge, not one deployment's data. +CATALOG_SPECIFIC = re.compile( + r"flights?_table|flight_alerts|flight_id|city_info|launch_country|mahoz|Tel Aviv \d|'France'|\"postgres\"\.\"public\"", + re.IGNORECASE, +) + + +@pytest.mark.parametrize("doc", DOCS, ids=list(DOCS)) +def test_referenced_tools_exist(doc): + unknown = set(_TOOL_REF.findall(DOCS[doc])) - DOMAIN_TOOLS - HARNESS_TOOLS + assert not unknown, f"{doc} references unknown tools: {sorted(unknown)}" + + +@pytest.mark.parametrize("pattern, reason", BANNED, ids=[r for _, r in BANNED]) +def test_banned_statements_are_absent(pattern, reason): + hits = [name for name, text in DOCS.items() if re.search(pattern, text)] + assert not hits, f"{reason}: found in {hits}" + + +@pytest.mark.parametrize("doc", DOCS, ids=list(DOCS)) +def test_no_catalog_specific_examples(doc): + hits = sorted(set(CATALOG_SPECIFIC.findall(DOCS[doc]))) + assert not hits, f"{doc} contains catalog-specific examples: {hits}" + + +def test_value_resolution_policy_has_one_owner(): + owners = [name for name, text in DOCS.items() if "the only column types it indexes" in text] + assert owners == ["system prompt"] + + +def test_system_prompt_names_every_skill(): + for skill in EXPECTED_SKILLS: + assert f"`{skill}`" in SYSTEM_PROMPT + + +def _sql_blocks(name: str, text: str) -> list[tuple[str, str]]: + blocks = [] + for i, block in enumerate(re.findall(r"```sql\n(.*?)```", text, re.DOTALL)): + # Split into statements on blank lines; keep complete SELECT / WITH statements only. + for j, chunk in enumerate(re.split(r"\n\s*\n", block)): + body = "\n".join(line for line in chunk.splitlines() if not line.strip().startswith("--")).strip() + if re.match(r"(?is)^(SELECT|WITH)\b", body): + blocks.append((f"{name}#{i}.{j}", body)) + return blocks + + +SQL_BLOCKS = [b for name, text in DOCS.items() if not name.startswith("docstring") for b in _sql_blocks(name, text)] + + +def test_guidance_contains_sql_examples(): + assert len(SQL_BLOCKS) >= 15 + + +@pytest.mark.parametrize("name, sql", SQL_BLOCKS, ids=[n for n, _ in SQL_BLOCKS]) +def test_guidance_sql_parses_as_trino(name, sql): + # Template placeholders like stand for a boolean expression. + sql = re.sub(r"<[^<>]+>", "1 = 1", sql) + sqlglot.parse_one(sql, read="trino") diff --git a/agent/tests/deep_agent/test_resources.py b/agent/tests/deep_agent/test_resources.py index 57f3880..2db93bc 100644 --- a/agent/tests/deep_agent/test_resources.py +++ b/agent/tests/deep_agent/test_resources.py @@ -6,7 +6,6 @@ from deep_agent.agent import create_deep_agent from deep_agent.resources import ( - DEFAULT_MEMORY_DIR, DEFAULT_SKILLS_DIR, EXPECTED_SKILLS, DeepAgentResourceError, @@ -17,11 +16,10 @@ from tests.deep_agent.conftest import system_text -def test_packaged_skills_and_memory_are_valid(): +def test_packaged_skills_are_valid(): resources = build_resources() assert resources.skill_names == EXPECTED_SKILLS assert resources.skills == ["/skills/"] - assert resources.memory == ["/memory/AGENTS.md"] def test_no_user_specific_paths_in_deep_agent_sources(): @@ -35,49 +33,39 @@ def test_resources_resolve_independently_of_cwd(tmp_path, monkeypatch): @pytest.fixture -def resource_copy(tmp_path): +def skills_copy(tmp_path): skills = tmp_path / "skills" - memory = tmp_path / "memory" shutil.copytree(DEFAULT_SKILLS_DIR, skills) - shutil.copytree(DEFAULT_MEMORY_DIR, memory) - return skills, memory + return skills def test_missing_skills_dir_fails_fast(tmp_path): with pytest.raises(DeepAgentResourceError, match="Skills directory not found"): - build_resources(skills_dir=tmp_path / "nope", memory_dir=DEFAULT_MEMORY_DIR) + build_resources(skills_dir=tmp_path / "nope") -def test_missing_required_skill_fails_fast(resource_copy): - skills, memory = resource_copy - shutil.rmtree(skills / "temporal-analyst") +def test_missing_required_skill_fails_fast(skills_copy): + shutil.rmtree(skills_copy / "temporal-analyst") with pytest.raises(DeepAgentResourceError, match="temporal-analyst"): - build_resources(skills_dir=skills, memory_dir=memory) + build_resources(skills_dir=skills_copy) -def test_empty_memory_fails_fast(resource_copy): - skills, memory = resource_copy - (memory / "AGENTS.md").write_text(" \n", encoding="utf-8") - with pytest.raises(DeepAgentResourceError, match="Memory file missing or empty"): - build_resources(skills_dir=skills, memory_dir=memory) - - -def test_skill_without_frontmatter_fails_fast(resource_copy): - skills, _ = resource_copy +def test_skill_without_frontmatter_fails_fast(skills_copy): + skills = skills_copy (skills / "trino-expert" / "SKILL.md").write_text("# no frontmatter", encoding="utf-8") with pytest.raises(DeepAgentResourceError, match="frontmatter"): discover_skills(skills) -def test_skill_name_must_match_directory(resource_copy): - skills, _ = resource_copy +def test_skill_name_must_match_directory(skills_copy): + skills = skills_copy os.rename(skills / "trino-expert", skills / "trino") with pytest.raises(DeepAgentResourceError, match="must match its directory"): discover_skills(skills) @pytest.mark.asyncio -async def test_skills_and_memory_reach_the_model_prompt(scripted_model): +async def test_skills_and_system_prompt_reach_the_model_without_memory(scripted_model): model = scripted_model(AIMessage("done")) agent = create_deep_agent(model=model) await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-prompt"}}) @@ -89,14 +77,15 @@ async def test_skills_and_memory_reach_the_model_prompt(scripted_model): for skill_md in sorted(DEFAULT_SKILLS_DIR.glob("*/SKILL.md")): description = _read_frontmatter(skill_md)["description"] assert description[:60] in prompt, f"skill {skill_md.parent.name} not loaded" - assert "Deep SQL Analyst — Core Memory" in prompt, "AGENTS.md memory not injected" + assert "## Phase 1 — Understand (Discovery)" in prompt, "system prompt file not loaded" + assert "" not in prompt, "no AGENTS.md memory block (or its boilerplate) is expected" @pytest.mark.asyncio -async def test_agent_cannot_write_skills_or_memory(scripted_model): +async def test_agent_cannot_write_skills(scripted_model): write = AIMessage("", tool_calls=[ {"name": "write_file", "args": {"file_path": "/skills/evil/SKILL.md", "content": "x"}, "id": "w1"}, - {"name": "edit_file", "args": {"file_path": "/memory/AGENTS.md", "old_string": "Deep", "new_string": "Shallow"}, "id": "w2"}, + {"name": "edit_file", "args": {"file_path": "/skills/trino-expert/SKILL.md", "old_string": "Trino", "new_string": "X"}, "id": "w2"}, ]) model = scripted_model(write, AIMessage("done")) agent = create_deep_agent(model=model) @@ -107,7 +96,7 @@ async def test_agent_cannot_write_skills_or_memory(scripted_model): for msg in tool_results: assert "denied" in msg.text.lower() or "permission" in msg.text.lower(), msg.text assert not (DEFAULT_SKILLS_DIR / "evil").exists() - assert "Deep SQL Analyst" in (DEFAULT_MEMORY_DIR / "AGENTS.md").read_text(encoding="utf-8") + assert "Trino SQL Expert Reference" in (DEFAULT_SKILLS_DIR / "trino-expert" / "SKILL.md").read_text(encoding="utf-8") @pytest.mark.asyncio From 38784836ab92144e1fb140cc82ee9ac1a3f78046 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 29 Oct 2026 10:52:23 +0200 Subject: [PATCH 17/37] feat(deep-agent): deterministic catalog, 8 tools, Trino rules in the prompt, Langfuse prompts, answer recovery (#48, revised) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Based on deep-agent/48-subagents-prompts (949f3a6, adcdce9), revised in review: - taken from #48: Langfuse-managed prompts (prompt_registry, per-call refresh, miss cache, trace links to the served version, sync script) — off by default until the prompts are finalised; merge_executions reducer - not taken: the schema-scout / value-resolver / result-verifier subagents - catalog is deterministic: CatalogMiddleware loads it once per run for the request's connection and adds it to every model call's system message (never to history); a failed or empty load fails the run; the built-in general-purpose subagent gets it too; get_database_catalog tool and the capabilities mechanism removed - tools 16 -> 8; get_database_tables / get_table_columns / get_table_profile / get_table_relationships / search_metadata / search_business_terms / search_knowledge_pairs kept unregistered (the catalog contains their data) - trino-expert folded into the system prompt (dialect essentials, non-Trino function table, merged error table verified on Trino); skill removed - answer tool renamed submit_answer - AnswerRecoveryMiddleware: gpt-oss on the configured server often writes the final answer JSON as text despite forced tool choice; text that validates against the answer schema is turned into the submit_answer result and marked (final_result.recovered_from_text); anything else stays no_answer - verified end to end on the real catalog + Trino: 4/4 questions answered Co-Authored-By: Claude Opus 5.5 --- agent/scripts/sync_deep_agent_prompts.py | 43 ++++ agent/src/agent/config.py | 4 + agent/src/deep_agent/agent.py | 45 +++- agent/src/deep_agent/answer.py | 116 ++++++++-- agent/src/deep_agent/catalog.py | 73 ++++++ agent/src/deep_agent/context.py | 34 +-- agent/src/deep_agent/observability.py | 8 + agent/src/deep_agent/prompt_registry.py | 134 +++++++++++ agent/src/deep_agent/prompts/system.md | 114 ++++++---- agent/src/deep_agent/resources.py | 2 +- .../deep_agent/skills/trino-expert/SKILL.md | 211 ------------------ agent/src/deep_agent/tools.py | 116 +++------- agent/tests/deep_agent/conftest.py | 18 ++ agent/tests/deep_agent/test_answer.py | 59 ++++- agent/tests/deep_agent/test_catalog_state.py | 34 ++- agent/tests/deep_agent/test_guidance_lint.py | 2 +- agent/tests/deep_agent/test_latency.py | 4 +- agent/tests/deep_agent/test_observability.py | 1 - .../deep_agent/test_prompts_and_catalog.py | 194 ++++++++++++++++ agent/tests/deep_agent/test_resources.py | 15 +- .../tests/deep_agent/test_runtime_context.py | 72 +++--- agent/tests/deep_agent/test_tool_contracts.py | 32 ++- 22 files changed, 869 insertions(+), 462 deletions(-) create mode 100644 agent/scripts/sync_deep_agent_prompts.py create mode 100644 agent/src/deep_agent/catalog.py create mode 100644 agent/src/deep_agent/prompt_registry.py delete mode 100644 agent/src/deep_agent/skills/trino-expert/SKILL.md create mode 100644 agent/tests/deep_agent/test_prompts_and_catalog.py diff --git a/agent/scripts/sync_deep_agent_prompts.py b/agent/scripts/sync_deep_agent_prompts.py new file mode 100644 index 0000000..33d051a --- /dev/null +++ b/agent/scripts/sync_deep_agent_prompts.py @@ -0,0 +1,43 @@ +""" +Push the packaged Deep Agent prompts (agent/src/deep_agent/prompts/*.md) to Langfuse. + + uv run python scripts/sync_deep_agent_prompts.py --label staging # create new versions labelled staging + uv run python scripts/sync_deep_agent_prompts.py --label production --dry-run + +Each run creates a new version of every `deep-agent/` text prompt with the given label. +Promote a version by moving the `production` label in the Langfuse UI — the running agent +picks it up within DEEP_AGENT_PROMPT_CACHE_TTL_S, no redeploy. +""" + +import argparse + +from deep_agent.prompt_registry import PROMPT_KEYS, langfuse_name, local_prompt + + +def sync(client, label: str, dry_run: bool = False) -> list[str]: + names = [] + for key in PROMPT_KEYS: + name = langfuse_name(key) + if not dry_run: + client.create_prompt(name=name, prompt=local_prompt(key), labels=[label], type="text", + commit_message="sync from agent/src/deep_agent/prompts") + names.append(name) + return names + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--label", default="staging") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + + from agent.langfuse_client import langfuse_client + + for name in sync(langfuse_client, args.label, args.dry_run): + print(f"{'would push' if args.dry_run else 'pushed'} {name} [{args.label}]") + if not args.dry_run: + langfuse_client.flush() + + +if __name__ == "__main__": + main() diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 124c852..2c047a1 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -54,6 +54,10 @@ class AgentSettings(BaseSettings): DEEP_AGENT_CLARIFICATIONS_ENABLED: bool = False # let the model ask a clarifying question instead of answering JEEN_METADATA_CACHE_TTL_S: float = Field(default=300.0, ge=0) # metadata read cache (0 disables) JEEN_METADATA_REUSE_SESSION: bool = True # keep one MCP session open per event loop + # Prompts (see deep_agent/prompt_registry.py). Off until the prompts are finalised and synced to Langfuse. + DEEP_AGENT_LANGFUSE_PROMPTS: bool = False # serve deep-agent/ prompts from Langfuse (packaged .md fallback) + DEEP_AGENT_PROMPT_LABEL: str = "production" # Langfuse prompt label to serve + DEEP_AGENT_PROMPT_CACHE_TTL_S: int = Field(default=60, ge=0) # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 566307b..5f4a090 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -1,25 +1,29 @@ """ Agent logic and LangGraph harness for the Deep Agent. -""" -from pathlib import Path +The system prompt is served by deep_agent.prompt_registry (Langfuse `deep-agent/system` when +DEEP_AGENT_LANGFUSE_PROMPTS is on, else the packaged prompts/system.md). The connection's catalog +is added to every model call by CatalogMiddleware (deep_agent.catalog). +""" from deepagents import create_deep_agent as create_harness_agent +from deepagents.middleware.subagents import DEFAULT_GENERAL_PURPOSE_DESCRIPTION, DEFAULT_SUBAGENT_PROMPT from langchain.agents.structured_output import ToolStrategy from langchain_core.language_models import BaseChatModel from langgraph.checkpoint.memory import MemorySaver -from agent.llm import get_llm from agent.config import settings -from deep_agent.answer import AnswerVerificationMiddleware, answer_schema +from agent.llm import get_llm +from deep_agent.answer import AnswerRecoveryMiddleware, AnswerVerificationMiddleware, answer_schema +from deep_agent.catalog import CatalogMiddleware from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware +from deep_agent.prompt_registry import PromptRefreshMiddleware, load_prompt, local_prompt from deep_agent.resources import build_resources from deep_agent.tool_filter import BuiltinToolFilterMiddleware from deep_agent.tools import DEEP_AGENT_TOOLS - -PROMPTS_DIR = Path(__file__).resolve().parent / "prompts" -SYSTEM_PROMPT = (PROMPTS_DIR / "system.md").read_text(encoding="utf-8") +# Packaged system prompt (the Langfuse-managed version, when enabled, is loaded per agent build and refreshed per call). +SYSTEM_PROMPT = local_prompt("system") # Appended to the system prompt only when DEEP_AGENT_CLARIFICATIONS_ENABLED is on. CLARIFICATION_PROMPT = """ @@ -27,10 +31,19 @@ """ +def _general_purpose_subagent() -> dict: + """deepagents' default `task` subagent, with our request context and the catalog it can no longer fetch itself.""" + return { + "name": "general-purpose", + "description": DEFAULT_GENERAL_PURPOSE_DESCRIPTION, + "system_prompt": DEFAULT_SUBAGENT_PROMPT, + "middleware": [DeepAgentContextMiddleware(), CatalogMiddleware(), BuiltinToolFilterMiddleware()], + } + + def create_deep_agent(model: BaseChatModel | None = None, clarifications_enabled: bool | None = None): """ - Creates and returns a compiled LangGraph deep agent equipped with all exploration, - enrichment, temporal, geospatial, and semantic validation tools. + Creates and returns a compiled LangGraph deep agent. Invoke with a per-request context, e.g. agent.ainvoke(inputs, config, context=DeepAgentContext(connection_id=89, user_id="u1")) @@ -44,12 +57,22 @@ def create_deep_agent(model: BaseChatModel | None = None, clarifications_enabled llm = model or get_llm() memory = MemorySaver() resources = build_resources() + suffix = CLARIFICATION_PROMPT if clarifications_enabled else "" + system_prompt = load_prompt("system").text + suffix agent = create_harness_agent( model=llm, tools=DEEP_AGENT_TOOLS, - system_prompt=SYSTEM_PROMPT + CLARIFICATION_PROMPT if clarifications_enabled else SYSTEM_PROMPT, - middleware=[DeepAgentContextMiddleware(), AnswerVerificationMiddleware(), BuiltinToolFilterMiddleware()], + system_prompt=system_prompt, + subagents=[_general_purpose_subagent()], + middleware=[ + DeepAgentContextMiddleware(), + CatalogMiddleware(), + PromptRefreshMiddleware("system", system_prompt, suffix=suffix), + AnswerRecoveryMiddleware(), + AnswerVerificationMiddleware(), + BuiltinToolFilterMiddleware(), + ], response_format=ToolStrategy(answer_schema(clarifications_enabled)), context_schema=DeepAgentContext, checkpointer=memory, diff --git a/agent/src/deep_agent/answer.py b/agent/src/deep_agent/answer.py index b095559..707a8c2 100644 --- a/agent/src/deep_agent/answer.py +++ b/agent/src/deep_agent/answer.py @@ -1,7 +1,7 @@ """ Structured final answer for the Deep Agent, bound to SQL that actually ran. -The model finishes by submitting a DeepAgentAnswer (ToolStrategy structured output). +The model finishes by calling the `submit_answer` tool (ToolStrategy structured output). AnswerVerificationMiddleware then binds it to evidence. `final_result.executed` says whether the final SQL ran and the rows shown are Trino's — it does NOT mean the answer was checked to be semantically correct. @@ -18,11 +18,16 @@ """ import asyncio +import json import logging +import re +import uuid +from collections.abc import Awaitable, Callable from typing import Any, Literal import sqlglot -from langchain.agents.middleware import AgentMiddleware +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse +from langchain_core.messages import AIMessage, ToolMessage from pydantic import BaseModel, Field, create_model from sqlglot.errors import SqlglotError @@ -36,9 +41,11 @@ VerificationStatus = Literal["matched", "re_executed", "rejected", "re_execution_failed", "clarification", "no_answer"] -class DeepAgentAnswer(BaseModel): - """Submit the final answer. Call this exactly once, when you are done.""" +TOOL_NAME = "submit_answer" +_SUBMIT_DOC = "Submit your final answer. Call this exactly once, when you are done — it ends your work." + +class _AnswerFields(BaseModel): sql: str = Field( description="The exact final Trino SQL whose results answer the question — the same query you executed " "successfully with execute_trino_query.", @@ -50,11 +57,15 @@ class DeepAgentAnswer(BaseModel): confidence: Literal["high", "medium", "low"] = Field(description="Confidence that the SQL answers the question.") -# Same tool name ("DeepAgentAnswer"), plus the option to ask a clarifying question instead of answering. -DeepAgentAnswerWithClarification = create_model( - "DeepAgentAnswer", - __base__=DeepAgentAnswer, - __doc__=DeepAgentAnswer.__doc__, +# The final-answer tool. LangChain's ToolStrategy names the tool after the schema's __name__, so the +# model sees a tool called `submit_answer` (the "I'm done" submit convention). +SubmitAnswer = create_model(TOOL_NAME, __base__=_AnswerFields, __doc__=_SUBMIT_DOC) + +# Same tool name, plus the option to ask a clarifying question instead of answering. +SubmitAnswerWithClarification = create_model( + TOOL_NAME, + __base__=SubmitAnswer, + __doc__=_SUBMIT_DOC, sql=(str | None, Field( default=None, description="The exact final Trino SQL whose results answer the question — the same query you executed " @@ -66,10 +77,10 @@ class DeepAgentAnswer(BaseModel): ) -def answer_schema(clarifications_enabled: bool | None = None) -> type[DeepAgentAnswer]: +def answer_schema(clarifications_enabled: bool | None = None) -> type[SubmitAnswer]: """The final-answer schema; without clarifications the model must always commit to a SQL answer.""" enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED if clarifications_enabled is None else clarifications_enabled - return DeepAgentAnswerWithClarification if enabled else DeepAgentAnswer + return SubmitAnswerWithClarification if enabled else SubmitAnswer def normalize_sql(sql: str | None) -> str | None: @@ -144,7 +155,7 @@ def _result_view(record: dict[str, Any]) -> dict[str, Any]: def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any]: """Build `final_result` from the structured answer and the run's successful executions.""" - if not isinstance(answer, DeepAgentAnswer): + if not isinstance(answer, SubmitAnswer): return {"status": "no_answer", "executed": False, "answer": None, "sql": None, "result": None, "error": None} base = {"answer": answer.model_dump(), "error": None} @@ -161,11 +172,90 @@ def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any] return {**base, "status": status, "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} +RECOVERED_FLAG = "deep_agent_recovered_answer" +_FENCED_JSON = re.compile(r"^```(?:json)?\s*(\{.*\})\s*```$", re.DOTALL) + + +def _answer_from_text(text: str, schema: type[BaseModel]) -> tuple[dict, BaseModel] | None: + """The message text as a valid final answer (a JSON object that passes the answer schema), else None.""" + body = text.strip() + fenced = _FENCED_JSON.match(body) + if fenced: + body = fenced.group(1) + if not (body.startswith("{") and body.endswith("}")): + return None + try: + args = json.loads(body) + return args, schema(**args) + except (ValueError, TypeError): + return None + + +class AnswerRecoveryMiddleware(AgentMiddleware): + """Recover a final answer the model wrote as text instead of calling submit_answer. + + With gpt-oss behind the configured OpenAI-compatible server, forced tool choice is not always + honoured late in a run: the model sometimes writes the submit_answer JSON as plain text + (finish_reason "tool_calls", no parsed tool call). LangChain then sees no tool call and the run + ends without an answer. When — and only when — the text is a JSON object that validates against + the answer schema, this turns it into the same result a real submit_answer call produces (the + tool call, its tool message and `structured_response`), marked with RECOVERED_FLAG. + Anything else is left untouched. + """ + + def _recover(self, request: ModelRequest, response: ModelResponse) -> ModelResponse: + schema = getattr(request.response_format, "schema", None) + if response.structured_response is not None or schema is None or not response.result: + return response + output = response.result[-1] + if not isinstance(output, AIMessage) or output.tool_calls: + return response + parsed = _answer_from_text(output.text, schema) + if parsed is None: + return response + args, answer = parsed + call_id = f"recovered_{uuid.uuid4().hex[:12]}" + logger.warning("Recovered a final answer the model wrote as text instead of a submit_answer call") + repaired = AIMessage( + content="", + tool_calls=[{"name": schema.__name__, "args": args, "id": call_id, "type": "tool_call"}], + additional_kwargs={**output.additional_kwargs, RECOVERED_FLAG: True}, + response_metadata=output.response_metadata, + usage_metadata=output.usage_metadata, + id=output.id, + name=output.name, + ) + tool_message = ToolMessage( + content=f"Returning structured response: {answer}", tool_call_id=call_id, name=schema.__name__, + ) + return ModelResponse(result=[*response.result[:-1], repaired, tool_message], structured_response=answer) + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return self._recover(request, handler(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return self._recover(request, await handler(request)) + + +def _current_turn(messages: list) -> list: + """Messages after the latest human message (this run's turn).""" + for i in range(len(messages) - 1, -1, -1): + if getattr(messages[i], "type", None) == "human": + return messages[i + 1:] + return messages + + class AnswerVerificationMiddleware(AgentMiddleware): """After the agent finishes, bind the structured answer to executed SQL and real rows.""" def after_agent(self, state, runtime) -> dict[str, Any] | None: - return {"final_result": verify_answer(state.get("structured_response"), state.get("executed_queries") or [])} + final = verify_answer(state.get("structured_response"), state.get("executed_queries") or []) + final["recovered_from_text"] = any( + (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in _current_turn(state.get("messages") or []) + ) + return {"final_result": final} async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: return await asyncio.to_thread(self.after_agent, state, runtime) diff --git a/agent/src/deep_agent/catalog.py b/agent/src/deep_agent/catalog.py new file mode 100644 index 0000000..39e103f --- /dev/null +++ b/agent/src/deep_agent/catalog.py @@ -0,0 +1,73 @@ +""" +Deterministic catalog loading for the Deep Agent. + +Every question needs the connection's catalog, so it is not a tool the model has to remember to +call: CatalogMiddleware loads it once at the start of each run (for the request's connection, +through the Jeen client's TTL cache) into graph state, and adds it to the system message of +every model call as a "Database Catalog" section after the static prompt. It is never written +into the message history, so it is not duplicated across turns. + +Without a catalog the agent cannot answer, so a failed load fails the run with a clear error. +""" + +import asyncio +from collections.abc import Awaitable, Callable +from typing import Any + +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse +from langchain_core.messages import SystemMessage + +from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from deep_agent.context import DeepAgentRuntimeState + +CATALOG_HEADER = "\n\n---\n\n# Database Catalog\n\nThe complete catalog of the connection you are answering against:\n\n" + + +class CatalogLoadError(RuntimeError): + """The connection's catalog could not be loaded; the run cannot proceed without it.""" + + +async def load_catalog(connection_id: int | None) -> str: + try: + catalog = await get_jeen_metadata_client().get_catalog_prompt(connection_id=connection_id) + except Exception as exc: + raise CatalogLoadError(f"Could not load the database catalog for connection {connection_id}: {exc}") from exc + if not catalog or not str(catalog).strip(): + raise CatalogLoadError(f"The database catalog for connection {connection_id} is empty") + return str(catalog) + + +def _connection_id(runtime: Any) -> int | None: + return getattr(getattr(runtime, "context", None), "connection_id", None) + + +def _with_catalog(request: ModelRequest) -> ModelRequest: + catalog = (request.state or {}).get("jeen_catalog") + if not catalog or request.system_message is None: + return request + content = request.system_message.content + if isinstance(content, str): + new_content: Any = content + CATALOG_HEADER + catalog + else: + new_content = [*content, {"type": "text", "text": CATALOG_HEADER + catalog}] + return request.override(system_message=SystemMessage(content=new_content)) + + +class CatalogMiddleware(AgentMiddleware): + """Load the connection's catalog at the start of each run and show it to every model call.""" + + state_schema = DeepAgentRuntimeState + + async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: + return {"jeen_catalog": await load_catalog(_connection_id(runtime))} + + def before_agent(self, state, runtime) -> dict[str, Any] | None: + return {"jeen_catalog": asyncio.run(load_catalog(_connection_id(runtime)))} + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(_with_catalog(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(_with_catalog(request)) diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index e14073b..52d3f4f 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -4,14 +4,12 @@ Nothing request-specific lives in module globals: - DeepAgentContext is passed per invocation (`agent.ainvoke(..., context=DeepAgentContext(...))`) and read by tools through `ToolRuntime.context`. -- Connection capabilities and the raw catalog fetched by get_database_catalog are written to - graph state (`connection_capabilities`, `jeen_catalog`) and read back by tools through - `ToolRuntime.state`. +- The connection's catalog is loaded once per run by CatalogMiddleware (deep_agent.catalog) + into graph state (`jeen_catalog`) and read back by tools through `ToolRuntime.state`. - Today's date is added to the latest human message on every model call, in the context's timezone, so long-running processes never serve a stale date. """ -import operator from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import datetime @@ -32,10 +30,26 @@ class DeepAgentContext: timezone: str = DEFAULT_TIMEZONE +def merge_executions(left: list[dict[str, Any]] | None, right: list[dict[str, Any]] | None) -> list[dict[str, Any]]: + """Append-only reducer for executed_queries that ignores records already present. + + deepagents passes the parent's state into a subagent and returns the subagent's state as + an update; a plain list-append reducer would duplicate the parent's history on every + `task` call. + """ + merged = list(left or []) + seen = {(r.get("query_id"), r.get("executed_sql")) for r in merged} + for record in right or []: + key = (record.get("query_id"), record.get("executed_sql")) + if key not in seen: + merged.append(record) + seen.add(key) + return merged + + class DeepAgentRuntimeState(AgentState): - connection_capabilities: NotRequired[dict[str, bool]] - jeen_catalog: NotRequired[str] # raw catalog text, cached so tools never need the model to re-send it - executed_queries: NotRequired[Annotated[list[dict[str, Any]], operator.add]] # successful executions (append-only) + jeen_catalog: NotRequired[str] # the connection's catalog, loaded once per run (deep_agent.catalog) + executed_queries: NotRequired[Annotated[list[dict[str, Any]], merge_executions]] # successful executions final_result: NotRequired[dict[str, Any]] # verified answer + rows (see deep_agent.answer) @@ -44,12 +58,6 @@ def connection_id(runtime: ToolRuntime | None) -> int | None: return getattr(ctx, "connection_id", None) -def capability(runtime: ToolRuntime | None, name: str) -> bool: - """Whether the connection has a discovery source; unknown (catalog not fetched yet) counts as available.""" - state = getattr(runtime, "state", None) or {} - return bool((state.get("connection_capabilities") or {}).get(name, True)) - - def cached_catalog(runtime: ToolRuntime | None) -> str | None: state = getattr(runtime, "state", None) or {} return state.get("jeen_catalog") or None diff --git a/agent/src/deep_agent/observability.py b/agent/src/deep_agent/observability.py index 89a38d6..c313c41 100644 --- a/agent/src/deep_agent/observability.py +++ b/agent/src/deep_agent/observability.py @@ -68,6 +68,14 @@ def build_run_config( } if user_id: metadata["langfuse_user_id"] = user_id + if handlers: + from deep_agent.prompt_registry import load_prompt + + prompt = load_prompt("system") + if prompt.client is not None: + metadata["langfuse_prompt"] = prompt.client # links generations to the served prompt version + metadata["prompt_source"] = prompt.source + metadata["prompt_version"] = prompt.version return RunnableConfig( configurable={"thread_id": thread_id}, diff --git a/agent/src/deep_agent/prompt_registry.py b/agent/src/deep_agent/prompt_registry.py new file mode 100644 index 0000000..23c669d --- /dev/null +++ b/agent/src/deep_agent/prompt_registry.py @@ -0,0 +1,134 @@ +""" +Prompt management for the Deep Agent. + +Prompts are Langfuse text prompts named `deep-agent/` (currently only `system`), fetched by label (DEEP_AGENT_PROMPT_LABEL, default +"production") with the SDK's TTL cache. The packaged `prompts/.md` files are the +fallback when Langfuse is unreachable or the prompt doesn't exist, and the only source when +DEEP_AGENT_LANGFUSE_PROMPTS is off (tests, offline dev). + +PromptRefreshMiddleware swaps in the current Langfuse version on every model call, so moving +a label in Langfuse changes behaviour without a redeploy. Push the packaged prompts with +`uv run python scripts/sync_deep_agent_prompts.py --label staging`. +""" + +import logging +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse +from langchain_core.messages import SystemMessage + +from agent.config import settings + +logger = logging.getLogger(__name__) + +PROMPTS_DIR = Path(__file__).resolve().parent / "prompts" +PROMPT_KEYS = ("system",) + + +def langfuse_name(key: str) -> str: + return f"deep-agent/{key}" + + +def local_prompt(key: str) -> str: + return (PROMPTS_DIR / f"{key}.md").read_text(encoding="utf-8") + + +@dataclass(frozen=True) +class LoadedPrompt: + key: str + text: str + source: str # "langfuse" | "local" + version: int | None = None + client: Any = None # langfuse TextPromptClient (links generations to the prompt version) + + +# key -> monotonic deadline until which Langfuse is not asked again (prompt missing / unreachable). +# The SDK caches successful fetches but not misses, and load_prompt runs on every model call. +_misses: dict[str, float] = {} + + +def _miss(key: str, local: str) -> LoadedPrompt: + _misses[key] = time.monotonic() + max(settings.DEEP_AGENT_PROMPT_CACHE_TTL_S, 1) + return LoadedPrompt(key, local, "local") + + +def load_prompt(key: str) -> LoadedPrompt: + local = local_prompt(key) + if not settings.DEEP_AGENT_LANGFUSE_PROMPTS: + return LoadedPrompt(key, local, "local") + if _misses.get(key, 0.0) > time.monotonic(): + return LoadedPrompt(key, local, "local") + try: + from agent.langfuse_client import langfuse_client + + client = langfuse_client.get_prompt( + langfuse_name(key), + label=settings.DEEP_AGENT_PROMPT_LABEL, + type="text", + fallback=local, + cache_ttl_seconds=settings.DEEP_AGENT_PROMPT_CACHE_TTL_S, + fetch_timeout_seconds=5, + max_retries=1, + ) + except Exception as exc: + logger.warning("Langfuse prompt %s unavailable (%s); using packaged prompt", langfuse_name(key), exc) + return _miss(key, local) + if getattr(client, "is_fallback", False): + return _miss(key, local) + _misses.pop(key, None) + return LoadedPrompt(key, client.prompt, "langfuse", getattr(client, "version", None), client) + + +def _system_text(message: SystemMessage | None) -> str: + if message is None: + return "" + content = message.content + if isinstance(content, str): + return content + first = content[0] if content else None + return first.get("text", "") if isinstance(first, dict) else str(first or "") + + +class PromptRefreshMiddleware(AgentMiddleware): + """Replace the prompt the agent was built with by the current version of `key`, per model call. + + deepagents composes the system message as + harness/skills sections, so only that + leading part is swapped; if it isn't found verbatim the request is left untouched. `suffix` is + text appended to the prompt at build time (e.g. the clarification sentence when that flag is + on) and is re-appended to every refreshed version. + """ + + def __init__(self, key: str, built_with: str, suffix: str = "") -> None: + super().__init__() + self.key = key + self.built_with = built_with + self.suffix = suffix + + def _refresh(self, request: ModelRequest) -> ModelRequest: + current = load_prompt(self.key).text + self.suffix + if current == self.built_with or request.system_message is None: + return request + message = request.system_message + if isinstance(message.content, str): + if not message.content.startswith(self.built_with): + return request + new_content: Any = current + message.content[len(self.built_with):] + else: + text = _system_text(message) + if not text.startswith(self.built_with): + return request + first = {**message.content[0], "text": current + text[len(self.built_with):]} + new_content = [first, *message.content[1:]] + return request.override(system_message=SystemMessage(content=new_content)) + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(self._refresh(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(self._refresh(request)) diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index 7d8df40..3529525 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -4,19 +4,18 @@ You are an elite, autonomous Deep SQL Analyst. Your mission: translate natural-l ## Non-negotiable Principle -**Execution success ≠ correctness.** A query can run, return plausible-looking rows, and still be wrong. Semantic correctness — whether the SQL actually answers the user's question — is your responsibility. Verify it; don't execute and hope. +**Execution success ≠ correctness.** A query can run, return plausible-looking rows, and still be wrong. Semantic correctness — whether the SQL actually answers the user's question — is your responsibility. Verify it throughout your work; don't execute and hope. (An independent check may run after you answer, but it never replaces your own verification.) --- -## Phase 1 — Understand (Discovery) +## Phase 1 — Understand -Start here, then move on — don't over-explore. +The connection's **complete catalog is included at the end of this prompt** ("Database Catalog"): every table with its exact 3-part name, every column with its type, `semantic_type`, distinct count, range and example values (all values when the domain is complete), plus the connection's knowledge pairs, business terms and relationships. You never need to fetch it. -- `get_database_catalog` — full schema with column stats and semantic types. **Call it once per conversation and reuse the result**; other tools reuse it too. - - The catalog ends with a **Discovery Capabilities Note**. When it says a connection has no knowledge pairs, no business terms or no relationships, do NOT call `search_knowledge_pairs`, `search_business_terms` or `get_table_relationships` respectively — they would only waste a round-trip. Without relationships, infer joins from matching column names (e.g. `customer_id`). -- `search_knowledge_pairs` — prior solved examples. When they exist, check them before exploring from scratch: they are the fastest path to the right join path, column conventions and domain logic. -- `search_business_terms` / `search_metadata` — map the user's (Hebrew / domain) vocabulary to database terminology. -- `get_table_relationships` — verified foreign keys and join paths. +- Read the question against the catalog: which tables and columns hold the answer, how they join, and what each term in the question means. +- **Knowledge pairs** (prior solved question → SQL examples), when the catalog lists any, are the fastest path to the right join path, column conventions and domain logic — check them first. +- **Business terms** map the user's (Hebrew / domain) vocabulary to database terminology. +- **Relationships** are verified join paths. When none are listed, infer joins from matching column names (e.g. `customer_id`), and verify the key formats match (`get_sample_rows` on both sides). Simple, unambiguous lookups may skip directly to Phase 3. @@ -44,16 +43,17 @@ The user's word is almost never the stored string — the value may be spelled d > **Tool scope**: `search_column_values` searches ONLY `large_categorical` and `large_unit_id` columns — the only column types it indexes. Standard `categorical` and `boolean` columns are not indexed and return 0 matches; numeric, date/timestamp and geometry columns are not indexed either. 1. **High-cardinality (`large_categorical` / `large_unit_id`)** — e.g. customer, company or person names, product SKUs, city names: - - Too many values to list; use `search_column_values` with the user's term to find how the database actually spells the entity (e.g. "Acme Corp" → "Acme Corporation LLC"). Use the returned values verbatim. + - Too many values to list; use `search_column_values` with the user's term to find how the database actually spells the entity (e.g. "Acme Corp" → "Acme Corporation LLC"). Use the returned `value`s verbatim. A `keyword_similarity` close to 1.0 is a strong lexical match; a `semantic_distance` close to 0.0 is a strong semantic match. - When several values match (e.g. "Acme Corporation LLC" and "Acme Corp Holdings", or "North Branch 1", "North Branch 2"), decide whether the question means one of them or all of them, and filter accordingly — `IN (...)` with the exact values, or a `LIKE 'prefix%'` that covers exactly those values. Record the choice in `assumptions`. + - When nothing matches, the value may not exist in the data — investigate before writing a filter that will return 0 rows. - Don't call `get_column_distinct_values` on these columns — dumping 50–100 arbitrary values is slow (10–20s), wastes tokens, and rarely contains the entity you need. 2. **Standard `categorical` & `boolean`** — e.g. status, priority, type, gender, active flags: - **Never call `search_column_values` on them** (not indexed → 0 results). - - Use the values listed in the catalog / `get_column_profile`. `domainIsComplete: true` is definitive: the listed values are the entire value set, and any other string does not exist in the data. + - Use the values listed in the catalog. When the catalog lists all values (the domain is complete), that list is definitive: any other string does not exist in the data. - If the values aren't listed, `get_column_distinct_values` shows the full set (usually 5–20 rows). -3. **Numeric, date, timestamp or geometry columns**: use profile min/max stats, `get_sample_rows`, and casting / date parsing (see the `temporal-analyst` skill). Place names → `resolve_location_to_wkt` (see the `spatial-analyst` skill). +3. **Numeric, date, timestamp or geometry columns**: use the catalog's ranges, `get_sample_rows`, and casting / date parsing (see the `temporal-analyst` skill). Place names → `resolve_location_to_wkt` (see the `spatial-analyst` skill). 4. **Safety net**: after drafting SQL with text filters, run `enrich_sql_filters` — it re-checks and aligns the WHERE-clause text values against the database at the AST level. Resolving values yourself *and* running it is the safest pattern. @@ -63,29 +63,78 @@ The user's word is almost never the stored string — the value may be spelled d - **Use CTEs (`WITH ... AS (...)`)** — Trino handles them well, and they prevent common bugs: 1. **Prevent join fan-out**: aggregate the child table in a CTE first, then join, instead of joining raw tables and fixing counts afterwards. - 2. **Break down multi-stage logic** into named blocks (`WITH filtered AS (...), per_entity AS (...)`) instead of deeply nested subqueries. + 2. **Break down multi-stage logic** into named blocks (`WITH filtered AS (...), per_entity AS (...)`), each with one responsibility, instead of deeply nested subqueries. 3. **Window functions & ranking**: compute `ROW_NUMBER()` / `RANK() OVER (...)` in a CTE and filter on it (`WHERE rn <= 3`) in the outer query. 4. **Parsing**: parse string dates (`date_parse(...)`) or geometries once in an early CTE so the rest of the query stays clean. -- SQL uses ONLY confirmed 3-part table names: `"catalog"."schema"."table"`. +- SQL uses ONLY confirmed 3-part table names from the catalog: `"catalog"."schema"."table"`. +- **Final queries select only the columns needed** — no `SELECT *` (use `get_sample_rows` to peek at raw rows). +- **Filter early** — inside the innermost CTE. If the catalog marks a partition column (e.g. `dt`, `p_date`), always filter it in its native type to avoid full scans. - `validate_sql` — optional dry-run by Trino (syntax, names, types; reads no data). For an invalid query `execute_trino_query` fails at the same step, just as fast and with the same error, so validating first usually saves nothing — use it only to check a draft you don't want to run yet. +### Trino dialect essentials + +- **Identifiers vs strings**: double quotes for identifiers (`"catalog"."schema"."table"`, `"column"`), single quotes for string literals. Never backticks. `'column_name' = 'val'` compares two strings, not the column. +- **Integer division truncates** (`5 / 2 = 2`): for ratios and percentages use `CAST(a AS double) / NULLIF(b, 0)` or `1.0 * a / NULLIF(b, 0)` — `NULLIF` also prevents division-by-zero errors. +- **Counting**: `COUNT(*)` counts rows, `COUNT(col)` skips NULLs, `COUNT(DISTINCT col)` counts unique non-null values — count entities with `COUNT(DISTINCT id)`. `approx_distinct(x)` is a fast estimate on large tables. +- **Idioms**: `count_if(cond)` instead of `SUM(CASE WHEN cond THEN 1 ELSE 0 END)`; `max_by(val, ts)` / `min_by(val, ts)` for the latest/earliest value per entity without a window or self-join. +- **NULLs**: `IS NULL` / `IS NOT NULL`, never `= NULL`. `AVG()` ignores NULLs — if NULL means zero, `AVG(COALESCE(col, 0))`; `COALESCE(SUM(...), 0)` when an empty group should be 0. +- **GROUP BY**: every non-aggregated `SELECT` column must be grouped. For distinct ordered values use `SELECT DISTINCT col ... ORDER BY col`. +- **Top-N and ties**: for "the highest / the top", return ALL rows sharing the top value unless the user asks for exactly one — `RANK()` keeps ties; `ROW_NUMBER()` breaks them arbitrarily; `ORDER BY ... LIMIT n` for a plain top-N. +- **Joins**: every JOIN needs an explicit `ON` with keys (no cross joins). `INNER JOIN` when the relationship is guaranteed; `LEFT JOIN` for "per entity" metrics where some entities may have zero related rows; anti-join (`NOT EXISTS`, or `LEFT JOIN ... WHERE right.key IS NULL`) for entities with NO related rows — not `NOT IN (subquery)` when the key can be NULL. Trino's optimizer reorders joins when statistics exist; without them, put the large fact table on the left and the small lookup table on the right. +- **Per-entity ratios**: mind the granularity of numerator vs denominator — "orders per resident" is `COUNT(orders) / SUM(population)`, not `AVG(count_per_row)`. When the denominator comes from another table, aggregate each side in its own CTE, then join and divide. +- **Set operations**: prefer `UNION ALL`; `UNION` adds an expensive distributed de-duplication — use it only when de-duplication is required. +- **Arrays**: membership `contains(arr, 'v')`; expand with `CROSS JOIN UNNEST(arr) AS t(element)`. +- **When several logic paths seem plausible** (INNER vs LEFT JOIN, different grouping), run 2–3 variants with `LIMIT 10` and compare before choosing — don't guess. + +**Functions that do NOT exist in Trino:** + +| Do NOT write | Write in Trino instead | +|---|---| +| `ILIKE '%text%'` | `lower(col) LIKE lower('%text%')` or `regexp_like(col, '(?i)text')` | +| `DATEADD`, `DATE_SUB`, `ADDDATE` | `date_add('day', n, ts)` or `ts + INTERVAL '1' DAY` | +| `DATEDIFF(a, b)`, `TIMESTAMPDIFF` | `date_diff('day', a, b)` (unit, then start, then end) | +| `GETDATE()`, `SYSDATE` | `current_timestamp`, `now()`, `current_date` | +| `TO_DATE`, `STR_TO_DATE`, `TO_TIMESTAMP` | `date_parse`, `CAST`, `from_iso8601_timestamp` | +| `TO_CHAR`, `STRFTIME` | `format_datetime` (Joda patterns) or `date_format` (MySQL patterns) | +| `IFNULL`, `NVL`, `ISNULL` | `coalesce(a, b)` | +| `IIF`, `DECODE` | `CASE WHEN ...` or `if(cond, a, b)` | +| `TOP n` | `LIMIT n` (at the end of the query) | +| `LEN`, `CHARINDEX`, `INSTR` | `length(col)`, `strpos(col, 'sub')` | +| `MEDIAN`, `PERCENTILE_CONT` | `approx_percentile(x, 0.5)` | +| `GROUP_CONCAT`, `STRING_AGG` | `array_join(array_agg(x), ',')` | +| `array_contains(arr, val)` | `contains(arr, val)` | +| `ST_MakePoint`, `ST_GeomFromText` | `ST_Point(lon, lat)`, `ST_GeometryFromText(wkt)` | +| `ST_SetSRID`, `ST_Transform` | none needed (Trino geometry works directly on coordinates) | +| `ST_DWithin(a, b, r)` | `ST_Distance(to_spherical_geography(a), to_spherical_geography(b)) <= r` | +| `::type` (Postgres cast) | `CAST(x AS type)` | +| `INTERVAL 7 DAY` | `INTERVAL '7' DAY` (the value is a quoted string) | +| `EXTRACT(EPOCH FROM ts)` | `to_unixtime(ts)` | + --- ## Phase 5 — Execute & Diagnose - `execute_trino_query` — always LIMIT exploratory queries. -- Every tool returns `{"ok", "data", "error"}` — check `ok` first (`get_database_catalog` returns the catalog itself as plain text). For SQL failures, `error.name`, `error.type` and `error.message` are Trino's own, and `error.location` points at the offending line/column. +- Every tool returns `{"ok", "data", "error"}` — check `ok` first. For SQL failures, `error.name`, `error.type` and `error.message` are Trino's own, and `error.location` points at the offending line/column. - **Read the error before changing anything**, and make a targeted fix: -| Trino `error.name` / situation | Targeted fix | +| Trino `error.name` / message / situation | Targeted fix | |---|---| -| `SYNTAX_ERROR` | Fix the specific line only — do not redesign the query | -| `TABLE_NOT_FOUND` / `SCHEMA_NOT_FOUND` / `CATALOG_NOT_FOUND` | Re-verify the exact 3-part identifier from the catalog | -| `COLUMN_NOT_FOUND` | Re-verify the column name for that table (`get_table_columns`) | +| `SYNTAX_ERROR` (`mismatched input`, `extraneous input`) | Fix the specific line only — do not redesign. Typical causes: backticks (use `"`), `INTERVAL 1 DAY` (use `INTERVAL '1' DAY`), `::` casts | +| `TABLE_NOT_FOUND` / `SCHEMA_NOT_FOUND` / `CATALOG_NOT_FOUND` | Use the exact 3-part identifier from the catalog | +| `COLUMN_NOT_FOUND` | Re-check the column name and the table alias prefix against the catalog | | `AMBIGUOUS_NAME` | Qualify the column with its table alias | -| `TYPE_MISMATCH` | `CAST(col AS type)` — check the actual type in the profile | -| `FUNCTION_NOT_FOUND` | Check the Trino function name and argument types (e.g. `ST_GeometryFromText`, not `ST_GeomFromText`) | +| `TYPE_MISMATCH` (`Cannot apply operator: timestamp = varchar`, `varchar = integer`) | `CAST` one side, use a typed literal (`TIMESTAMP '...'`), or quote the literal | +| `FUNCTION_NOT_FOUND` (`not registered`) | A non-Trino function — see the table above | +| `FUNCTION_NOT_FOUND` (`Unexpected parameters`) | The function exists; CAST the arguments to the expected types | | `EXPRESSION_NOT_AGGREGATE` | Add the column to `GROUP BY` or wrap it in an aggregate | +| `INVALID_CAST_ARGUMENT` (`Value cannot be cast to timestamp`) | The text has `T` / `Z` or a custom format — `from_iso8601_timestamp(col)` or `date_parse(col, fmt)` | +| `INVALID_FUNCTION_ARGUMENT` (`Invalid format` in `date_parse`) | Wrong format specifiers — MySQL style, `%i` is minutes (not `%M`) | +| `INVALID_FUNCTION_ARGUMENT` (`Latitude must be between -90 and 90`) | Coordinates swapped — `ST_Point(lon, lat)`, longitude first | +| `DIVISION_BY_ZERO` | Wrap the divisor in `NULLIF(divisor, 0)` | +| `SUBQUERY_MULTIPLE_ROWS` | Aggregate or `LIMIT 1` the scalar subquery, or turn it into a JOIN | +| `EXCEEDED_*` (memory / time limits) | Narrow the time or partition range, select fewer columns, pre-aggregate in a CTE | +| Missing partition filter | Filter the partition column in its native type | | `error.type` other than `USER_ERROR` | A cluster / source-database problem, not necessarily your SQL — read the message before rewriting | | 0 rows | Investigate, in order: string filter values (re-resolve them, Phase 3) → join key formats (`get_sample_rows` on both sides) → date range logic and column type → NULLs (`get_column_profile`). Remove conditions one at a time to find the culprit | | Count ≫ expected | Fan-out JOIN — `COUNT(DISTINCT id)` or aggregate before joining | @@ -117,46 +166,35 @@ If any check fails or you're unsure, run a targeted diagnostic query. Do not gue ## Skills -Before writing SQL in an area, read its skill with `read_file`: `trino-expert` (dialect rules, joins, aggregation, error fixes), `temporal-analyst` (dates, times, Hebrew time expressions), `spatial-analyst` (locations and geometry), `semantic-validation` (verification checks and diagnostics). +Before writing SQL in these areas, read the skill with `read_file`: `temporal-analyst` (dates, times, Hebrew time expressions), `spatial-analyst` (locations and geometry), `semantic-validation` (deeper verification checks and diagnostics). --- ## Tool Reference -**Schema & Metadata** -- `get_database_catalog` — complete schema; once per conversation. -- `get_database_tables` — quick table roster with quoted identifiers. -- `get_table_columns` — columns with types, examples, profiling stats. -- `get_table_relationships` — verified foreign keys. -- `get_table_profile` / `get_column_profile` — deep stats; `domainIsComplete: true` means the listed values are the entire value set. - -**Discovery** -- `search_metadata` — search all schema entities by concept. -- `search_business_terms` — map user / domain vocabulary to database terminology. -- `search_knowledge_pairs` — prior solved examples (often reveal join paths). - -**Value Resolution** +**Values & places** - `search_column_values` — targeted value search for `large_categorical` / `large_unit_id` columns only. +- `get_column_distinct_values` — live distinct values of a low-cardinality `categorical` column (e.g. a `status` column) when the catalog doesn't list them. +- `get_column_profile` — a column's full statistics beyond the catalog: null count / ratio, top values with frequencies, string lengths, quartiles. - `resolve_location_to_wkt` — place name → area polygon (WKT) for `ST_GeometryFromText('...')`. **Execution** - `execute_trino_query` — runs SQL; on failure `error` carries Trino's own `name` / `type` / `message` / `location`. - `get_sample_rows` — peek at raw data: formats, string casing, date formats. -- `get_column_distinct_values` — live distinct values of a low-cardinality `categorical` column (e.g. a `status` column) when the catalog doesn't list them. - `validate_sql` — optional dry-run; not needed before executing. **Post-processing** - `enrich_sql_filters` — AST-level correction of text filter values. Pass only the SQL. **Delegation** -- `task` — spawn a subagent for heavy exploration (many tables or columns) without filling your own context. +- `task` — spawn a subagent for heavy, separable exploration without filling your own context. --- ## Hard Constraints - NEVER guess or assume a string filter value — resolve it (Phase 3). -- NEVER reference a table or column not confirmed in the catalog. +- NEVER reference a table or column not in the catalog. - ALWAYS use exact 3-part table names: `"catalog"."schema"."table"`. - Read-only `SELECT` / `WITH` only; ALWAYS LIMIT exploratory queries. - NEVER use `ST_GeomFromText()` — only `ST_GeometryFromText()` exists in Trino. @@ -173,7 +211,7 @@ Before writing SQL in an area, read its skill with `read_file`: `trino-expert` ( ## Final Answer -When you have the answer, stop calling other tools and finish by calling `DeepAgentAnswer` exactly once: +When you have the answer, stop calling other tools and finish by calling `submit_answer` exactly once: - `sql` — the exact final SQL you executed successfully with `execute_trino_query` (it is checked against your executions) - `explanation_he` — a brief Hebrew explanation of what the SQL does and what the result means - `assumptions` — interpretation choices you made (Hebrew) diff --git a/agent/src/deep_agent/resources.py b/agent/src/deep_agent/resources.py index 1d2f40e..ab8a258 100644 --- a/agent/src/deep_agent/resources.py +++ b/agent/src/deep_agent/resources.py @@ -25,7 +25,7 @@ SKILLS_ROUTE = "/skills/" -EXPECTED_SKILLS = frozenset({"trino-expert", "temporal-analyst", "spatial-analyst", "semantic-validation"}) +EXPECTED_SKILLS = frozenset({"temporal-analyst", "spatial-analyst", "semantic-validation"}) class DeepAgentResourceError(RuntimeError): diff --git a/agent/src/deep_agent/skills/trino-expert/SKILL.md b/agent/src/deep_agent/skills/trino-expert/SKILL.md deleted file mode 100644 index a4b3165..0000000 --- a/agent/src/deep_agent/skills/trino-expert/SKILL.md +++ /dev/null @@ -1,211 +0,0 @@ ---- -name: trino-expert -description: Trino SQL syntax rules, domain conventions, categorical filter patterns, aggregation correctness, join strategies, and systematic debugging for this database. ---- -# Trino SQL Expert Reference - -## Core Rules Checklist - -1. **Strings vs Identifiers**: Strings use single quotes `'abc'`. Identifiers with special chars or Hebrew use double quotes `"col"`. Never use backticks (\`col\`). -2. **Fully Qualified Names**: Always write full table names as given in the metadata: `"catalog"."schema"."table"`. -3. **Column Projection**: Final queries select only the columns needed — no `SELECT *` (use `get_sample_rows` to peek at raw rows). -4. **Early Filtering**: Put filters in `WHERE` as early as possible (inside the innermost CTE); always filter the partition column on large tables. -5. **Row Limits**: Always add `LIMIT` to non-aggregate exploratory queries. Use `ORDER BY` + `LIMIT` for "top N" (or `RANK()` if ties must be preserved). -6. **Integer Division Truncation**: `5 / 2 = 2`. Use `CAST(a AS double) / b` or `1.0 * a / b` for ratios and percentages. -7. **Safe Division**: Divide safely: `x / NULLIF(y, 0)` to avoid division-by-zero crashes. -8. **GROUP BY Completeness**: Every non-aggregated column in `SELECT` must be included in `GROUP BY`. -9. **No Cross Joins**: Every `JOIN` must have an explicit `ON` condition with keys. -10. **Distinct Cardinality**: Use `COUNT(DISTINCT x)` when exact is required; use `approx_distinct(x)` on large tables for speed. -11. **Case-Insensitive Matching**: Use `lower(col) LIKE lower('%text%')` or `regexp_like(col, '(?i)...')`. There is no `ILIKE`. -12. **NULL Checks**: Use `IS NULL` / `IS NOT NULL`. Never use `= NULL` or `!= NULL`. -13. **CTEs for Structure**: Use CTEs (`WITH x AS (...)`) for multi-step logic. Keep each CTE focused on a single responsibility. -14. **Strictly Read-Only**: Never write `INSERT`, `UPDATE`, `DELETE`, `DROP`, `CREATE`, `ALTER`. Read-only SELECT statements only. - -## Common Table Expressions (`WITH` Clauses) — Preferred SQL Style -- Trino has first-class, highly optimized support for CTEs (`WITH cte_name AS (...)`). -- **Always prefer CTEs over deeply nested subqueries**: - - Cleanly separates data preparation (filtering, date parsing, geometry) from final presentation. - - Aggregates child tables before joining to completely eliminate 1-to-many join fan-out. - - Enables window filtering (e.g. compute `ROW_NUMBER() / RANK() OVER (...)` in a CTE, filter `WHERE rn <= N` in the outer query). - - Makes SQL self-documenting, modular, and easy to inspect. - -## Arrays -- Check array membership: `contains(array_col, 'value')` — NEVER `array_contains()` -- Expand arrays: `CROSS JOIN UNNEST(array_col) AS t(element)` - -## Aggregations & Nulls -- **Integer Division Truncates**: `5 / 2 = 2`! When calculating ratios, percentages, or rates, integer division silently truncates to 0. - - Always cast the numerator: `CAST(a AS double) / NULLIF(b, 0)` or `1.0 * a / NULLIF(b, 0)`. - - Always divide safely with `NULLIF(y, 0)` to prevent runtime division-by-zero errors. -- **Idiomatic Conditional Counts**: Use `count_if(cond)` instead of verbose `SUM(CASE WHEN cond THEN 1 ELSE 0 END)`. - - Example: `count_if(status = 'active')` -- **Latest State Without Window / Self-Join**: Use `max_by(val, time)` or `min_by(val, time)` to find the latest value per entity: - - Example: `SELECT entity_id, max_by(status, updated_at) AS last_status, max(updated_at) AS last_at FROM t GROUP BY entity_id` -- Wrap aggregated columns: `COALESCE(col, 0)` to prevent NULL poisoning -- Count unique entities: `COUNT(DISTINCT id)` — not `COUNT(*)` -- `COUNT(*)` counts rows; `COUNT(col)` skips NULLs; `COUNT(DISTINCT col)` counts unique non-null values -- `AVG()` ignores NULLs — if NULLs mean "zero", use `AVG(COALESCE(col, 0))` - -## Dialect & Syntax Prohibitions -- **NO `ILIKE`**: Trino does NOT support `ILIKE`. Use `LOWER(col) LIKE LOWER('val')` or `regexp_like(col, '(?i)...')`. -- **NO Trailing Semicolons (`;`)**: Trino parser rejects queries ending in `;`. Never include trailing semicolons. -- **Identifier Quotes vs String Literals**: - - Double quotes `"catalog"."schema"."table"` or `"column"` are for identifiers. - - Single quotes `'string'` are for string literals. - - NEVER write `'column_name' = 'val'` — that compares two strings, not the database column! -- **Prohibited Token**: Never include the literal token `'kill'` anywhere in SQL. -- **Distinct Ordered Results**: - - To select distinct ordered values, use `SELECT DISTINCT col ... ORDER BY col`. - - Do NOT blindly add `GROUP BY
` before `ORDER BY` if there are other unaggregated columns, as Trino will throw a `GROUP BY` validation error. - -### Functions that DO NOT EXIST in Trino (Never Use) - -| Do NOT Write | Write in Trino Instead | -|---|---| -| `ILIKE '%text%'` | `LOWER(col) LIKE LOWER('%text%')` or `regexp_like(col, '(?i)text')` | -| `DATEADD`, `DATE_SUB`, `ADDDATE` | `date_add('day', n, ts)` or `ts + INTERVAL '1' DAY` | -| `DATEDIFF(a,b)`, `TIMESTAMPDIFF` | `date_diff('day', a, b)` (unit first, then start, then end) | -| `GETDATE()`, `SYSDATE`, `NOW` without () | `current_timestamp`, `now()`, `current_date` | -| `TO_DATE`, `STR_TO_DATE`, `TO_TIMESTAMP` | `date_parse`, `CAST`, `from_iso8601_timestamp` | -| `TO_CHAR`, `STRFTIME` | `format_datetime`, `date_format` | -| `IFNULL`, `NVL`, `ISNULL` | `coalesce(a, b)` | -| `IIF`, `DECODE` | `CASE WHEN ...` or `if(cond, a, b)` | -| `TOP n` | `LIMIT n` (at end of query) | -| `LEN`, `CHARINDEX`, `INSTR` | `length(col)`, `strpos(col, 'sub')` | -| `MEDIAN`, `PERCENTILE_CONT` | `approx_percentile(x, 0.5)` | -| `GROUP_CONCAT`, `STRING_AGG` | `array_join(array_agg(x), ',')` | -| `array_contains(arr, val)` | `contains(arr, val)` | -| `ST_MakePoint`, `ST_GeomFromText` | `ST_Point(lon, lat)`, `ST_GeometryFromText(wkt)` | -| `ST_SetSRID`, `ST_Transform` | None needed (Trino geometry operates directly on coordinates) | -| `ST_DWithin(a, b, r)` | `ST_Distance(to_spherical_geography(a), to_spherical_geography(b)) <= r` | -| `::type` (Postgres cast) | `CAST(x AS type)` | -| `INTERVAL 7 DAY` | `INTERVAL '7' DAY` (value must be quoted string) | -| `EXTRACT(EPOCH FROM ts)` | `to_unixtime(ts)` | - - -## Sorting & Top-N -- When querying for "the highest" or "the top", return ALL records sharing that top value — not just `LIMIT 1` — unless the user explicitly asks for a single result -- Use `RANK() OVER (ORDER BY col DESC)` when ties must be preserved -- `ROW_NUMBER()` breaks ties arbitrarily — use only when exactly one record per group is needed - -## Dates & Times -- Cast explicitly: `CAST(date_string AS DATE)`, `CAST(ts AS TIMESTAMP)` -- Use ISO 8601 strings for date literals: `DATE '2024-01-01'` -- Relative dates: `CURRENT_DATE`, `date_add('day', -N, CURRENT_DATE)`, `date_trunc('month', CURRENT_DATE)` -- Year filter: `col >= DATE '2024-01-01' AND col < DATE '2025-01-01'` (open-ended upper bound is safer than `<= '2024-12-31'` for timestamps) -- Month filter: `date_trunc('month', col) = DATE '2024-01-01'` - -## Categorical Filters — The #1 Correctness Issue -The user says "מגורים". The database stores "Residential". They are NOT the same string. - -Before writing ANY string equality filter (`WHERE col = '...'`), resolve the value by the column's `semantic_type`: -1. `categorical` / `boolean` — the values in the catalog / `get_column_profile` (`domainIsComplete: true` = the full - value set), otherwise `get_column_distinct_values`. `search_column_values` does not index these columns. -2. `large_categorical` / `large_unit_id` — `search_column_values` with the user's term finds the exact spelling. -3. After writing SQL, pass it through `enrich_sql_filters` as an automatic correctness pass. - -**Interpreting `search_column_values` results:** -- Use the `value` field from each result — that is the exact database string -- High `keyword_similarity` (close to 1.0) = good lexical match -- Low `semantic_distance` (close to 0.0) = good semantic match -- If multiple values match, find a filter or combination of filters (e.g. `col IN ('value1', 'value2', ...)` or a well-crafted LIKE) that covers all variants (unless the question targets a specific one). -- If no values match at all, the filter value may not exist in the data — investigate before writing a WHERE clause that will return 0 rows - -## Join Strategy - -### Always verify join keys before writing JOIN -- `get_sample_rows` on both sides to check that key formats match (e.g., both are integers, both use the same city_code format) -- `get_table_relationships` for known FK relationships - -### Fan-out detection (aggregation correctness) -A 1-to-many JOIN inflates row counts. `COUNT(*)` after such a join is wrong. - -Quick diagnostic: compare COUNT before and after the join: -```sql --- How many customers match? -SELECT COUNT(*) FROM "catalog"."schema"."customers" WHERE country = 'IL' - --- How many rows after JOIN? -SELECT COUNT(*) FROM "catalog"."schema"."customers" c -JOIN "catalog"."schema"."orders" o ON c.customer_id = o.customer_id -WHERE c.country = 'IL' -``` -If second > first → fan-out → use `COUNT(DISTINCT c.customer_id)` or aggregate before joining. - -### Join type selection & Distributed Execution Order -- **Join order**: Trino's cost-based optimizer reorders joins when table statistics exist. Without statistics, keep the - large fact table on the LEFT (probe side) and the small lookup table on the RIGHT (build side, may be broadcast). -- **No Cross Joins**: Every `JOIN` must have an explicit `ON` condition with matching keys. -- **INNER JOIN**: only rows that exist in both tables — use when the relationship is guaranteed. -- **LEFT JOIN**: keep all left-side rows even without a match — use for "per entity" metrics where some entities may have zero related records. -- **Anti-join** (NOT EXISTS / LEFT JOIN ... WHERE right.key IS NULL): entities with NO related records. - -### Set Operations (`UNION ALL` vs `UNION`) -- Always prefer `UNION ALL` over `UNION`. In Trino, `UNION` triggers an expensive distributed distinct/deduplication pass across all worker nodes. Only use `UNION` if deduplication across result sets is strictly required. - -### Partition Column Pruning -- If the catalog or table metadata indicates a partition column (e.g. `dt`, `date_key`, `p_date`), **always include a filter on the partition column directly in its native type** to avoid scanning entire clusters. - - -## Window Functions -```sql --- Rank within group (e.g., top 3 products per category) -ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn --- Then filter: WHERE rn <= 3 -``` - -## Zero-Row Investigation -If your query returns 0 rows unexpectedly, investigate in this order: -1. String filter values — re-resolve them by semantic type (`get_column_distinct_values` for categorical, `search_column_values` for large_categorical) -2. Join key alignment — `get_sample_rows` on both tables to verify key format matches -3. Date range logic — is the column a `DATE` or `TIMESTAMP`? Are the casts correct? -4. NULL presence — `get_column_profile` shows null_ratio; high null columns often filter everything out -5. Remove filters one by one to isolate which one eliminates all rows - -## SQL Exploration Patterns -When multiple logic paths seem plausible (INNER vs LEFT JOIN, different grouping strategies), run 2–3 variations with `LIMIT 10` and compare results to choose the correct one — don't guess. - -When schema is ambiguous, map the user's Hebrew terms to English tables/columns mentally before drafting. - -## Per-Capita / Per-Entity Patterns -Notice the granularity difference between the numerator and the denominator. For example in the question: -"orders per resident" = COUNT(orders) / SUM(population) — not AVG(count_per_row). - -When the denominator comes from a different table, aggregate it independently in a CTE, then divide: -```sql -WITH order_counts AS ( - SELECT region, COUNT(*) AS orders - FROM orders GROUP BY region -), -populations AS ( - SELECT region, SUM(population) AS pop - FROM regions GROUP BY region -) -SELECT o.region, o.orders * 1.0 / p.pop AS orders_per_resident -FROM order_counts o JOIN populations p ON o.region = p.region -``` - -## Trino Error → Fix Diagnostic Reference - -When `execute_trino_query` returns an error, consult this lookup table: - -| Error Message Contains | Cause | Corrective Action | -|---|---|---| -| `Cannot apply operator: timestamp = varchar` | Comparing timestamp to text | Convert with `TIMESTAMP '...'` literal or `CAST(varchar_col AS timestamp)`. | -| `Cannot apply operator: varchar = integer` | Column is varchar or literal is unquoted | Use `CAST(col AS integer)` / `try_cast` or quote the literal `'123'`. | -| `Value cannot be cast to timestamp` | Text has `T` / `Z` or custom format | Use `from_iso8601_timestamp(col)` for ISO format, or `date_parse(col, fmt)`. | -| `Invalid format` (in `date_parse`) | Wrong format specifiers | Trino uses MySQL codes (`%Y-%m-%d %H:%i:%s`; note `%i` for minutes, NOT `%M`). | -| `Function 'x' not registered` / `Unknown function` | Invented or non-Trino dialect function | Check "Functions that DO NOT EXIST in Trino" table above and substitute. | -| `Unexpected parameters for function x` | Wrong argument types | Cast parameters to types expected by the function. | -| `Column 'x' cannot be resolved` | Misspelled column or invalid alias | Check exact spelling in metadata profile; verify table alias prefix. | -| `Table 'x' does not exist` | Missing catalog/schema or wrong name | Use fully qualified name: `"catalog"."schema"."table"`. | -| `must be an aggregate expression or appear in GROUP BY` | Non-aggregated column in SELECT | Add the missing column to `GROUP BY` or wrap it in an aggregate function. | -| `mismatched input` / `extraneous input` | Dialect syntax error | Replace backticks with `"`, fix `INTERVAL '1' DAY` (must have quotes), remove `::`. | -| `Division by zero` | Zero denominator | Wrap divisor in `NULLIF(denominator, 0)`. | -| `Scalar sub-query has returned multiple rows` | Subquery returns >1 row | Add `LIMIT 1`, aggregate, or convert to a `JOIN`. | -| `Latitude must be between -90 and 90` | Inverted coordinate order | Coordinates swapped: use `ST_Point(lon, lat)` (longitude first). | -| `ST_Contains ... SphericalGeography` | Containment on geography | `ST_Contains` requires `geometry` (degrees). Convert with `to_geometry()`. | -| `Query exceeded per-node memory limit` | Too much data processed | Narrow the time/partition range, select fewer columns, or pre-aggregate in a CTE. | -| `Filter required on ... for at least one partition column` | Missing partition filter | Add a partition column filter in its native type (e.g. `WHERE dt = '...'`). | - - diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 71ec558..4287880 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -3,7 +3,11 @@ Every tool returns the same JSON envelope (see deep_agent.envelope): {"ok": true, "data": ..., "error": null} | {"ok": false, "data": null, "error": {"name", "message", ...}} -except get_database_catalog, whose success result is the catalog itself as plain text. + +The connection's catalog is not a tool: it is loaded for every run and shown to the model by +CatalogMiddleware (deep_agent.catalog). DEEP_AGENT_TOOLS (bottom of this file) is what the model +gets; a few metadata tools are kept here unregistered because the catalog already contains +their information. """ import logging @@ -23,7 +27,7 @@ from core.trino import execute_query_sync from deep_agent import trino_errors from deep_agent.answer import executed_query_record -from deep_agent.context import DeepAgentContext, cached_catalog, capability, connection_id, user_request +from deep_agent.context import DeepAgentContext, cached_catalog, connection_id, user_request from deep_agent.envelope import ( ENRICHMENT_ERROR, LOCATION_NOT_FOUND, @@ -39,7 +43,7 @@ # --------------------------------------------------------------------------- -# Database Catalog & Schema +# Metadata (beyond the catalog) # --------------------------------------------------------------------------- Runtime = ToolRuntime[DeepAgentContext] @@ -53,54 +57,6 @@ def _metadata_failure(what: str, exc: Exception) -> str: )) -@tool -async def get_database_catalog(runtime: Runtime = None) -> str | Command: - """ - Retrieves the complete metadata catalog and structural overview for the database. - - Use this FIRST when starting any new query to discover what tables exist, how they relate, - and to see column profiling statistics including semantic types, null ratios, and distinct counts. - - On success the result is the catalog as plain text (not JSON): Column/Table Names, Descriptions, - Types, Universal Base Metrics (Null Rate, Distinct Count, Cardinality Ratio) and specific Profiling - Data Payloads, followed by a note on which discovery sources exist for this connection. - On failure it is the usual JSON envelope with ok=false. - - Column semantic_type values to watch for: - - 'categorical' — small finite value set; values are in the catalog or via get_column_distinct_values. - - 'large_categorical' / 'large_unit_id' — too many values to enumerate; use search_column_values. - - 'geo' — WKT geometry column; use resolve_location_to_wkt to build filter values. - - Do NOT use this to fetch live data rows; this only retrieves metadata and schema definitions. - """ - try: - catalog_prompt = await get_jeen_metadata_client().get_catalog_prompt(connection_id=connection_id(runtime)) - except Exception as e: - return _metadata_failure("get_database_catalog", e) - - lower_prompt = catalog_prompt.lower() - has_kp = "(no knowledge pairs)" not in lower_prompt - has_bt = "(no business terms)" not in lower_prompt - has_fk = "(no relationships)" not in lower_prompt - - footer_lines = [ - "\n\n---", - "### Discovery Capabilities Note:", - f"- Knowledge Pairs: {'Available' if has_kp else 'None (skip search_knowledge_pairs)'}", - f"- Business Terms: {'Available' if has_bt else 'None (skip search_business_terms)'}", - f"- Foreign Keys: {'Available' if has_fk else 'None (infer joins from column names)'}", - ] - content = catalog_prompt + "\n".join(footer_lines) - if runtime is None or not runtime.tool_call_id: - return content - # Record capabilities + the raw catalog in this thread's state so later tool calls in the thread can read them. - return Command(update={ - "connection_capabilities": {"knowledge_pairs": has_kp, "business_terms": has_bt, "relationships": has_fk}, - "jeen_catalog": catalog_prompt, - "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="get_database_catalog")], - }) - - @tool async def get_database_tables(runtime: Runtime = None) -> str: """ @@ -135,11 +91,6 @@ async def get_table_relationships(runtime: Runtime = None) -> str: Returns the source-scoped foreign-key and semantic join relationships between tables. Use this to identify exact join paths and foreign key pairs. """ - if not capability(runtime, "relationships"): - return ok({ - "relationships": [], - "notice": "This connection has NO foreign key relationships defined. Infer joins using matching column names, e.g. customer_id.", - }) try: rels = await get_jeen_metadata_client().get_relationships(connection_id=connection_id(runtime)) return ok({"relationships": rels}) @@ -172,14 +123,12 @@ async def get_table_profile(table_name: str, runtime: Runtime = None) -> str: @tool async def get_column_profile(table_name: str, column_name: str, runtime: Runtime = None) -> str: """ - Retrieves the latest stored statistics for a single specific column. - - Use this before writing a WHERE clause to learn exactly how values are formatted in the database. - If 'domainIsComplete: true', the listed example values are the ENTIRE value set — any other - value can be safely ruled out. The 'semanticType' field indicates how to search the column - (e.g., categorical, large_categorical, geo). + Retrieves the full stored statistics of one column — detail the catalog does not show: + null count / ratio, top values with their frequencies, string lengths, quartiles and a histogram. - Do NOT use this for live dynamic querying of values; this reads pre-computed metadata only. + The catalog already lists each column's type, semantic_type, distinct count, range and example + values (all values when the domain is complete), so call this only when you need that extra + detail — e.g. checking NULLs when a query returns 0 rows, or a value distribution. Args: table_name (str): The fully qualified exact name of the table, e.g., '"catalog"."schema"."table"'. @@ -322,14 +271,14 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 BEST USED FOR: - Low-cardinality `categorical` columns (e.g. status, priority, category) where you want to see all - 5-20 possible valid values, and they aren't already complete in the catalog (`domainIsComplete: false`). + 5-20 possible valid values, and the catalog doesn't already list all of them. DO NOT USE FOR: - High-cardinality columns (`large_categorical`, `large_unit_id`, names, SKUs, cities). Dumping 50-100 random values from a table with thousands of entities wastes tokens and latency without finding the specific entity you need. Use `search_column_values` instead for targeted entity search. - Numeric, date, or continuous columns (checking unique values is meaningless for value matching). - - Columns where the catalog already says `domainIsComplete: true` (all values are already known). + - Columns whose values the catalog already lists in full ("values (all)"). Args: table_name (str): The fully qualified exact name of the table. @@ -425,8 +374,6 @@ async def search_business_terms(query: str, limit: int = 10, runtime: Runtime = query (str): A natural language question or phrase (multilingual support). limit (int): Maximum number of results to return. Defaults to 10. """ - if not capability(runtime, "business_terms"): - return ok({"terms": [], "notice": "This connection has NO business terms defined. Do not call this tool again."}) try: terms = await get_jeen_metadata_client().search_business_terms(query, limit, connection_id=connection_id(runtime)) return ok(terms) @@ -450,8 +397,6 @@ async def search_knowledge_pairs(query: str, limit: int = 10, runtime: Runtime = query (str): The natural language user question (multilingual/Hebrew support). limit (int): Maximum number of results to return. Defaults to 10. """ - if not capability(runtime, "knowledge_pairs"): - return ok({"pairs": [], "notice": "This connection has NO knowledge pairs defined. Do not call this tool again."}) try: pairs = await get_jeen_metadata_client().search_knowledge_pairs(query, limit, connection_id=connection_id(runtime)) return ok(pairs) @@ -649,26 +594,31 @@ def resolve_location_to_wkt(location_name: str) -> str: return ok({"location": location_name, "wkt": quoted.strip("'")}) -# The agent's full domain tool set (order = order shown to the model). +# The tools the model gets (order = order shown to the model). The catalog itself is loaded for +# every run by CatalogMiddleware, so there is no catalog tool. DEEP_AGENT_TOOLS = [ - # Discovery & Schema - get_database_catalog, - get_database_tables, - get_table_columns, - get_table_relationships, - get_table_profile, - get_column_profile, - # Search & Resolve - search_metadata, - search_business_terms, - search_knowledge_pairs, + # Values & places search_column_values, + get_column_distinct_values, + get_column_profile, resolve_location_to_wkt, - # Query Execution + # Query execution execute_trino_query, get_sample_rows, - get_column_distinct_values, validate_sql, # Post-processing enrich_sql_filters, ] + +# Implemented but not registered: the catalog already contains their information (tables, columns, +# profile stats, relationships, business terms, knowledge pairs). Register again if a connection's +# catalog grows too large to load whole, or when targeted search over those sections pays off. +UNREGISTERED_TOOLS = [ + get_database_tables, + get_table_columns, + get_table_profile, + get_table_relationships, + search_metadata, + search_business_terms, + search_knowledge_pairs, +] diff --git a/agent/tests/deep_agent/conftest.py b/agent/tests/deep_agent/conftest.py index 86a9726..78f754b 100644 --- a/agent/tests/deep_agent/conftest.py +++ b/agent/tests/deep_agent/conftest.py @@ -58,3 +58,21 @@ def _make(policy: Callable[[list[BaseMessage]], AIMessage]) -> PolicyChatModel: return model return _make + + +TEST_CATALOG = '# Database Schema\n\n## Columns\n"catalog"."schema"."orders": Orders\n - "status" (varchar) [semantic_type=categorical]' + + +@pytest.fixture(autouse=True) +def fake_catalog(monkeypatch): + """Every agent run loads the connection's catalog (CatalogMiddleware); never hit the real Jeen service in tests. + + Tests that need a specific catalog or a failure override `fake_catalog.get_catalog_prompt`. + """ + from unittest.mock import AsyncMock, MagicMock + + import deep_agent.catalog as catalog_module + + client = MagicMock(get_catalog_prompt=AsyncMock(return_value=TEST_CATALOG)) + monkeypatch.setattr(catalog_module, "get_jeen_metadata_client", lambda: client) + return client diff --git a/agent/tests/deep_agent/test_answer.py b/agent/tests/deep_agent/test_answer.py index f43563b..9a70596 100644 --- a/agent/tests/deep_agent/test_answer.py +++ b/agent/tests/deep_agent/test_answer.py @@ -7,7 +7,7 @@ from deep_agent import answer as answer_module from deep_agent import tools from deep_agent.agent import create_deep_agent -from deep_agent.answer import DeepAgentAnswer, answer_schema, normalize_sql, render_markdown, verify_answer +from deep_agent.answer import SubmitAnswer, answer_schema, normalize_sql, render_markdown, verify_answer from tests.deep_agent.conftest import system_text EXECUTED = "SELECT COUNT(DISTINCT flight_id) AS flights FROM \"postgres\".\"public\".\"flights_table\" WHERE launch_country = 'France'" @@ -24,7 +24,7 @@ def policy(messages): tool_msgs = [m for m in messages if m.type == "tool"] if not tool_msgs: return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED}, "id": "e1"}]) - return AIMessage(content, tool_calls=[{"name": "DeepAgentAnswer", "args": final_args, "id": "final"}]) + return AIMessage(content, tool_calls=[{"name": "submit_answer", "args": final_args, "id": "final"}]) return policy @@ -127,23 +127,23 @@ def test_verify_without_structured_answer(): def test_answer_schema_requires_explanation_and_confidence(): with pytest.raises(ValueError): - DeepAgentAnswer(sql="SELECT 1") + SubmitAnswer(sql="SELECT 1") def test_clarifications_are_off_by_default(): schema = answer_schema() - assert schema.__name__ == "DeepAgentAnswer" + assert schema.__name__ == "submit_answer" assert "needs_clarification" not in schema.model_fields assert schema.model_fields["sql"].is_required() # the model must always commit to a SQL answer enabled = answer_schema(True) - assert enabled.__name__ == "DeepAgentAnswer" # same tool name either way + assert enabled.__name__ == "submit_answer" # same tool name either way assert "needs_clarification" in enabled.model_fields and not enabled.model_fields["sql"].is_required() @pytest.mark.asyncio @pytest.mark.parametrize("enabled", [False, True]) async def test_clarification_only_mentioned_in_prompt_when_enabled(scripted_model, enabled): - model = scripted_model(AIMessage("", tool_calls=[{"name": "DeepAgentAnswer", "args": {**ANSWER}, "id": "f"}])) + model = scripted_model(AIMessage("", tool_calls=[{"name": "submit_answer", "args": {**ANSWER}, "id": "f"}])) agent = create_deep_agent(model=model, clarifications_enabled=enabled) with patch.object(answer_module, "execute_query_sync", return_value=_trino([[1]])): await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": f"c{enabled}"}}) @@ -156,7 +156,7 @@ async def test_matched_exploration_sample_is_re_executed_for_the_full_answer(pol def policy(messages): if not [m for m in messages if m.type == "tool"]: return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED, "limit": 5}, "id": "e1"}]) - return AIMessage("", tool_calls=[{"name": "DeepAgentAnswer", "args": ANSWER, "id": "final"}]) + return AIMessage("", tool_calls=[{"name": "submit_answer", "args": ANSWER, "id": "final"}]) sample = _trino([[i] for i in range(6)]) # 5 + 1 rows -> truncated sample full = _trino([[i] for i in range(40)]) @@ -170,8 +170,51 @@ def policy(messages): def test_re_execution_without_a_row_ceiling(monkeypatch): monkeypatch.setattr(answer_module.settings, "DEEP_AGENT_MAX_ROWS", None) - answer = DeepAgentAnswer(sql="SELECT a FROM t", explanation_he="הסבר", confidence="high") + answer = SubmitAnswer(sql="SELECT a FROM t", explanation_he="הסבר", confidence="high") with patch.object(answer_module, "execute_query_sync", return_value=_trino([[i] for i in range(500)])) as run: final = verify_answer(answer, []) assert run.call_args.args[0] == "SELECT a FROM t" # no LIMIT added assert final["executed"] is True and final["result"]["row_count"] == 500 and final["result"]["truncated"] is False + + +# ── recovery of answers written as text (gpt-oss behind the configured server) ── + +def _text_ending_policy(final_text): + def policy(messages): + if not [m for m in messages if m.type == "tool"]: + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED}, "id": "e1"}]) + return AIMessage(final_text, response_metadata={"finish_reason": "tool_calls"}) + return policy + + +@pytest.mark.asyncio +@pytest.mark.parametrize("wrap", [lambda j: j, lambda j: f"```json\n{j}\n```"], ids=["bare", "fenced"]) +async def test_answer_written_as_json_text_is_recovered(policy_model, wrap): + import json as _json + + result, _, reexec = await _run(policy_model, _text_ending_policy(wrap(_json.dumps(ANSWER, ensure_ascii=False))), + [_trino([[466]])]) + final = result["final_result"] + assert final["status"] == "matched" and final["executed"] is True + assert final["result"]["rows"] == [[466]] + assert final["recovered_from_text"] is True + reexec.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("text", [ + "סיימתי, התשובה היא 466", # prose, not an answer object + '{"sql": "SELECT 1"}', # JSON, but missing required fields + '{"explanation_he": "x", "confidence": "high"', # broken JSON +], ids=["prose", "invalid-schema", "broken-json"]) +async def test_text_that_is_not_a_valid_answer_is_not_recovered(policy_model, text): + result, _, _ = await _run(policy_model, _text_ending_policy(text), [_trino([[466]])]) + final = result["final_result"] + assert final["status"] == "no_answer" and final["executed"] is False + assert final["recovered_from_text"] is False + + +@pytest.mark.asyncio +async def test_a_real_tool_call_is_not_marked_recovered(policy_model): + result, _, _ = await _run(policy_model, _policy(ANSWER), [_trino([[466]])]) + assert result["final_result"]["recovered_from_text"] is False diff --git a/agent/tests/deep_agent/test_catalog_state.py b/agent/tests/deep_agent/test_catalog_state.py index 6ec1272..efb47d6 100644 --- a/agent/tests/deep_agent/test_catalog_state.py +++ b/agent/tests/deep_agent/test_catalog_state.py @@ -17,21 +17,17 @@ class Marker(AsyncCallbackHandler): """A caller-supplied callback handler; it must reach the enrichment LLM calls.""" -def _policy(first_tool: str): +def _policy(enrich_calls: int): def policy(messages): tool_msgs = [m for m in messages if m.type == "tool"] - steps = [first_tool, "enrich_sql_filters", "enrich_sql_filters"] if first_tool == "enrich_sql_filters" \ - else ["get_database_catalog", "enrich_sql_filters"] - if len(tool_msgs) < len(steps): - name = steps[len(tool_msgs)] - args = {"sql": DRAFT} if name == "enrich_sql_filters" else {} - return AIMessage("", tool_calls=[{"name": name, "args": args, "id": f"t{len(tool_msgs)}"}]) + if len(tool_msgs) < enrich_calls: + return AIMessage("", tool_calls=[{"name": "enrich_sql_filters", "args": {"sql": DRAFT}, "id": f"t{len(tool_msgs)}"}]) return AIMessage("done") return policy @pytest.fixture -def enrichment(): +def enrichment(fake_catalog): plan = SimpleNamespace(enrichment_details=[SimpleNamespace( changed_filter=True, column="launch_country", original_value="צרפת", refined_values=["France"], old_operator="=", new_operator="=", @@ -42,12 +38,13 @@ def enrichment(): with patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", enrich), \ patch("agent.nodes.refiner.parse_jeen_catalog_tables", parse), \ patch.object(tools, "get_jeen_metadata_client", return_value=client): - yield SimpleNamespace(enrich=enrich, parse=parse, client=client) + fake_catalog.get_catalog_prompt.return_value = CATALOG # what CatalogMiddleware loads for the run + yield SimpleNamespace(enrich=enrich, parse=parse, client=client, run_catalog=fake_catalog) @pytest.mark.asyncio -async def test_enrichment_uses_cached_catalog_question_and_parent_config(policy_model, enrichment): - agent = create_deep_agent(model=policy_model(_policy("get_database_catalog"))) +async def test_enrichment_uses_the_run_catalog_question_and_parent_config(policy_model, enrichment): + agent = create_deep_agent(model=policy_model(_policy(1))) marker = Marker() result = await agent.ainvoke( {"messages": [("user", QUESTION)]}, @@ -55,8 +52,9 @@ async def test_enrichment_uses_cached_catalog_question_and_parent_config(policy_ ) assert result["jeen_catalog"] == CATALOG - enrichment.client.get_catalog_prompt.assert_awaited_once() # fetched once, by the catalog tool - enrichment.parse.assert_called_once_with(CATALOG) # exact cached text, not a model re-typing + enrichment.run_catalog.get_catalog_prompt.assert_awaited_once() # loaded once, by CatalogMiddleware + enrichment.client.get_catalog_prompt.assert_not_awaited() # the tool never fetches it itself + enrichment.parse.assert_called_once_with(CATALOG) # exact loaded text, not a model re-typing kwargs = enrichment.enrich.await_args.kwargs assert kwargs["user_request"] == QUESTION @@ -71,13 +69,13 @@ async def test_enrichment_uses_cached_catalog_question_and_parent_config(policy_ @pytest.mark.asyncio -async def test_enrichment_before_catalog_fetches_once_and_caches(policy_model, enrichment): - agent = create_deep_agent(model=policy_model(_policy("enrich_sql_filters"))) - result = await agent.ainvoke({"messages": [("user", QUESTION)]}, {"configurable": {"thread_id": "e2"}}) +async def test_repeated_enrichment_never_refetches_the_catalog(policy_model, enrichment): + agent = create_deep_agent(model=policy_model(_policy(3))) + await agent.ainvoke({"messages": [("user", QUESTION)]}, {"configurable": {"thread_id": "e2"}}) - assert result["jeen_catalog"] == CATALOG assert enrichment.enrich.await_count == 3 - enrichment.client.get_catalog_prompt.assert_awaited_once() # later calls hit the state cache + enrichment.run_catalog.get_catalog_prompt.assert_awaited_once() + enrichment.client.get_catalog_prompt.assert_not_awaited() @pytest.mark.asyncio diff --git a/agent/tests/deep_agent/test_guidance_lint.py b/agent/tests/deep_agent/test_guidance_lint.py index 38af0c5..ac4431a 100644 --- a/agent/tests/deep_agent/test_guidance_lint.py +++ b/agent/tests/deep_agent/test_guidance_lint.py @@ -16,7 +16,7 @@ from deep_agent.tools import DEEP_AGENT_TOOLS DOMAIN_TOOLS = {t.name for t in DEEP_AGENT_TOOLS} -HARNESS_TOOLS = {"task", "write_todos", "read_file", "ls", "DeepAgentAnswer"} +HARNESS_TOOLS = {"task", "write_todos", "read_file", "ls", "submit_answer"} DOCS: dict[str, str] = { "system prompt": SYSTEM_PROMPT, diff --git a/agent/tests/deep_agent/test_latency.py b/agent/tests/deep_agent/test_latency.py index c6399ab..399f1f4 100644 --- a/agent/tests/deep_agent/test_latency.py +++ b/agent/tests/deep_agent/test_latency.py @@ -23,7 +23,7 @@ async def test_unused_builtin_tools_are_not_offered_to_the_model(scripted_model) await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "t"}}) offered = set(model.bound_tool_names[-1]) assert not offered & EXCLUDED_BUILTIN_TOOLS - assert {"read_file", "write_todos", "execute_trino_query", "DeepAgentAnswer"} <= offered + assert {"read_file", "write_todos", "execute_trino_query", "submit_answer"} <= offered # ── metadata cache ────────────────────────────────────────────────────────── @@ -187,7 +187,7 @@ def policy(messages): if not [m for m in messages if m.type == "tool"]: msg = AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": "SELECT 7 AS n"}, "id": "e"}]) else: - msg = AIMessage("", tool_calls=[{"name": "DeepAgentAnswer", "id": "f", "args": { + msg = AIMessage("", tool_calls=[{"name": "submit_answer", "id": "f", "args": { "sql": "SELECT 7 AS n", "explanation_he": "שבע", "confidence": "high"}}]) msg.usage_metadata = {"input_tokens": 100, "output_tokens": 10, "total_tokens": 110} return msg diff --git a/agent/tests/deep_agent/test_observability.py b/agent/tests/deep_agent/test_observability.py index 3cf0d7c..5c76b8c 100644 --- a/agent/tests/deep_agent/test_observability.py +++ b/agent/tests/deep_agent/test_observability.py @@ -44,7 +44,6 @@ def reaches(self, run_id, root): STEPS = [ - ("get_database_catalog", {}), ("get_sample_rows", {"table_name": '"postgres"."public"."flights_table"'}), ("execute_trino_query", {"sql": "SELECT COUNT(*) FROM flights_table WHERE launch_country = 'France'"}), ("enrich_sql_filters", {"sql": "SELECT 1 FROM flights_table WHERE launch_country = 'צרפת'"}), diff --git a/agent/tests/deep_agent/test_prompts_and_catalog.py b/agent/tests/deep_agent/test_prompts_and_catalog.py new file mode 100644 index 0000000..cb072aa --- /dev/null +++ b/agent/tests/deep_agent/test_prompts_and_catalog.py @@ -0,0 +1,194 @@ +"""Prompt registry (Langfuse-managed prompts), the deterministic catalog, and subagent state handling.""" + +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from langchain_core.messages import AIMessage + +from agent.config import settings +from deep_agent import observability, prompt_registry +from deep_agent.agent import CLARIFICATION_PROMPT, create_deep_agent +from deep_agent.catalog import CatalogLoadError +from deep_agent.context import merge_executions +from deep_agent.prompt_registry import PROMPT_KEYS, load_prompt, local_prompt +from tests.deep_agent.conftest import TEST_CATALOG, system_text + + +# ── deterministic catalog ──────────────────────────────────────────────────── + +@pytest.mark.asyncio +async def test_catalog_is_in_every_model_call_but_not_in_history(scripted_model): + model = scripted_model(AIMessage("", tool_calls=[{"name": "write_todos", "args": {"todos": []}, "id": "w"}]), + AIMessage("done")) + result = await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "c"}}) + assert len(model.seen) == 2 + assert all(TEST_CATALOG in system_text(seen) for seen in model.seen) + assert all(TEST_CATALOG not in m.text for m in result["messages"]) # never duplicated into the message history + assert "get_database_catalog" not in model.bound_tool_names[-1] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", [RuntimeError("mcp down"), ""], ids=["unreachable", "empty"]) +async def test_run_fails_clearly_without_a_catalog(scripted_model, fake_catalog, failure): + if isinstance(failure, Exception): + fake_catalog.get_catalog_prompt.side_effect = failure + else: + fake_catalog.get_catalog_prompt.return_value = failure + model = scripted_model(AIMessage("done")) + with pytest.raises(CatalogLoadError, match="catalog"): + await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "x"}}) + assert model.seen == [] # the model is never called without a catalog + + +@pytest.mark.asyncio +async def test_general_purpose_subagent_sees_the_catalog(policy_model): + def policy(messages): + roles = [m.type for m in messages] + if messages and messages[0].type == "human" and "explore" in messages[0].text: # inside the subagent + return AIMessage("subagent brief") + if "tool" not in roles: + return AIMessage("", tool_calls=[{"name": "task", "id": "t", "args": { + "description": "explore the order tables", "subagent_type": "general-purpose"}}]) + return AIMessage("done") + + model = policy_model(policy) + await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "gp"}}) + sub_calls = [seen for seen in model.seen if any(m.type == "human" and "explore" in m.text for m in seen)] + assert sub_calls, "the subagent was never called" + assert all(TEST_CATALOG in system_text(seen) for seen in sub_calls) + + +# ── subagent state round trips ─────────────────────────────────────────────── + +def test_merge_executions_is_idempotent_for_subagent_round_trips(): + a = {"query_id": "q1", "executed_sql": "SELECT 1"} + b = {"query_id": "q2", "executed_sql": "SELECT 2"} + # Subagent returns parent's history plus one new record. + assert merge_executions([a], [a, b]) == [a, b] + assert merge_executions(None, [a, a]) == [a] + + +# ── prompt registry ────────────────────────────────────────────────────────── + +def test_every_prompt_has_a_packaged_fallback(): + for key in PROMPT_KEYS: + assert local_prompt(key).strip() + + +def test_disabled_langfuse_uses_packaged_prompt(): + p = load_prompt("system") + assert p.source == "local" and p.text == local_prompt("system") and p.client is None + + +@pytest.fixture +def langfuse_enabled(monkeypatch): + monkeypatch.setattr(settings, "DEEP_AGENT_LANGFUSE_PROMPTS", True) + prompt_registry._misses.clear() + yield + prompt_registry._misses.clear() + + +def _served(text, version=3, fallback=False): + return SimpleNamespace(prompt=text, version=version, is_fallback=fallback) + + +def test_langfuse_prompt_by_label(langfuse_enabled, monkeypatch): + monkeypatch.setattr(settings, "DEEP_AGENT_PROMPT_LABEL", "staging") + fake = MagicMock(get_prompt=MagicMock(return_value=_served("served v3"))) + with patch("agent.langfuse_client.langfuse_client", fake): + p = load_prompt("system") + assert (p.source, p.text, p.version) == ("langfuse", "served v3", 3) + args, kwargs = fake.get_prompt.call_args + assert args == ("deep-agent/system",) + assert kwargs["label"] == "staging" and kwargs["fallback"] == local_prompt("system") + + +@pytest.mark.parametrize("behaviour", ["fallback", "raises"]) +def test_langfuse_unavailable_falls_back(langfuse_enabled, behaviour): + fake = MagicMock() + if behaviour == "fallback": + fake.get_prompt.return_value = _served(local_prompt("system"), version=None, fallback=True) + else: + fake.get_prompt.side_effect = RuntimeError("404 prompt not found") + with patch("agent.langfuse_client.langfuse_client", fake): + p = load_prompt("system") + assert p.source == "local" and p.text == local_prompt("system") + + +@pytest.mark.asyncio +async def test_prompt_label_change_takes_effect_without_rebuild(scripted_model, langfuse_enabled): + served = {"text": local_prompt("system")} + fake = MagicMock(get_prompt=MagicMock(side_effect=lambda *a, **k: _served(served["text"]))) + model = scripted_model(AIMessage("one"), AIMessage("two")) + with patch("agent.langfuse_client.langfuse_client", fake): + agent = create_deep_agent(model=model) + await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "p1"}}) + served["text"] = "You are the NEW deep analyst prompt v4." + await agent.ainvoke({"messages": [("user", "b")]}, {"configurable": {"thread_id": "p2"}}) + + first, second = system_text(model.seen[0]), system_text(model.seen[1]) + assert first.startswith(local_prompt("system")[:80]) + assert second.startswith("You are the NEW deep analyst prompt v4.") + assert "Skills System" in second # harness / skills sections after our prompt are preserved + assert local_prompt("system")[:80] not in second + + +def test_run_config_links_generations_to_the_prompt_version(langfuse_enabled): + client = _served("x", version=7) + with patch.object(observability, "_langfuse_handler", return_value=object()), \ + patch.object(prompt_registry, "load_prompt", + return_value=prompt_registry.LoadedPrompt("system", "x", "langfuse", 7, client)): + config = observability.build_run_config("t", tracing=True) + assert config["metadata"]["langfuse_prompt"] is client + assert config["metadata"]["prompt_version"] == 7 + assert config["metadata"]["prompt_source"] == "langfuse" + + +def test_sync_script_pushes_every_prompt_with_label(): + import importlib.util + from pathlib import Path + + path = Path(__file__).resolve().parents[2] / "scripts" / "sync_deep_agent_prompts.py" + spec = importlib.util.spec_from_file_location("sync_prompts", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + fake = MagicMock() + pushed = module.sync(fake, label="staging", dry_run=False) + assert pushed == [f"deep-agent/{k}" for k in PROMPT_KEYS] + for call, key in zip(fake.create_prompt.call_args_list, PROMPT_KEYS): + assert call.kwargs["name"] == f"deep-agent/{key}" + assert call.kwargs["prompt"] == local_prompt(key) + assert call.kwargs["labels"] == ["staging"] and call.kwargs["type"] == "text" + assert module.sync(MagicMock(), label="staging", dry_run=True) == pushed + json.dumps(pushed) + + +def test_missing_prompt_is_not_refetched_on_every_call(langfuse_enabled): + """A 404 / fallback must not cost a Langfuse round trip on every model call.""" + fake = MagicMock(get_prompt=MagicMock(return_value=_served(local_prompt("system"), version=None, fallback=True))) + with patch("agent.langfuse_client.langfuse_client", fake): + for _ in range(5): + assert load_prompt("system").source == "local" + assert fake.get_prompt.call_count == 1 + + +def test_miss_expires_after_ttl(langfuse_enabled, monkeypatch): + fake = MagicMock(get_prompt=MagicMock(side_effect=[RuntimeError("down"), _served("now served", version=2)])) + with patch("agent.langfuse_client.langfuse_client", fake): + assert load_prompt("system").source == "local" + prompt_registry._misses["system"] = 0.0 # TTL elapsed + assert load_prompt("system").text == "now served" + + +@pytest.mark.asyncio +async def test_prompt_refresh_keeps_the_clarification_suffix(scripted_model, langfuse_enabled): + fake = MagicMock(get_prompt=MagicMock(side_effect=lambda *a, **k: _served("NEW system prompt v5."))) + model = scripted_model(AIMessage("done")) + with patch("agent.langfuse_client.langfuse_client", fake): + agent = create_deep_agent(model=model, clarifications_enabled=True) + fake.get_prompt.side_effect = lambda *a, **k: _served("NEWER system prompt v6.") + await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "s"}}) + prompt = system_text(model.seen[0]) + assert prompt.startswith("NEWER system prompt v6." + CLARIFICATION_PROMPT) diff --git a/agent/tests/deep_agent/test_resources.py b/agent/tests/deep_agent/test_resources.py index 2db93bc..18a0a04 100644 --- a/agent/tests/deep_agent/test_resources.py +++ b/agent/tests/deep_agent/test_resources.py @@ -52,14 +52,14 @@ def test_missing_required_skill_fails_fast(skills_copy): def test_skill_without_frontmatter_fails_fast(skills_copy): skills = skills_copy - (skills / "trino-expert" / "SKILL.md").write_text("# no frontmatter", encoding="utf-8") + (skills / "temporal-analyst" / "SKILL.md").write_text("# no frontmatter", encoding="utf-8") with pytest.raises(DeepAgentResourceError, match="frontmatter"): discover_skills(skills) def test_skill_name_must_match_directory(skills_copy): skills = skills_copy - os.rename(skills / "trino-expert", skills / "trino") + os.rename(skills / "temporal-analyst", skills / "temporal") with pytest.raises(DeepAgentResourceError, match="must match its directory"): discover_skills(skills) @@ -77,7 +77,8 @@ async def test_skills_and_system_prompt_reach_the_model_without_memory(scripted_ for skill_md in sorted(DEFAULT_SKILLS_DIR.glob("*/SKILL.md")): description = _read_frontmatter(skill_md)["description"] assert description[:60] in prompt, f"skill {skill_md.parent.name} not loaded" - assert "## Phase 1 — Understand (Discovery)" in prompt, "system prompt file not loaded" + assert "## Phase 1 — Understand" in prompt, "system prompt file not loaded" + assert "# Database Catalog" in prompt, "connection catalog not added to the system message" assert "" not in prompt, "no AGENTS.md memory block (or its boilerplate) is expected" @@ -85,7 +86,7 @@ async def test_skills_and_system_prompt_reach_the_model_without_memory(scripted_ async def test_agent_cannot_write_skills(scripted_model): write = AIMessage("", tool_calls=[ {"name": "write_file", "args": {"file_path": "/skills/evil/SKILL.md", "content": "x"}, "id": "w1"}, - {"name": "edit_file", "args": {"file_path": "/skills/trino-expert/SKILL.md", "old_string": "Trino", "new_string": "X"}, "id": "w2"}, + {"name": "edit_file", "args": {"file_path": "/skills/temporal-analyst/SKILL.md", "old_string": "Temporal", "new_string": "X"}, "id": "w2"}, ]) model = scripted_model(write, AIMessage("done")) agent = create_deep_agent(model=model) @@ -96,17 +97,17 @@ async def test_agent_cannot_write_skills(scripted_model): for msg in tool_results: assert "denied" in msg.text.lower() or "permission" in msg.text.lower(), msg.text assert not (DEFAULT_SKILLS_DIR / "evil").exists() - assert "Trino SQL Expert Reference" in (DEFAULT_SKILLS_DIR / "trino-expert" / "SKILL.md").read_text(encoding="utf-8") + assert "Temporal SQL Reference for Trino" in (DEFAULT_SKILLS_DIR / "temporal-analyst" / "SKILL.md").read_text(encoding="utf-8") @pytest.mark.asyncio async def test_agent_can_read_a_skill_file(scripted_model): read = AIMessage("", tool_calls=[ - {"name": "read_file", "args": {"file_path": "/skills/trino-expert/SKILL.md"}, "id": "r1"}, + {"name": "read_file", "args": {"file_path": "/skills/temporal-analyst/SKILL.md"}, "id": "r1"}, ]) model = scripted_model(read, AIMessage("done")) agent = create_deep_agent(model=model) result = await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-read"}}) tool_msg = next(m for m in result["messages"] if m.type == "tool") - assert "Trino SQL Expert Reference" in tool_msg.text + assert "Temporal SQL Reference for Trino" in tool_msg.text diff --git a/agent/tests/deep_agent/test_runtime_context.py b/agent/tests/deep_agent/test_runtime_context.py index 5f4d390..9214f78 100644 --- a/agent/tests/deep_agent/test_runtime_context.py +++ b/agent/tests/deep_agent/test_runtime_context.py @@ -12,37 +12,36 @@ from deep_agent.context import DeepAgentContext, date_line from tests.deep_agent.conftest import system_text -NO_PAIRS_CATALOG = "# catalog for connection 1\n(no knowledge pairs)" -FULL_CATALOG = "# catalog for connection 2\nknowledge pairs: 3" +CATALOGS = {1: "# catalog for connection 1", 2: "# catalog for connection 2"} -def _catalog_then_pairs_policy(messages): - """Thread-local behaviour: fetch catalog, then search knowledge pairs, then answer.""" - tool_msgs = [m for m in messages if m.type == "tool"] - if not tool_msgs: - return AIMessage("", tool_calls=[{"name": "get_database_catalog", "args": {}, "id": "c1"}]) - if tool_msgs[-1].name == "get_database_catalog": - return AIMessage("", tool_calls=[{"name": "search_knowledge_pairs", "args": {"query": "כמה טיסות"}, "id": "k1"}]) +def _search_then_answer_policy(messages): + """Thread-local behaviour: one value search, then finish.""" + if not [m for m in messages if m.type == "tool"]: + return AIMessage("", tool_calls=[{"name": "search_column_values", "args": {"search_term": "Acme"}, "id": "s1"}]) return AIMessage("done") -def _metadata_client(): +def _catalog_by_connection(): async def catalog(connection_id=None): await asyncio.sleep(0.01) # force interleaving between the two requests - return NO_PAIRS_CATALOG if connection_id == 1 else FULL_CATALOG + return CATALOGS.get(connection_id, "# default connection catalog") + return AsyncMock(side_effect=catalog) - async def pairs(query, limit=10, connection_id=None): - await asyncio.sleep(0.01) - return [{"question": query, "connection": connection_id}] - return MagicMock(get_catalog_prompt=AsyncMock(side_effect=catalog), - search_knowledge_pairs=AsyncMock(side_effect=pairs)) +def _value_client(): + async def search(search_term, table=None, column=None, limit=10, raw=False, connection_id=None): + await asyncio.sleep(0.01) + return {"values": [{"value": f"{search_term} @ {connection_id}"}]} + return MagicMock(search_column_values=AsyncMock(side_effect=search)) @pytest.mark.asyncio -async def test_concurrent_requests_for_different_connections_are_isolated(policy_model): - agent = create_deep_agent(model=policy_model(_catalog_then_pairs_policy)) - client = _metadata_client() +async def test_concurrent_requests_for_different_connections_are_isolated(policy_model, fake_catalog): + model = policy_model(_search_then_answer_policy) + agent = create_deep_agent(model=model) + fake_catalog.get_catalog_prompt = _catalog_by_connection() + client = _value_client() with patch.object(tools, "get_jeen_metadata_client", return_value=client): r1, r2 = await asyncio.gather( @@ -52,28 +51,25 @@ async def test_concurrent_requests_for_different_connections_are_isolated(policy context=DeepAgentContext(connection_id=2)), ) - # Each request fetched its own catalog... - assert sorted(c.kwargs["connection_id"] for c in client.get_catalog_prompt.await_args_list) == [1, 2] - # ...capabilities landed in each thread's own state... - assert r1["connection_capabilities"]["knowledge_pairs"] is False - assert r2["connection_capabilities"]["knowledge_pairs"] is True - # ...so only connection 2 actually searched knowledge pairs, with its own connection id. - client.search_knowledge_pairs.assert_awaited_once() - assert client.search_knowledge_pairs.await_args.kwargs["connection_id"] == 2 - - pairs_1 = json.loads(next(m for m in r1["messages"] if m.type == "tool" and m.name == "search_knowledge_pairs").text) - pairs_2 = json.loads(next(m for m in r2["messages"] if m.type == "tool" and m.name == "search_knowledge_pairs").text) - assert pairs_1["data"]["pairs"] == [] and "NO knowledge pairs" in pairs_1["data"]["notice"] - assert pairs_2["data"] == [{"question": "כמה טיסות", "connection": 2}] + # Each run loaded its own connection's catalog into its own state... + assert sorted(c.kwargs["connection_id"] for c in fake_catalog.get_catalog_prompt.await_args_list) == [1, 2] + assert (r1["jeen_catalog"], r2["jeen_catalog"]) == (CATALOGS[1], CATALOGS[2]) + # ...each model call saw only its own catalog... + prompts = [system_text(seen) for seen in model.seen] + for prompt in prompts: + assert (CATALOGS[1] in prompt) != (CATALOGS[2] in prompt) + # ...and tools called the metadata service with their own connection id. + assert sorted(c.kwargs["connection_id"] for c in client.search_column_values.await_args_list) == [1, 2] + v1 = json.loads(next(m for m in r1["messages"] if m.type == "tool").text) + v2 = json.loads(next(m for m in r2["messages"] if m.type == "tool").text) + assert v1["data"]["matches"][0]["value"] == "Acme @ 1" and v2["data"]["matches"][0]["value"] == "Acme @ 2" @pytest.mark.asyncio -async def test_no_context_falls_back_to_default_connection(policy_model): - agent = create_deep_agent(model=policy_model(_catalog_then_pairs_policy)) - client = _metadata_client() - with patch.object(tools, "get_jeen_metadata_client", return_value=client): - await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "default"}}) - assert client.get_catalog_prompt.await_args.kwargs["connection_id"] is None # client uses its configured default +async def test_no_context_falls_back_to_default_connection(policy_model, fake_catalog): + agent = create_deep_agent(model=policy_model(lambda messages: AIMessage("done"))) + await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "default"}}) + assert fake_catalog.get_catalog_prompt.await_args.kwargs["connection_id"] is None # client uses its configured default class _FrozenDatetime(datetime): diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py index c82d2dd..a7a8788 100644 --- a/agent/tests/deep_agent/test_tool_contracts.py +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -9,11 +9,12 @@ from agent.utils.jeen_metadata_client import JeenMetadataClient, JeenMetadataError from core.trino import TrinoExecutionResult from deep_agent import tools -from deep_agent.tools import DEEP_AGENT_TOOLS +from deep_agent.tools import DEEP_AGENT_TOOLS, UNREGISTERED_TOOLS -# Minimal valid arguments for every tool. +ALL_TOOLS = [*DEEP_AGENT_TOOLS, *UNREGISTERED_TOOLS] + +# Minimal valid arguments for every tool (registered and unregistered — both must honour the envelope). TOOL_ARGS = { - "get_database_catalog": {}, "get_database_tables": {}, "get_table_columns": {"table_name": "t"}, "get_table_relationships": {}, @@ -63,17 +64,23 @@ def patched(request): def test_every_tool_is_covered(): - assert {t.name for t in DEEP_AGENT_TOOLS} == set(TOOL_ARGS) + assert {t.name for t in ALL_TOOLS} == set(TOOL_ARGS) + + +def test_registered_tool_set(): + """The catalog is loaded for every run (CatalogMiddleware), so there is no catalog tool, and the + tools whose information the catalog already contains are not offered to the model.""" + assert {t.name for t in DEEP_AGENT_TOOLS} == { + "search_column_values", "get_column_distinct_values", "get_column_profile", "resolve_location_to_wkt", + "execute_trino_query", "get_sample_rows", "validate_sql", "enrich_sql_filters", + } @pytest.mark.asyncio @pytest.mark.parametrize("patched", [False, True], ids=["success", "failure"], indirect=True) -@pytest.mark.parametrize("tool", DEEP_AGENT_TOOLS, ids=lambda t: t.name) +@pytest.mark.parametrize("tool", ALL_TOOLS, ids=lambda t: t.name) async def test_tool_returns_envelope(tool, patched): raw = await tool.ainvoke(TOOL_ARGS[tool.name]) - if tool.name == "get_database_catalog" and not patched: - assert raw.startswith("# catalog") # the catalog itself, as plain text - return out = json.loads(raw) assert set(out) == {"ok", "data", "error"}, raw assert out["ok"] is (not patched), raw @@ -86,15 +93,6 @@ async def test_tool_returns_envelope(tool, patched): assert "\n " not in raw, "envelope must be compact (no indentation)" -@pytest.mark.asyncio -async def test_catalog_is_plain_text_with_capabilities_note(): - client = MagicMock(get_catalog_prompt=AsyncMock(return_value='"postgres"."public"."t": desc\n(no knowledge pairs)')) - with patch.object(tools, "get_jeen_metadata_client", return_value=client): - raw = await tools.get_database_catalog.ainvoke({}) - assert raw.startswith('"postgres"."public"."t"') # quotes not JSON-escaped - assert "Knowledge Pairs: None (skip search_knowledge_pairs)" in raw - - @pytest.mark.asyncio async def test_metadata_failure_says_data_is_not_empty(): client = MagicMock(get_tables=AsyncMock(side_effect=JeenMetadataError("auth expired"))) From 903efc66b88eb50a2663a2c849b86de0b1b3d7b4 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 29 Oct 2026 11:34:54 +0200 Subject: [PATCH 18/37] feat(deep-agent): serve the deep agent behind chat_with_agent with durable threads (#43, revised) - deep_agent/service.py: process-wide agent via create_deep_agent(checkpointer=...), AsyncPostgresSaver when DEEP_AGENT_CHECKPOINT_DB_URL is set (else in-memory), Redis stream events (deep:, deep:answer), legacy response contract plus engine / verification / executed / recovered_from_text / confidence - no run timeout or best-effort answers; the caller passes timeout_s (how long it waits) and the run is cancelled then; omitted = no limit. Backend sends 290 of its 300s - answers are verified only against SQL executed in the same turn (turn_execution_start); each turn starts with the previous answer cleared; the answer object is not kept in checkpoints (only final_result plain data) - chat_with_agent: engine / user_id / timeout_s arguments, AGENT_ENGINE default, deep-* thread ids routed back to the deep agent - backend: engine passthrough, timeout_s, new response fields - core: TRINO_TIMEZONE (default Asia/Jerusalem) as the Trino session time zone Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 21 +++ agent/pyproject.toml | 2 + agent/src/agent/config.py | 3 + agent/src/agent/mcp_server.py | 43 +++++ agent/src/deep_agent/agent.py | 7 +- agent/src/deep_agent/answer.py | 28 +++- agent/src/deep_agent/context.py | 1 + agent/src/deep_agent/service.py | 194 +++++++++++++++++++++ agent/tests/deep_agent/test_service.py | 224 +++++++++++++++++++++++++ agent/uv.lock | 76 ++++++++- backend/app/routers/agent.py | 17 +- backend/tests/test_agent_engine.py | 40 +++++ core/src/core/config.py | 2 + core/src/core/trino.py | 1 + 14 files changed, 648 insertions(+), 11 deletions(-) create mode 100644 agent/src/deep_agent/service.py create mode 100644 agent/tests/deep_agent/test_service.py create mode 100644 backend/tests/test_agent_engine.py diff --git a/agent/README.md b/agent/README.md index 3d32294..b282f3b 100644 --- a/agent/README.md +++ b/agent/README.md @@ -70,3 +70,24 @@ Every deep-agent run is **one Langfuse trace** built by `deep_agent.observabilit - run-level scores: `deep-agent.model_calls`, `.tool_calls`, `.sql_executions`, `.latency_s` In Langfuse, filter traces by **tag = `deep-agent`** (save it as a view). Disable tracing with `DEEP_AGENT_TRACING_ENABLED=false`. + +### Serving the deep agent + +The UI → backend → agent path is the `chat_with_agent` MCP tool. It runs the legacy graph or the deep agent: + +| Setting / argument | Effect | +|---|---| +| `AGENT_ENGINE=legacy` (default) / `deep` | default engine for new threads | +| `engine` argument (backend `POST /api/agent/chat` body: `"engine": "deep"`) | per-request choice | +| thread id `deep-…` | resumes always go back to the deep agent (and legacy threads to the legacy graph) | +| `DEEP_AGENT_CHECKPOINT_DB_URL=postgresql://…` | durable deep-agent threads (shared by replicas, survive restarts); unset = in-memory | +| `timeout_s` argument | how long the caller waits; the run is cancelled then (a query already running finishes first). Omitted = no limit. The backend sends 290 (it waits 300). | + +The deep agent is built once per process and streams the same Redis `agent_stream:{thread_id}` events as the legacy graph +(nodes `deep:` and `deep:answer`). Responses keep the legacy contract and add `engine`, `verification` +(matched / re_executed / rejected / re_execution_failed / no_answer), `executed` (the final SQL ran and the rows are +Trino's), `recovered_from_text` and `confidence`. Each turn's answer is checked only against SQL executed in that turn. + +Clarifications are off (`DEEP_AGENT_CLARIFICATIONS_ENABLED=false`). When on, a clarification comes back as +`status: "interrupted"` with `interrupt_details.type = "hitl_escalation"` (`subtype: "clarification"`); the user's answer +is sent as `resume_value` (string or `{"feedback": ...}`). diff --git a/agent/pyproject.toml b/agent/pyproject.toml index 9b7296a..92b6ba0 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -25,6 +25,8 @@ dependencies = [ "deepagents>=0.6.12", "urllib3>=2.7.0", "pyyaml>=6.0", + "langgraph-checkpoint-postgres>=2.0", + "psycopg[binary,pool]>=3.2", ] [project.scripts] diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 2c047a1..a6092e9 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -58,6 +58,9 @@ class AgentSettings(BaseSettings): DEEP_AGENT_LANGFUSE_PROMPTS: bool = False # serve deep-agent/ prompts from Langfuse (packaged .md fallback) DEEP_AGENT_PROMPT_LABEL: str = "production" # Langfuse prompt label to serve DEEP_AGENT_PROMPT_CACHE_TTL_S: int = Field(default=60, ge=0) + # Serving (see deep_agent/service.py) + AGENT_ENGINE: Literal["legacy", "deep"] = "legacy" # default engine for chat_with_agent (per-call `engine` overrides) + DEEP_AGENT_CHECKPOINT_DB_URL: str | None = None # postgresql://... for durable deep-agent threads; unset = in-memory # ── Trino connection info for explicit catalog/schema qualification ── TRINO_CATALOG: str = "" diff --git a/agent/src/agent/mcp_server.py b/agent/src/agent/mcp_server.py index 331b014..140f5cd 100644 --- a/agent/src/agent/mcp_server.py +++ b/agent/src/agent/mcp_server.py @@ -25,6 +25,9 @@ async def chat_with_agent( active_skills: list[str] | None = None, execution_mode: str | None = None, hitl_enabled: bool = True, + engine: str | None = None, + user_id: str | None = None, + timeout_s: float | None = None, ) -> str: """Run the Text2SQL agent to answer database queries. @@ -40,7 +43,17 @@ async def chat_with_agent( 'high_quality', 'benchmark'). Overrides flag defaults for this invocation only. hitl_enabled: If False, skip all human-in-the-loop interrupts. + engine: 'legacy' (LangGraph workflow) or 'deep' (Deep Agent). Defaults to AGENT_ENGINE. + Threads started on the deep agent are routed back to it on resume. + user_id: End-user id for tracing (Deep Agent). + timeout_s: How long the caller waits (Deep Agent): the run is cancelled when it expires. + Omit for no limit. """ + if _use_deep_agent(engine, thread_id): + return json.dumps(await _deep_chat(connection_id, query, thread_id, resume_value, hitl_enabled, user_id, + timeout_s), + default=str) + thread_id = thread_id or str(uuid.uuid4()) langfuse_handler = None @@ -211,6 +224,36 @@ async def chat_with_agent( } ) +DEEP_THREAD_PREFIX = "deep-" + + +def _use_deep_agent(engine: str | None, thread_id: str | None) -> bool: + if thread_id: # a resumed thread stays on the engine that started it + return thread_id.startswith(DEEP_THREAD_PREFIX) + from agent.config import settings + + return (engine or settings.AGENT_ENGINE) == "deep" + + +async def _deep_chat(connection_id, query, thread_id, resume_value, hitl_enabled, user_id, timeout_s=None) -> dict: + from deep_agent.service import run_deep_chat + + response = await run_deep_chat( + connection_id=connection_id, + query=query, + thread_id=thread_id or f"{DEEP_THREAD_PREFIX}{uuid.uuid4()}", + resume_value=resume_value, + user_id=user_id, + timeout_s=timeout_s, + ) + if not hitl_enabled and response.get("status") == "interrupted": + # Non-interactive callers get the clarifying question as the answer instead of a pause. + question = (response.get("interrupt_details") or {}).get("reason", "") + response = {**response, "status": "completed", "summary": question, "interrupt_details": None, + "is_unanswerable": True} + return response + + @mcp.tool() async def suggest_fixes(thread_id: str, category: str) -> str: """Generate quick fix suggestions during an interruption.""" diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 5f4a090..a7760d7 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -41,7 +41,9 @@ def _general_purpose_subagent() -> dict: } -def create_deep_agent(model: BaseChatModel | None = None, clarifications_enabled: bool | None = None): +def create_deep_agent( + model: BaseChatModel | None = None, clarifications_enabled: bool | None = None, checkpointer=None +): """ Creates and returns a compiled LangGraph deep agent. @@ -51,11 +53,12 @@ def create_deep_agent(model: BaseChatModel | None = None, clarifications_enabled Args: model: Chat model override (tests); defaults to the configured LLM. clarifications_enabled: Override DEEP_AGENT_CLARIFICATIONS_ENABLED (tests). + checkpointer: Thread persistence (e.g. AsyncPostgresSaver); defaults to an in-memory saver. """ if clarifications_enabled is None: clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED llm = model or get_llm() - memory = MemorySaver() + memory = checkpointer or MemorySaver() resources = build_resources() suffix = CLARIFICATION_PROMPT if clarifications_enabled else "" system_prompt = load_prompt("system").text + suffix diff --git a/agent/src/deep_agent/answer.py b/agent/src/deep_agent/answer.py index 707a8c2..394ba1f 100644 --- a/agent/src/deep_agent/answer.py +++ b/agent/src/deep_agent/answer.py @@ -239,7 +239,7 @@ async def awrap_model_call( return self._recover(request, await handler(request)) -def _current_turn(messages: list) -> list: +def current_turn(messages: list) -> list: """Messages after the latest human message (this run's turn).""" for i in range(len(messages) - 1, -1, -1): if getattr(messages[i], "type", None) == "human": @@ -248,14 +248,29 @@ def _current_turn(messages: list) -> list: class AnswerVerificationMiddleware(AgentMiddleware): - """After the agent finishes, bind the structured answer to executed SQL and real rows.""" + """Bind each turn's structured answer to SQL executed in that turn and its real rows. + + before_agent clears the previous turn's structured answer (it would otherwise be reported + again on a turn that ends without a new one) and marks where this turn's executions start, + so an answer can only match SQL that ran in its own turn. + + after_agent keeps the answer only as plain data in final_result and drops the pydantic object: + checkpoints can't restore the dynamically built `submit_answer` class. + """ + + def before_agent(self, state, runtime) -> dict[str, Any] | None: + return {"structured_response": None, "turn_execution_start": len(state.get("executed_queries") or [])} + + async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: + return self.before_agent(state, runtime) def after_agent(self, state, runtime) -> dict[str, Any] | None: - final = verify_answer(state.get("structured_response"), state.get("executed_queries") or []) + executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + final = verify_answer(state.get("structured_response"), executed) final["recovered_from_text"] = any( - (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in _current_turn(state.get("messages") or []) + (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in current_turn(state.get("messages") or []) ) - return {"final_result": final} + return {"final_result": final, "structured_response": None} async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: return await asyncio.to_thread(self.after_agent, state, runtime) @@ -282,6 +297,9 @@ def render_markdown(final_result: dict[str, Any]) -> str: parts.append("\n".join([header, sep, *body])) if result.get("truncated"): parts.append(f"_מוצגות {result['row_count']} השורות הראשונות בלבד._") + elif final_result.get("status") == "no_answer": + reason = final_result.get("error") + parts.append("⚠️ לא התקבלה תשובה סופית" + (f": {reason}" if reason else ".")) elif final_result.get("error"): parts.append(f"⚠️ לא ניתן היה להריץ את השאילתה הסופית: {final_result['error']}") diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index 52d3f4f..3737a97 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -51,6 +51,7 @@ class DeepAgentRuntimeState(AgentState): jeen_catalog: NotRequired[str] # the connection's catalog, loaded once per run (deep_agent.catalog) executed_queries: NotRequired[Annotated[list[dict[str, Any]], merge_executions]] # successful executions final_result: NotRequired[dict[str, Any]] # verified answer + rows (see deep_agent.answer) + turn_execution_start: NotRequired[int] # index into executed_queries where the current turn began def connection_id(runtime: ToolRuntime | None) -> int | None: diff --git a/agent/src/deep_agent/service.py b/agent/src/deep_agent/service.py new file mode 100644 index 0000000..36a10b7 --- /dev/null +++ b/agent/src/deep_agent/service.py @@ -0,0 +1,194 @@ +""" +Serving the Deep Agent behind the existing `chat_with_agent` MCP tool. + +- One agent per process (built lazily, shared by all requests); per-request data travels in + DeepAgentContext (connection, user) and the thread id. +- Durable threads: AsyncPostgresSaver when DEEP_AGENT_CHECKPOINT_DB_URL is set (shared by all + replicas, survives restarts), otherwise an in-memory saver. +- Streaming: the same Redis events the legacy graph publishes (`agent_stream:{thread_id}`, + {"thread_id", "node", "status"}), so the backend SSE relay and UI work unchanged. Nodes are + named `deep:` (e.g. deep:execute_trino_query) plus `deep:answer`. +- Response: the legacy JSON contract (status / summary / sql_query / sql_explanation / + interrupt_details / trace_id / execution_path / is_unanswerable) plus `engine`, + `verification`, `executed`, `recovered_from_text` and `confidence`. +- Run limit: none by default. A caller that stops waiting after N seconds passes `timeout_s`; + the run is then cancelled at that point (no tokens spent on an answer nobody receives). +- Clarification (only with DEEP_AGENT_CLARIFICATIONS_ENABLED): an answer with needs_clarification returns status "interrupted" with + interrupt_details {"type": "hitl_escalation", "subtype": "clarification", "reason": }, + which the UI already renders as a free-text prompt. The reply (resume_value) is sent as the + next user message on the same thread. +""" + +import asyncio +import logging +import time +from typing import Any +from uuid import UUID + +from langchain_core.callbacks import AsyncCallbackHandler +from langgraph.checkpoint.memory import MemorySaver + +from agent.config import settings +from agent.utils.redis_publisher import publish_node_event +from deep_agent import observability +from deep_agent.answer import current_turn, render_markdown +from deep_agent.context import DeepAgentContext + +logger = logging.getLogger(__name__) + +_agent = None +_agent_lock: asyncio.Lock | None = None +_pg_pool = None + +UNANSWERED = {"no_answer", "rejected", "re_execution_failed"} + + +async def build_checkpointer(): + """AsyncPostgresSaver over a process-wide pool when configured, else MemorySaver.""" + global _pg_pool + if not settings.DEEP_AGENT_CHECKPOINT_DB_URL: + logger.warning("DEEP_AGENT_CHECKPOINT_DB_URL not set — deep-agent threads are in-memory (lost on restart)") + return MemorySaver() + from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver + from psycopg.rows import dict_row + from psycopg_pool import AsyncConnectionPool + + _pg_pool = AsyncConnectionPool( + settings.DEEP_AGENT_CHECKPOINT_DB_URL, open=False, max_size=10, + kwargs={"autocommit": True, "prepare_threshold": 0, "row_factory": dict_row}, + ) + await _pg_pool.open() + saver = AsyncPostgresSaver(_pg_pool) + await saver.setup() # idempotent: creates/migrates the checkpoint tables + return saver + + +async def get_deep_agent(): + """The process-wide Deep Agent (built once, on first use).""" + global _agent, _agent_lock + if _agent is not None: + return _agent + if _agent_lock is None: + _agent_lock = asyncio.Lock() + async with _agent_lock: + if _agent is None: + from deep_agent.agent import create_deep_agent + + _agent = create_deep_agent(checkpointer=await build_checkpointer()) + return _agent + + +def reset_for_tests(agent=None) -> None: + global _agent, _agent_lock + _agent, _agent_lock = agent, None + + +class StreamPublisher(AsyncCallbackHandler): + """Publishes tool start/end to the legacy Redis stream and records the execution path.""" + + def __init__(self, thread_id: str) -> None: + self.thread_id = thread_id + self.execution_path: list[str] = [] + self._names: dict[UUID, str] = {} + + async def _publish(self, node: str, status: str) -> None: + await publish_node_event(self.thread_id, node, status) + + async def on_tool_start(self, serialized, input_str, *, run_id, **kwargs) -> None: + name = f"deep:{(serialized or {}).get('name') or kwargs.get('name') or 'tool'}" + self._names[run_id] = name + self.execution_path.append(name) + await self._publish(name, "active") + + async def on_tool_end(self, output, *, run_id, **kwargs) -> None: + await self._publish(self._names.pop(run_id, "deep:tool"), "completed") + + async def on_tool_error(self, error, *, run_id, **kwargs) -> None: + await self._publish(self._names.pop(run_id, "deep:tool"), "error") + + +def to_response(thread_id: str, final_result: dict[str, Any], trace_id: str | None, + execution_path: list[str]) -> dict[str, Any]: + answer = final_result.get("answer") or {} + status = final_result.get("status", "no_answer") + base = { + "thread_id": thread_id, + "engine": "deep", + "verification": status, + "executed": bool(final_result.get("executed")), + "recovered_from_text": bool(final_result.get("recovered_from_text")), + "confidence": answer.get("confidence"), + "trace_id": trace_id, + "execution_path": execution_path, + } + if status == "clarification": + return { + **base, + "status": "interrupted", + "interrupt_details": { + "type": "hitl_escalation", + "subtype": "clarification", + "reason": answer.get("needs_clarification") or answer.get("explanation_he") or "", + }, + "sql_query": None, + } + return { + **base, + "status": "completed", + "summary": render_markdown({**final_result, "sql": None}), # SQL is returned separately + "raw_data_ref": None, + "sql_query": final_result.get("sql"), + "sql_explanation": answer.get("explanation_he"), + "is_unanswerable": status in UNANSWERED, + } + + +def _resume_text(resume_value: str | dict | None) -> str | None: + if isinstance(resume_value, str): + return resume_value + if isinstance(resume_value, dict): + return resume_value.get("feedback") or resume_value.get("answer") + return None + + +async def run_deep_chat( + *, + connection_id: int | None, + query: str | None = None, + thread_id: str, + resume_value: str | dict | None = None, + user_id: str | None = None, + timeout_s: float | None = None, + agent=None, +) -> dict[str, Any]: + """One chat turn on the Deep Agent, in the legacy chat_with_agent response shape. + + timeout_s: how long the caller will wait. The run is cancelled when it expires; None = no limit. + """ + message = query if resume_value is None else _resume_text(resume_value) + if not message: + return {"error": "Query is required for new chat session." if resume_value is None + else "resume_value must be the user's answer (a string or {'feedback': ...})."} + + agent = agent or await get_deep_agent() + context = DeepAgentContext(connection_id=connection_id, user_id=user_id) + publisher = StreamPublisher(thread_id) + config = observability.build_run_config(thread_id, user_id=user_id, connection_id=connection_id, + callbacks=[publisher]) + start = time.perf_counter() + try: + async with asyncio.timeout(timeout_s): # None = no limit + state = await agent.ainvoke({"messages": [("user", message)]}, config, context=context) + final_result = state.get("final_result") or {"status": "no_answer", "executed": False} + except TimeoutError: + logger.warning("deep agent run %s cancelled: the caller waits only %ss", thread_id, timeout_s) + state = (await agent.aget_state(config)).values + final_result = {"status": "no_answer", "executed": False, + "error": f"stopped after {timeout_s:g}s: the caller does not wait longer"} + + await publish_node_event(thread_id, "deep:answer", "completed") + trace_id = observability.langfuse_trace_id(config) + observability.score_run(trace_id, observability.run_metrics(current_turn(state.get("messages") or []), + time.perf_counter() - start, final_result)) + observability.flush() + return to_response(thread_id, final_result, trace_id, publisher.execution_path) diff --git a/agent/tests/deep_agent/test_service.py b/agent/tests/deep_agent/test_service.py new file mode 100644 index 0000000..17fb2a1 --- /dev/null +++ b/agent/tests/deep_agent/test_service.py @@ -0,0 +1,224 @@ +import json +import os +import time +import uuid +from unittest.mock import AsyncMock, patch + +import pytest +from langchain_core.messages import AIMessage + +from core.trino import TrinoExecutionResult +from deep_agent import answer, service, tools +from deep_agent.agent import create_deep_agent +from deep_agent.service import run_deep_chat, to_response + +SQL = "SELECT COUNT(*) AS orders FROM orders WHERE status = 'shipped'" +OK = TrinoExecutionResult(success=True, rows=[[466]], columns=["orders"], row_count=1, query_id="q-1") + + +def _answer(sql=SQL, **extra): + return AIMessage("", tool_calls=[{"name": "submit_answer", "id": f"f{uuid.uuid4().hex[:4]}", "args": { + "sql": sql, "explanation_he": "סופר הזמנות שנשלחו", "confidence": "high", **extra}}]) + + +def _policy(messages): + """Turn 1 asks for clarification; after the user's reply, executes and answers.""" + humans = [m for m in messages if m.type == "human"] + if len(humans) == 1: + return _answer(sql=None, needs_clarification="האם הכוונה להזמנות שנשלחו או שנמסרו?") + last_tool = next((m for m in reversed(messages) if m.type == "tool"), None) + if last_tool is None or last_tool.name == "submit_answer": + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": f"e{len(messages)}"}]) + return _answer() + + +@pytest.fixture(autouse=True) +def no_tracing(monkeypatch): + """run_deep_chat builds a real Langfuse handler when tracing is on; never send test runs upstream.""" + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_TRACING_ENABLED", False) + + +@pytest.fixture +def published(): + with patch.object(service, "publish_node_event", AsyncMock()) as pub: + yield pub + + +# ── response mapping ───────────────────────────────────────────────────────── + +def test_completed_response_matches_legacy_contract(): + final = {"status": "matched", "verified": True, "sql": SQL, "error": None, + "answer": {"explanation_he": "הסבר", "confidence": "high", "assumptions": []}, + "result": {"columns": ["orders"], "rows": [[466]], "row_count": 1, "truncated": False, "query_id": "q"}} + r = to_response("deep-1", final, "trace-1", ["deep:execute_trino_query"]) + assert r["status"] == "completed" and r["sql_query"] == SQL and r["sql_explanation"] == "הסבר" + assert "| 466 |" in r["summary"] and "```sql" not in r["summary"] # SQL is returned separately + assert r["is_unanswerable"] is False and r["engine"] == "deep" and r["verification"] == "matched" + assert r["executed"] is False and r["recovered_from_text"] is False # absent in final -> False + assert to_response("t", {**final, "executed": True, "recovered_from_text": True}, None, [])["executed"] is True + assert {"thread_id", "status", "summary", "raw_data_ref", "sql_query", "sql_explanation", "trace_id", + "execution_path", "is_unanswerable"} <= set(r) + + +@pytest.mark.parametrize("status", ["no_answer", "rejected", "re_execution_failed"]) +def test_unanswered_statuses(status): + assert to_response("t", {"status": status, "answer": None}, None, [])["is_unanswerable"] is True + + +def test_clarification_maps_to_free_text_hitl(): + r = to_response("t", {"status": "clarification", "answer": {"needs_clarification": "איזו שנה?"}}, None, []) + assert r["status"] == "interrupted" + assert r["interrupt_details"] == {"type": "hitl_escalation", "subtype": "clarification", "reason": "איזו שנה?"} + + +# ── full turns ─────────────────────────────────────────────────────────────── + +@pytest.mark.asyncio +async def test_clarify_then_resume_on_the_same_thread(policy_model, published): + agent = create_deep_agent(model=policy_model(_policy), clarifications_enabled=True) + with patch.object(tools, "execute_query_sync", return_value=OK): + first = await run_deep_chat(connection_id=89, query="כמה הזמנות נשלחו", thread_id="deep-t1", agent=agent) + second = await run_deep_chat(connection_id=89, thread_id="deep-t1", agent=agent, + resume_value={"approved": False, "feedback": "שנשלחו"}) + + assert first["status"] == "interrupted" and "שנשלחו" in first["interrupt_details"]["reason"] + assert second["status"] == "completed" and second["sql_query"] == SQL + assert second["verification"] == "matched" and second["executed"] is True and "466" in second["summary"] + assert second["execution_path"] == ["deep:execute_trino_query"] + + events = [(c.args[1], c.args[2]) for c in published.await_args_list] + assert ("deep:execute_trino_query", "active") in events and ("deep:execute_trino_query", "completed") in events + assert events[-1] == ("deep:answer", "completed") + assert all(c.args[0] == "deep-t1" for c in published.await_args_list) + + +@pytest.mark.asyncio +async def test_turn_without_new_answer_does_not_repeat_the_previous_one(scripted_model, published): + model = scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), + _answer(), + AIMessage("small talk, no answer"), + ) + agent = create_deep_agent(model=model) + with patch.object(tools, "execute_query_sync", return_value=OK): + first = await run_deep_chat(connection_id=89, query="q1", thread_id="deep-t2", agent=agent) + second = await run_deep_chat(connection_id=89, query="ותודה", thread_id="deep-t2", agent=agent) + assert first["verification"] == "matched" + assert second["verification"] == "no_answer" and second["sql_query"] is None + + +@pytest.mark.asyncio +async def test_answer_only_matches_sql_executed_in_its_own_turn(scripted_model, published): + """Turn 2 submits turn 1's SQL without running it: not 'matched' — it is re-executed to get real rows.""" + model = scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), + _answer(), + _answer(), + ) + agent = create_deep_agent(model=model) + with patch.object(tools, "execute_query_sync", return_value=OK), \ + patch.object(answer, "execute_query_sync", return_value=OK) as rerun: + first = await run_deep_chat(connection_id=89, query="q1", thread_id="deep-t3", agent=agent) + second = await run_deep_chat(connection_id=89, query="ושוב", thread_id="deep-t3", agent=agent) + assert first["verification"] == "matched" + assert second["verification"] == "re_executed" and second["executed"] is True + rerun.assert_called_once() + + +@pytest.mark.asyncio +async def test_checkpoints_hold_only_plain_data(scripted_model, published, caplog): + """The answer object isn't kept in thread state (checkpoints can't restore its class); final_result is.""" + agent = create_deep_agent(model=scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), _answer())) + with patch.object(tools, "execute_query_sync", return_value=OK): + await run_deep_chat(connection_id=89, query="q", thread_id="deep-t5", agent=agent) + state = (await agent.aget_state({"configurable": {"thread_id": "deep-t5"}})).values + assert state.get("structured_response") is None + assert state["final_result"]["answer"]["sql"] == SQL + assert "unregistered type" not in caplog.text + + +@pytest.mark.asyncio +async def test_timeout_s_cancels_the_run(scripted_model, published): + model = scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), + _answer(), + ) + agent = create_deep_agent(model=model) + + def slow_query(*args, **kwargs): + time.sleep(1.0) + return OK + + # A query already running in a worker thread can't be interrupted; the run stops there. + with patch.object(tools, "execute_query_sync", side_effect=slow_query): + r = await run_deep_chat(connection_id=89, query="q", thread_id="deep-t4", agent=agent, timeout_s=0.3) + assert r["verification"] == "no_answer" and r["executed"] is False and r["is_unanswerable"] is True + assert "stopped after 0.3s" in r["summary"] + assert model.seen and len(model.seen) == 1 # the model was never called again after the cancel + + +@pytest.mark.asyncio +async def test_missing_query_is_an_error(): + assert "error" in await run_deep_chat(connection_id=1, query=None, thread_id="deep-x", agent=object()) + assert "error" in await run_deep_chat(connection_id=1, thread_id="deep-x", resume_value={"approved": True}, + agent=object()) + + +# ── MCP tool routing ───────────────────────────────────────────────────────── + +@pytest.mark.parametrize("engine, thread_id, default, deep", [ + ("deep", None, "legacy", True), + (None, None, "deep", True), + (None, None, "legacy", False), + ("legacy", "deep-abc", "legacy", True), # a resumed deep thread stays on the deep agent + ("deep", "legacy-thread", "deep", False), # ...and a legacy thread stays legacy +]) +def test_engine_routing(engine, thread_id, default, deep, monkeypatch): + from agent import mcp_server + from agent.config import settings + + monkeypatch.setattr(settings, "AGENT_ENGINE", default) + assert mcp_server._use_deep_agent(engine, thread_id) is deep + + +@pytest.mark.asyncio +@pytest.mark.parametrize("hitl, expected_status", [(True, "interrupted"), (False, "completed")]) +async def test_chat_with_agent_deep_path(hitl, expected_status): + from agent import mcp_server + + clarification = to_response("deep-z", {"status": "clarification", "answer": {"needs_clarification": "?"}}, None, []) + with patch("deep_agent.service.run_deep_chat", AsyncMock(return_value=clarification)) as run, \ + patch.object(mcp_server.agent_graph, "ainvoke") as legacy: + raw = await mcp_server.chat_with_agent(connection_id=89, query="q", engine="deep", hitl_enabled=hitl) + out = json.loads(raw) + legacy.assert_not_called() + assert run.await_args.kwargs["thread_id"].startswith("deep-") + assert run.await_args.kwargs["timeout_s"] is None # no limit unless the caller passes one + assert out["status"] == expected_status + + +# ── durable threads (real Postgres) ────────────────────────────────────────── + +PG_URL = os.environ.get("DEEP_AGENT_TEST_PG_URL") + + +@pytest.mark.asyncio +@pytest.mark.skipif(not PG_URL, reason="set DEEP_AGENT_TEST_PG_URL to a throwaway Postgres database") +async def test_threads_survive_a_restart_with_postgres(scripted_model, monkeypatch): + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_CHECKPOINT_DB_URL", PG_URL) + thread = f"deep-durable-{uuid.uuid4().hex[:8]}" + + first_process = create_deep_agent(model=scripted_model(AIMessage("first")), checkpointer=await service.build_checkpointer()) + await first_process.ainvoke({"messages": [("user", "שאלה ראשונה")]}, {"configurable": {"thread_id": thread}}) + await service._pg_pool.close() + + # "Restart": a new agent with a new pool sees the same thread. + second_process = create_deep_agent(model=scripted_model(AIMessage("second")), checkpointer=await service.build_checkpointer()) + state = await second_process.aget_state({"configurable": {"thread_id": thread}}) + assert [m.text for m in state.values["messages"] if m.type == "human"] == ["שאלה ראשונה"] + await service._pg_pool.close() diff --git a/agent/uv.lock b/agent/uv.lock index a9409bc..aac3d5a 100644 --- a/agent/uv.lock +++ b/agent/uv.lock @@ -18,8 +18,10 @@ dependencies = [ { name = "langchain-openai" }, { name = "langfuse" }, { name = "langgraph" }, + { name = "langgraph-checkpoint-postgres" }, { name = "mcp" }, { name = "networkx" }, + { name = "psycopg", extra = ["binary", "pool"] }, { name = "pydantic-settings" }, { name = "pyyaml" }, { name = "shapely" }, @@ -51,8 +53,10 @@ requires-dist = [ { name = "langchain-openai", specifier = "==1.3.5" }, { name = "langfuse", specifier = ">=2.0.0" }, { name = "langgraph" }, + { name = "langgraph-checkpoint-postgres", specifier = ">=2.0" }, { name = "mcp", specifier = ">=1.12.4" }, { name = "networkx", specifier = ">=3.3" }, + { name = "psycopg", extras = ["binary", "pool"], specifier = ">=3.2" }, { name = "pydantic-settings", specifier = ">=2.7.0" }, { name = "pyyaml", specifier = ">=6.0" }, { name = "shapely", specifier = ">=2.0.0" }, @@ -818,15 +822,30 @@ wheels = [ [[package]] name = "langgraph-checkpoint" -version = "4.1.1" +version = "4.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "langchain-core" }, { name = "ormsgpack" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/83/47/886af6f886f0bff2273164a45f008694e48a96ff3cd25ff0228f2aa9480e/langgraph_checkpoint-4.1.1.tar.gz", hash = "sha256:6c2bdb530c91f91d7d9c1bd100925d0fc4f498d418c17f3587d1526279482a25", size = 184020, upload-time = "2026-05-22T16:57:38.503Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f0/c4/f4107f50dd07169d08d95766cd69104231e694f44a1b25b68ad8b393712d/langgraph_checkpoint-4.3.1.tar.gz", hash = "sha256:625e7c78a72b33e7c47f7e87ca051060fb90aa66f5fd551c472c08376fb669cb", size = 182679, upload-time = "2026-10-26T19:57:31.416Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/bd/b4/71425e3e38be92611300b9cc5e46a5bf98ab23f5ea8a75b73d02a2f1413c/langgraph_checkpoint-4.1.1-py3-none-any.whl", hash = "sha256:25d29144b082827218e7bc3f1e9b0566a4bb007895cd6cc26f66a8428739f56e", size = 56212, upload-time = "2026-05-22T16:57:37.203Z" }, + { url = "https://files.pythonhosted.org/packages/f3/40/4251d676b5c585d42175c901175d4bff56e22939625e18bcef781fc3e893/langgraph_checkpoint-4.3.1-py3-none-any.whl", hash = "sha256:215a826935c8db4d9676e79fd95943e5b3847d78604390898e1d98581cc594e5", size = 58093, upload-time = "2026-10-26T19:57:30.361Z" }, +] + +[[package]] +name = "langgraph-checkpoint-postgres" +version = "3.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "langgraph-checkpoint" }, + { name = "orjson" }, + { name = "psycopg" }, + { name = "psycopg-pool" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/45/28/bc0927c2770ab713edc33c4c2f87d1f7b51c344b401d7dda5c8584bd8bf8/langgraph_checkpoint_postgres-3.2.0.tar.gz", hash = "sha256:dffef0e6822d7c614019f7f2c4bdbef42859746aee2d3e6d9d9747cf3744ca90", size = 165780, upload-time = "2026-10-14T19:54:41.116Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/af/07090322c0ac00429ff7f4789b0855e72cbd3c47026ce6b8575f39cd0f9a/langgraph_checkpoint_postgres-3.2.0-py3-none-any.whl", hash = "sha256:4d89526ab3dff0c71d575233e4132327f95812deb07b6c2e75fc473525b5b8fc", size = 55937, upload-time = "2026-10-14T19:54:40.048Z" }, ] [[package]] @@ -1174,6 +1193,57 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, ] +[[package]] +name = "psycopg" +version = "3.3.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, + { name = "tzdata", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/26/3ea4ca5eaea1c0debcdf7ee7c1613fbe721dc27a03c461c0817ffd8a0601/psycopg-3.3.6.tar.gz", hash = "sha256:c081f2250df751a943036e42db6df4571c66cd0aabe8291a7a506512b12007d2", size = 168171, upload-time = "2026-09-18T13:22:55.152Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4e/de/748bd7609c71cae5d737f0ba9192f19329f70180ecda8fff3cac02c5abe3/psycopg-3.3.6-py3-none-any.whl", hash = "sha256:a1db9f7148b06a28606767efaca51fa6f9398c5c0a3810519be69d7000bdb631", size = 215490, upload-time = "2026-09-18T13:15:29.374Z" }, +] + +[package.optional-dependencies] +binary = [ + { name = "psycopg-binary", marker = "implementation_name != 'pypy'" }, +] +pool = [ + { name = "psycopg-pool" }, +] + +[[package]] +name = "psycopg-binary" +version = "3.3.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/01/2cdd1824e58b4467ee0b9498664cd28c42d8794db6b1e35b6bcb834f0044/psycopg_binary-3.3.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3f84dab25e0385692ee13274c68678377e0b1a70ab9d14e56264cbf61f60c62d", size = 4707086, upload-time = "2026-09-18T13:18:05.138Z" }, + { url = "https://files.pythonhosted.org/packages/f6/76/de9948ac06895261c84d5b9fbe283d8f3c5bc9f070691b8d9eaa1b51e322/psycopg_binary-3.3.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:612382ac3ed13651c7fa44b5fee9fbf7baaa2ddbc6f500391672682c5f1df9e0", size = 4769607, upload-time = "2026-09-18T13:18:12.83Z" }, + { url = "https://files.pythonhosted.org/packages/76/a9/72436c9915ee4905964689e7f0e182ce7767cc0a0390b3ce703be8177625/psycopg_binary-3.3.6-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:366db6e97e66b37211475f20c4c1324a2dc0dd825e46d4e87f9d599304d276f9", size = 5554134, upload-time = "2026-09-18T13:18:21.175Z" }, + { url = "https://files.pythonhosted.org/packages/0a/42/948bb3d2617795093512613fd96ba380e922992c7908fbc073858147d196/psycopg_binary-3.3.6-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1679a1cb93fbe5a6d1fd58d82cbddcc6fcb8c61446ba7cae6eb2a7b19bc585de", size = 5235723, upload-time = "2026-09-18T13:18:27.071Z" }, + { url = "https://files.pythonhosted.org/packages/99/47/93e823ff1b0088400703410939c9bda3e63ed9c850b3ee088e8769f4c10b/psycopg_binary-3.3.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:37d40450659401600e6d043ff586c89a71a69f33cbb8bcdba6cdb2569beecdbe", size = 6833587, upload-time = "2026-09-18T13:18:33.794Z" }, + { url = "https://files.pythonhosted.org/packages/5e/2d/ecc69c847795aa704041a9f5667a6b0938a088cf1853636d762a6938e493/psycopg_binary-3.3.6-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a5165300324efd5a772c48a88ab3a928513ab3979fca76553e62ee815f7b2b9c", size = 5070013, upload-time = "2026-09-18T13:18:39.628Z" }, + { url = "https://files.pythonhosted.org/packages/92/36/6126f0dac21713dcae91404f2a76da18598a6252339a8c669c46370d43b2/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d636338c8f21b0df2f84657b00bc34f9313f826ef93f1155bc743607e4a0c5eb", size = 4597367, upload-time = "2026-09-18T13:18:45.023Z" }, + { url = "https://files.pythonhosted.org/packages/4d/29/7ecfc04243b46c89ffd49924e9c5634ea904ef96c7d0f37e4073623584c1/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a4ee3bdd5468a725f2a4d9aab8a74b6d0279f768c8b5d3aeb102c5307ff3d59c", size = 4275419, upload-time = "2026-09-18T13:18:49.299Z" }, + { url = "https://files.pythonhosted.org/packages/6e/90/2f46d2e0de79706ac170df0a3637fe63c4498fc04f131f6049520b78b806/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:289aadd6a00e151203c081f708348ec89f1e483c9b510ef4ac3981f847f01f79", size = 4007358, upload-time = "2026-09-18T13:18:53.944Z" }, + { url = "https://files.pythonhosted.org/packages/03/48/6744e91291b751a8cf12d63d719977974bb94c84ceba913e7ddb2e478e51/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f21d057f3e5f5491067e5b292498073b73847d48799b099803fef100775fcc52", size = 4320156, upload-time = "2026-09-18T13:18:59.258Z" }, + { url = "https://files.pythonhosted.org/packages/1a/9b/94ff7fce53a64d5b286e2ec454e0a025cf3d6e6b4a9189bef16aa5de98b2/psycopg_binary-3.3.6-cp312-cp312-win_amd64.whl", hash = "sha256:e23a66a763fbe83fcc210bc77c27e5a5ea380ebf091c06f34d8561b695e5a40f", size = 3658864, upload-time = "2026-09-18T13:19:06.503Z" }, +] + +[[package]] +name = "psycopg-pool" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/74/5e/c0664b968b102ff68b811d999c728546c48d5c1eec03e3bbaf88c0cb4472/psycopg_pool-3.3.3.tar.gz", hash = "sha256:df87b5d9d0ad7db37f6cdad4fa8ce113d250f5997f6db38e9a99192fb67f9e1d", size = 32006, upload-time = "2026-09-22T15:53:24.947Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/b4/452c6607a0f479465cd8a9b0d9956919fcb150050c1f83f9f11e6b8ee8dc/psycopg_pool-3.3.3-py3-none-any.whl", hash = "sha256:9b9cd6a4fcec47a410f7e82d408540e7f77b478509e91b44c1a5457a13e5ff37", size = 40304, upload-time = "2026-09-22T15:53:23.712Z" }, +] + [[package]] name = "psycopg2-binary" version = "2.9.9" diff --git a/backend/app/routers/agent.py b/backend/app/routers/agent.py index 94a93b7..a3dcf38 100644 --- a/backend/app/routers/agent.py +++ b/backend/app/routers/agent.py @@ -13,6 +13,7 @@ import logging from contextlib import asynccontextmanager from datetime import datetime, timedelta +from typing import Literal import httpx import redis.asyncio as redis @@ -28,6 +29,11 @@ router = APIRouter(prefix="/agent", tags=["agent"]) +# How long /chat waits for the agent. The agent is told a little less (timeout_s) so it stops the +# run and its "stopped" response still arrives before we give up. +CHAT_TIMEOUT_S = 300.0 +AGENT_STOP_MARGIN_S = 10.0 + # --------------------------------------------------------------------------- # Schemas # --------------------------------------------------------------------------- @@ -49,6 +55,7 @@ class ChatRequest(BaseModel): execution_mode: str | None = None hitl_enabled: bool = True connection_id: int + engine: Literal["legacy", "deep"] | None = None # None -> the agent service's AGENT_ENGINE class SuggestFixesRequest(BaseModel): @@ -68,6 +75,11 @@ class ChatResponse(BaseModel): trace_id: str | None = None execution_path: list[str] | None = None is_unanswerable: bool = False + engine: str | None = None # "deep" when answered by the Deep Agent + verification: str | None = None # Deep Agent answer verification status (matched, re_executed, ...) + confidence: str | None = None # Deep Agent self-reported confidence (high / medium / low) + executed: bool | None = None # Deep Agent: the submitted final SQL ran and the rows are Trino's + recovered_from_text: bool | None = None # Deep Agent: final answer was written as text and recovered # --------------------------------------------------------------------------- @@ -119,7 +131,7 @@ async def _call_agent_mcp(tool_arguments: dict) -> dict: result = await session.call_tool( "chat_with_agent", arguments=tool_arguments, - read_timeout_seconds=timedelta(seconds=300.0), + read_timeout_seconds=timedelta(seconds=CHAT_TIMEOUT_S), ) if not result.content: @@ -209,7 +221,10 @@ async def chat(request: ChatRequest) -> ChatResponse: "extractors": request.extractors, "hitl_enabled": request.hitl_enabled, "connection_id": request.connection_id, + "timeout_s": CHAT_TIMEOUT_S - AGENT_STOP_MARGIN_S, # the deep agent stops its run then } + if request.engine is not None: # only sent when chosen, so older agent services keep working + tool_arguments["engine"] = request.engine result = await _call_agent_mcp(tool_arguments) return ChatResponse(**result) diff --git a/backend/tests/test_agent_engine.py b/backend/tests/test_agent_engine.py new file mode 100644 index 0000000..8aea2da --- /dev/null +++ b/backend/tests/test_agent_engine.py @@ -0,0 +1,40 @@ +from unittest.mock import AsyncMock, patch + +DEEP_RESPONSE = { + "thread_id": "deep-123", "status": "completed", "summary": "466 הזמנות", "sql_query": "SELECT 1", + "sql_explanation": "x", "trace_id": "t", "execution_path": ["deep:execute_trino_query"], + "is_unanswerable": False, "engine": "deep", "verification": "matched", "confidence": "high", + "executed": True, "recovered_from_text": False, +} + + +@patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, return_value=DEEP_RESPONSE) +def test_chat_forwards_engine_and_returns_verification(mock_call, client): + response = client.post("/api/agent/chat", json={"query": "כמה הזמנות", "connection_id": 89, "engine": "deep"}) + assert response.status_code == 200, response.text + assert mock_call.await_args.args[0]["engine"] == "deep" + body = response.json() + assert body["engine"] == "deep" and body["verification"] == "matched" and body["confidence"] == "high" + assert body["executed"] is True and body["recovered_from_text"] is False + + +@patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, return_value=DEEP_RESPONSE) +def test_chat_tells_the_agent_how_long_it_waits(mock_call, client): + from app.routers.agent import AGENT_STOP_MARGIN_S, CHAT_TIMEOUT_S + + client.post("/api/agent/chat", json={"query": "q", "connection_id": 89, "engine": "deep"}) + assert mock_call.await_args.args[0]["timeout_s"] == CHAT_TIMEOUT_S - AGENT_STOP_MARGIN_S < CHAT_TIMEOUT_S + + +@patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, + return_value={"thread_id": "t", "status": "completed", "summary": "ok"}) +def test_chat_omits_engine_when_not_chosen(mock_call, client): + response = client.post("/api/agent/chat", json={"query": "q", "connection_id": 89}) + assert response.status_code == 200, response.text + assert "engine" not in mock_call.await_args.args[0] + assert response.json()["engine"] is None + + +def test_chat_rejects_unknown_engine(client): + response = client.post("/api/agent/chat", json={"query": "q", "connection_id": 89, "engine": "gpt"}) + assert response.status_code == 422 diff --git a/core/src/core/config.py b/core/src/core/config.py index 5d2e3b7..7651bc5 100644 --- a/core/src/core/config.py +++ b/core/src/core/config.py @@ -17,6 +17,8 @@ class CoreSettings(BaseSettings): TRINO_SCHEMA: str = "simple_retail" TRINO_HTTP_SCHEME: str = "http" TRINO_REQUEST_TIMEOUT: float = 30.0 + # Session time zone for current_date / now(); otherwise the client sends the machine's zone (UTC in Docker). + TRINO_TIMEZONE: str = "Asia/Jerusalem" TRINO_ENABLED: bool = True TRINO_VERIFY: bool | str = False TRINO_CERT_PATH: str | None = None diff --git a/core/src/core/trino.py b/core/src/core/trino.py index edfd571..043a0d6 100644 --- a/core/src/core/trino.py +++ b/core/src/core/trino.py @@ -77,6 +77,7 @@ def get_trino_connection(): http_scheme=settings.TRINO_HTTP_SCHEME, auth=auth, request_timeout=settings.TRINO_REQUEST_TIMEOUT, + timezone=settings.TRINO_TIMEZONE, verify=settings.TRINO_VERIFY, ) From 873cb5dcb83789196c03098457bb11a42d645483 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 29 Oct 2026 12:01:18 +0200 Subject: [PATCH 19/37] chore(deep-agent): remove the benchmark (evals live in a separate repository) Removes deep_agent/benchmark.py, the deep-agent-bench command, its question set and tests. Co-Authored-By: Claude Opus 5.5 --- agent/benchmarks/deep_agent_questions.json | 42 ------ agent/pyproject.toml | 1 - agent/src/deep_agent/benchmark.py | 155 --------------------- agent/tests/deep_agent/test_latency.py | 41 +----- 4 files changed, 1 insertion(+), 238 deletions(-) delete mode 100644 agent/benchmarks/deep_agent_questions.json delete mode 100644 agent/src/deep_agent/benchmark.py diff --git a/agent/benchmarks/deep_agent_questions.json b/agent/benchmarks/deep_agent_questions.json deleted file mode 100644 index d4f9852..0000000 --- a/agent/benchmarks/deep_agent_questions.json +++ /dev/null @@ -1,42 +0,0 @@ -[ - { - "id": "q01", - "question": "כמה טיסות המריאו מצרפת" - }, - { - "id": "q02", - "question": "what cities are in the Haifa district" - }, - { - "id": "q03", - "question": "חשב את מספר התראות הטיסה לנפש עבור כל מחוז. לאחר מכן, עבור 3 המחוזות עם כמות ההתראות הגבוהה ביותר, ציין את 3 הערים הגדולות ביותר בכל מחוז על בסיס שטח הפנים שלהן." - }, - { - "id": "q04", - "question": "כמה טיסות המריאו מצרפת ונחתו בתל אביב" - }, - { - "id": "q05", - "question": "מצא את אזורי ההנחיה שבהם מדיניות הטיסה אוסרת טיסה בגובה נמוך או סוגרת את המרחב האווירי לחלוטין, ובמקביל מדיניות הנחיתה מחייבת העברה לשדה חלופי. עבור כל אזור הצג את מדיניות הטיסה, את מדיניות הנחיתה ואת מועד העדכון האחרון. מיין מהעדכון החדש ביותר לישן ביותר." - }, - { - "id": "q06", - "question": "השווה בין ערים לפי מספר ההתרעות שהתקבלו בהן במהלך יוני 2026 ביחס לגודל האוכלוסייה שלהן. הצג רק ערים שיש להן לפחות 10 התרעות בתקופה, והצג את חמש הערים עם מספר ההתרעות הגבוה ביותר לכל 10,000 תושבים. הצג גם את מספר ההתרעות ואת גודל האוכלוסייה ששימשו לחישוב." - }, - { - "id": "q07", - "question": "מצא את הערים שבהן נרשמו לפחות 5 התרעות במהלך השבועיים הראשונים של יולי 2026, אך לא נרשמה בהן אף נחיתת חירום באותה תקופה. הצג את מספר ההתרעות בכל עיר, ומיין מהמספר הגבוה לנמוך." - }, - { - "id": "q08", - "question": "עבור טיסות שהמריאו במהלך יוני 2026, מצא את אזורי ההנחיה שבהם שיעור הטיסות ארוכות הטווח גבוה מהממוצע של כלל הטיסות בתקופה. הצג את מספר הטיסות בכל אזור, מספר הטיסות ארוכות הטווח, השיעור שלהן והפער בנקודות אחוז מהממוצע הכללי. מיין לפי הפער מהגבוה לנמוך." - }, - { - "id": "q09", - "question": "זהה את עשר הרשויות שבהן היחס בין מספר האנשים השוהים במתקני האירוח לבין מספר העובדים הוא הגבוה ביותר, בתנאי שיש בהן לפחות 500 אנשים. הצג גם את מספר החדרים, את מספר האנשים לכל חדר ואת מועד העדכון של נתוני האירוח. אל תכלול רשויות שבהן מספר העובדים הוא אפס." - }, - { - "id": "q10", - "question": "עבור כל אזור הנחיה, הצג את המדיניות העדכנית ביותר הידועה, את תאריך העדכון שלה ואת מספר הטיסות ששויכו לאזור במהלך יולי 2026. הצג גם אזורים שאין להם טיסות בתקופה, וודא שאזור שמופיעות עבורו כמה גרסאות של מדיניות נספר פעם אחת בלבד." - } -] diff --git a/agent/pyproject.toml b/agent/pyproject.toml index 92b6ba0..39e132e 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -31,7 +31,6 @@ dependencies = [ [project.scripts] deep-agent = "deep_agent.cli:main" -deep-agent-bench = "deep_agent.benchmark:main" [tool.uv.sources] core = { path = "../core", editable = true } diff --git a/agent/src/deep_agent/benchmark.py b/agent/src/deep_agent/benchmark.py deleted file mode 100644 index 203ca79..0000000 --- a/agent/src/deep_agent/benchmark.py +++ /dev/null @@ -1,155 +0,0 @@ -""" -Latency / cost benchmark for the Deep Agent. - - uv run deep-agent-bench # benchmarks/deep_agent_questions.json - uv run deep-agent-bench --questions my.json --out runs/bench.json --concurrency 2 - -Reports per question and in aggregate: wall-clock latency (p50/p95), model calls, tool -calls, SQL executions, input/output tokens (from provider usage metadata) and the answer -status of the final answer (executed or not). Accuracy against gold SQL is the evaluation harness's job (#44). -""" - -import argparse -import asyncio -import json -import math -import time -import uuid -from dataclasses import asdict, dataclass -from pathlib import Path -from typing import Any - -from deep_agent import observability -from deep_agent.context import DeepAgentContext - -DEFAULT_QUESTIONS = Path(__file__).resolve().parents[2] / "benchmarks" / "deep_agent_questions.json" - - -@dataclass(frozen=True) -class QuestionRun: - id: str - question: str - latency_s: float - model_calls: int - tool_calls: int - sql_executions: int - input_tokens: int - output_tokens: int - status: str - executed: bool - error: str | None = None - - -def percentile(values: list[float], pct: float) -> float: - """Nearest-rank percentile (pct in 0–100).""" - if not values: - return 0.0 - ordered = sorted(values) - rank = max(1, math.ceil(pct / 100 * len(ordered))) - return ordered[rank - 1] - - -def _token_usage(messages: list) -> tuple[int, int]: - inp = out = 0 - for m in messages: - usage = getattr(m, "usage_metadata", None) or {} - inp += int(usage.get("input_tokens") or 0) - out += int(usage.get("output_tokens") or 0) - return inp, out - - -async def run_question(agent, item: dict[str, Any], context: DeepAgentContext) -> QuestionRun: - thread_id = f"bench_{item['id']}_{uuid.uuid4().hex[:6]}" - config = observability.build_run_config(thread_id, connection_id=context.connection_id) - start = time.perf_counter() - error = None - try: - state = await agent.ainvoke({"messages": [("user", item["question"])]}, config, context=context) - final_result = state.get("final_result") or {"status": "no_answer", "executed": False} - except Exception as exc: # one failing question must not abort the benchmark - state, final_result, error = {"messages": []}, {"status": "error", "executed": False}, repr(exc) - latency = time.perf_counter() - start - - messages = state.get("messages") or [] - metrics = observability.run_metrics(messages, latency, final_result) - observability.score_run(observability.langfuse_trace_id(config), metrics) - input_tokens, output_tokens = _token_usage(messages) - return QuestionRun( - id=item["id"], question=item["question"], latency_s=metrics.latency_s, model_calls=metrics.model_calls, - tool_calls=metrics.tool_calls, sql_executions=metrics.sql_executions, input_tokens=input_tokens, - output_tokens=output_tokens, status=final_result.get("status", "no_answer"), - executed=bool(final_result.get("executed")), error=error, - ) - - -async def run_benchmark( - agent, questions: list[dict[str, Any]], context: DeepAgentContext, concurrency: int = 1, -) -> list[QuestionRun]: - sem = asyncio.Semaphore(max(1, concurrency)) - - async def one(item): - async with sem: - return await run_question(agent, item, context) - - return list(await asyncio.gather(*(one(q) for q in questions))) - - -def summarize(runs: list[QuestionRun]) -> dict[str, Any]: - n = len(runs) or 1 - latencies = [r.latency_s for r in runs] - return { - "questions": len(runs), - "latency_p50_s": round(percentile(latencies, 50), 2), - "latency_p95_s": round(percentile(latencies, 95), 2), - "avg_model_calls": round(sum(r.model_calls for r in runs) / n, 2), - "avg_tool_calls": round(sum(r.tool_calls for r in runs) / n, 2), - "avg_sql_executions": round(sum(r.sql_executions for r in runs) / n, 2), - "avg_input_tokens": round(sum(r.input_tokens for r in runs) / n), - "avg_output_tokens": round(sum(r.output_tokens for r in runs) / n), - "executed_rate": round(sum(r.executed for r in runs) / n, 3), - "errors": sum(1 for r in runs if r.error), - } - - -def _print_report(runs: list[QuestionRun], summary: dict[str, Any]) -> None: - print(f"{'id':5} {'latency':>8} {'model':>6} {'tools':>6} {'sql':>4} {'in_tok':>8} {'out_tok':>8} status") - for r in runs: - print(f"{r.id:5} {r.latency_s:8.2f} {r.model_calls:6d} {r.tool_calls:6d} {r.sql_executions:4d} " - f"{r.input_tokens:8d} {r.output_tokens:8d} {r.status}{' (' + r.error + ')' if r.error else ''}") - print(json.dumps(summary, indent=2)) - - -def main() -> None: - parser = argparse.ArgumentParser(description="Benchmark Deep Agent latency and cost.") - parser.add_argument("--questions", type=Path, default=DEFAULT_QUESTIONS) - parser.add_argument("--connection-id", type=int, default=None) - parser.add_argument("--concurrency", type=int, default=1) - parser.add_argument("--out", type=Path, default=None, help="Write per-question results + summary as JSON.") - args = parser.parse_args() - - from agent.utils.jeen_metadata_client import close_mcp_sessions - from deep_agent.agent import create_deep_agent - - questions = json.loads(args.questions.read_text(encoding="utf-8")) - - async def _run(): - try: - return await run_benchmark(create_deep_agent(), questions, DeepAgentContext(connection_id=args.connection_id), - concurrency=args.concurrency) - finally: - await close_mcp_sessions() - - try: - runs = asyncio.run(_run()) - finally: - observability.flush() - summary = summarize(runs) - _print_report(runs, summary) - if args.out: - args.out.parent.mkdir(parents=True, exist_ok=True) - args.out.write_text(json.dumps({"summary": summary, "runs": [asdict(r) for r in runs]}, - ensure_ascii=False, indent=2), encoding="utf-8") - - -if __name__ == "__main__": - main() diff --git a/agent/tests/deep_agent/test_latency.py b/agent/tests/deep_agent/test_latency.py index 399f1f4..ec59068 100644 --- a/agent/tests/deep_agent/test_latency.py +++ b/agent/tests/deep_agent/test_latency.py @@ -10,7 +10,7 @@ from agent.config import settings from agent.utils.jeen_metadata_client import JeenMetadataClient, JeenMetadataError, close_mcp_sessions from core.trino import TrinoExecutionResult -from deep_agent import benchmark, tools +from deep_agent import tools from deep_agent.agent import create_deep_agent from deep_agent.tool_filter import EXCLUDED_BUILTIN_TOOLS @@ -171,42 +171,3 @@ def test_default_execution_still_opens_and_closes_a_connection(monkeypatch): with patch.object(core_trino, "get_trino_connection", return_value=conn): core_trino.execute_query_sync("SELECT 1") conn.close.assert_called_once() - - -# ── benchmark ─────────────────────────────────────────────────────────────── - -def test_percentile_nearest_rank(): - assert benchmark.percentile([5, 1, 3, 2, 4], 50) == 3 - assert benchmark.percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 95) == 10 - assert benchmark.percentile([], 95) == 0.0 - - -@pytest.mark.asyncio -async def test_benchmark_reports_calls_tokens_and_status(policy_model): - def policy(messages): - if not [m for m in messages if m.type == "tool"]: - msg = AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": "SELECT 7 AS n"}, "id": "e"}]) - else: - msg = AIMessage("", tool_calls=[{"name": "submit_answer", "id": "f", "args": { - "sql": "SELECT 7 AS n", "explanation_he": "שבע", "confidence": "high"}}]) - msg.usage_metadata = {"input_tokens": 100, "output_tokens": 10, "total_tokens": 110} - return msg - - agent = create_deep_agent(model=policy_model(policy)) - with patch.object(tools, "execute_query_sync", return_value=OK): - runs = await benchmark.run_benchmark(agent, [{"id": "q1", "question": "a"}, {"id": "q2", "question": "b"}], - benchmark.DeepAgentContext(), concurrency=2) - assert [r.status for r in runs] == ["matched", "matched"] - assert all(r.model_calls == 2 and r.sql_executions == 1 and r.input_tokens == 200 and r.output_tokens == 20 - for r in runs) - summary = benchmark.summarize(runs) - assert summary["questions"] == 2 and summary["executed_rate"] == 1.0 and summary["errors"] == 0 - - -def test_benchmark_question_set_is_valid(): - import json - - questions = json.loads(benchmark.DEFAULT_QUESTIONS.read_text(encoding="utf-8")) - assert len(questions) >= 10 - assert len({q["id"] for q in questions}) == len(questions) - assert all(q["question"].strip() for q in questions) From 1dd53e76ce687027ad6af5cd9f749e983b3e632b Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 29 Oct 2026 15:57:58 +0200 Subject: [PATCH 20/37] fix(deep-agent): search_column_values says when the match limit was hit It returned at most `limit` matches (default 10) while promising "every matching value", with nothing saying the list was cut. It now documents "up to `limit`" and returns `limit_reached` plus a notice to call again with a higher limit. Co-Authored-By: Claude Opus 5.5 --- .../skills/semantic-validation/SKILL.md | 143 ------------------ agent/src/deep_agent/tools.py | 14 +- agent/tests/deep_agent/test_tool_contracts.py | 8 + 3 files changed, 20 insertions(+), 145 deletions(-) delete mode 100644 agent/src/deep_agent/skills/semantic-validation/SKILL.md diff --git a/agent/src/deep_agent/skills/semantic-validation/SKILL.md b/agent/src/deep_agent/skills/semantic-validation/SKILL.md deleted file mode 100644 index d4d2707..0000000 --- a/agent/src/deep_agent/skills/semantic-validation/SKILL.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -name: semantic-validation -description: Semantic correctness checks for Text-to-SQL — use when a query has executed successfully but you need to verify it actually answers the user's intent, especially for aggregations, joins, and complex conditions. ---- -# Semantic Validation Reference - -## When to apply semantic validation - -Apply at least a mental checklist — and targeted diagnostic queries — when: -- The query uses **JOINs** (risk: fan-out multiplication) -- The query uses **aggregations**: `COUNT`, `SUM`, `AVG`, `MIN`, `MAX` -- The question asks for **"per X"** metrics (risk: wrong grouping unit) -- The question uses **"most"**, **"top N"**, **"highest"**, **"total"** -- The filter involves **dates, ranges, or boundaries** -- The result is **0 rows** or an **unexpectedly round/large number** -- The question involves **"customers/entities with NO related records"** (anti-join risk) - ---- - -## The Output Grain Test - -Before writing SQL, answer: **What does one output row represent?** - -Match this to the user's question: -- "כמה X היו בY?" → one row = COUNT of X (scalar) -- "מה X עשו בY?" → one row = (metric, X) pair -- "הכי הרבה X ב-Y" → one row = (X, metric) pair -- "X לנפש" → one row = (entity, per-capita metric) - -If the grain is wrong, every aggregation in the query is suspect. - ---- - -## Join Fan-Out Check (Critical for aggregations) - -A JOIN on a 1-to-many relationship **multiplies rows**. `COUNT(*)` after such a join counts inflated rows, not entities. - -**The diagnostic**: After joining, verify the row count on each side independently. - -```sql --- Step 1: count entities in the left table -SELECT COUNT(*) FROM "catalog"."schema"."left_table" -WHERE ; - --- Step 2: count rows after the JOIN -SELECT COUNT(*) FROM "catalog"."schema"."left_table" l -JOIN "catalog"."schema"."right_table" r ON l.id = r.left_id -WHERE ; -``` - -If Step 2 > Step 1, rows are being duplicated. Fix options: -- Use `COUNT(DISTINCT l.id)` instead of `COUNT(*)` -- Use a subquery/CTE to aggregate first, then join -- Join on a truly unique key - -**Example pattern:** -```sql --- WRONG: counts order rows, not customers -SELECT COUNT(*) FROM customers c JOIN orders o ON c.id = o.customer_id - --- CORRECT: count distinct customers that have orders -SELECT COUNT(DISTINCT c.id) FROM customers c JOIN orders o ON c.id = o.customer_id -``` - ---- - -## Aggregation Semantics - -| User says | Probably means | Watch out for | -|-----------|----------------|----------------| -| "כמה" (how many) | COUNT of entities | COUNT(*) after 1-to-many join | -| "ממוצע" (average) | AVG() | Is it avg-of-averages vs avg-of-rows? | -| "סה"כ" (total) | SUM() | NULL rows excluded from SUM | -| "הגבוה ביותר" (highest) | MAX() or ORDER BY ... LIMIT 1 | Ties — should you return all? | -| "לנפש" (per capita/person) | division by count | Division by zero on NULL | -| "לפי X" (by X) | GROUP BY X | Did you group at the right grain? | - ---- - -## Filter Boundary Checks - -Date/time ranges: -- **"בחודש ינואר"** → `BETWEEN '2024-01-01' AND '2024-01-31'` or `date_trunc('month', col) = DATE '2024-01-01'` -- **"ב-2023"** → `YEAR(col) = 2023` or `col >= DATE '2023-01-01' AND col < DATE '2024-01-01'` -- Check if the column is `DATE` or `TIMESTAMP` — compare types matter - -Categorical filters: -- After `search_column_values`, use the **exact string returned** — never modify it -- If `LIKE` is necessary (large_categorical prefix pattern), use `LIKE 'Tel Aviv%'` not `LIKE '%Tel Aviv%'` unless you need interior match - ---- - -## Anti-join Patterns (entities with NO related records) - -```sql --- CORRECT: entities with no matching records -SELECT c.id FROM customers c -WHERE NOT EXISTS ( - SELECT 1 FROM orders o WHERE o.customer_id = c.id -) - --- ALSO CORRECT (but watch for NULL-join behavior) -SELECT c.id FROM customers c -LEFT JOIN orders o ON o.customer_id = c.id -WHERE o.id IS NULL -``` - -Do NOT use `c.id NOT IN (SELECT customer_id FROM orders)` if `customer_id` can be NULL — this returns 0 rows when any NULL exists. - ---- - -## The Intent-Preservation Quick-Check - -Before finalizing the response, mentally translate your SQL back to plain language and compare filter-by-filter to the user's question: - -1. Does each WHERE clause correspond to a condition the user mentioned? -2. Did you include a condition that the user did NOT mention? -3. Is the GROUP BY at the right entity level? -4. Does the SELECT list include what the user asked for (and nothing unasked)? -5. Are ties handled (RANK vs ROW_NUMBER vs LIMIT)? - -If any answer is "no" or "unsure" — revise the SQL before executing. - ---- - -## When results are suspicious — diagnostic queries - -**0 rows returned:** -1. Strip WHERE clauses one at a time to find which one eliminates all rows -2. Re-resolve every string filter you wrote by semantic type (`get_column_distinct_values` for categorical, `search_column_values` for large_categorical) -3. Sample the join keys: `get_sample_rows` on both sides — do the key formats match? - -**Count too high (round number like 10000 or identical to table size):** -1. Run `SELECT COUNT(*) FROM table` — if equal, your WHERE clause may be doing nothing -2. Check for Cartesian product: does the JOIN have a proper ON condition? - -**Count too low (0 or 1 when many are expected):** -1. Check for strict INNER JOIN when LEFT JOIN is needed -2. Check for NULL key: `WHERE key IS NOT NULL` accidentally excluded nulls? - -**Average looks wrong:** -1. Compare with a manual spot-check: `SELECT col FROM table WHERE condition LIMIT 10` -2. Verify the denominator: are you dividing by count of rows or count of entities? diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py index 4287880..ca74e68 100644 --- a/agent/src/deep_agent/tools.py +++ b/agent/src/deep_agent/tools.py @@ -447,9 +447,11 @@ async def search_column_values( (e.g., finding 'Acme Corporation LLC' from 'Acme Corp', or the stored spelling of a Hebrew term). Multilingual, keyword, and vector search finds the exact database spelling. - Returns data.matches — every matching value (use each 'value' verbatim in SQL) with: + Returns data.matches — up to `limit` matching values (use each 'value' verbatim in SQL) with: - 'keyword_similarity' close to 1.0 = strong lexical match - 'semantic_distance' close to 0.0 = strong semantic match + data.limit_reached is true when exactly `limit` matches came back: there may be more — call again + with a higher `limit` before filtering on the list. Args: search_term (str): The specific value to look for (partial or full string, Hebrew or English). @@ -467,10 +469,18 @@ async def search_column_values( values = (res.get("values") or []) if isinstance(res, dict) else [] matches = [_value_match(v) for v in values] + limit_reached = len(matches) >= limit + if not matches: + notice = "No matches — the value may not exist in this column, or the column is not indexed (only large_categorical / large_unit_id are)." + elif limit_reached: + notice = f"Returned the first {limit} matches (the limit); there may be more — call again with a higher limit." + else: + notice = None return ok({ "search_term": search_term, "matches": matches, - "notice": None if matches else "No matches — the value may not exist in this column, or the column is not indexed (only large_categorical / large_unit_id are).", + "limit_reached": limit_reached, + "notice": notice, }) diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py index a7a8788..e7da654 100644 --- a/agent/tests/deep_agent/test_tool_contracts.py +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -163,6 +163,14 @@ async def test_search_values_returns_every_match_without_prefix_guessing(): assert "prefix_pattern" not in out["data"] +@pytest.mark.asyncio +async def test_search_values_says_when_the_limit_was_hit(): + full = await _search([{"value": f"v{i}"} for i in range(10)]) # default limit 10 + assert full["data"]["limit_reached"] is True and "higher limit" in full["data"]["notice"] + fewer = await _search([{"value": "v1"}, {"value": "v2"}]) + assert fewer["data"]["limit_reached"] is False and fewer["data"]["notice"] is None + + @pytest.mark.asyncio async def test_search_values_passes_limit_through_unclamped(): client = MagicMock(search_column_values=AsyncMock(return_value={"values": []})) From 15473ec32fc104ca8730fb13c0dbcff0d2cf5737 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 29 Oct 2026 15:57:58 +0200 Subject: [PATCH 21/37] feat(deep-agent): independent semantic reviewer (always by default) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - deep_agent/validator.py: a reviewer agent with a fresh context (user's messages, SQL, rows, assumptions, catalog — not the main agent's reasoning), read-only diagnostic tools and a submit_verdict (pass / fail + issues with evidence). It judges, it doesn't solve. DEEP_AGENT_SEMANTIC_VALIDATION: always (default: every submitted answer is reviewed; on fail the agent fixes it or resubmits with validation_response = dispute), on_demand (a `semantic-validator` task subagent), off. Optional DEEP_AGENT_VALIDATOR_MAX_ROUNDS. - final_result / response `semantic_validation` (verdict, rounds, issues, reviewed_final_sql), Langfuse scores semantic_validation_passed / validation_rounds, deep:review: stream events, Hebrew warning in the answer on failed / disputed - prompts/validator.md (deep-agent/validator in Langfuse); the semantic-validation skill is removed — its unique checks moved into the reviewer prompt - SubmitReminderMiddleware: one "submit now" reminder per turn when the model ends with text instead of its submit call (main agent and reviewer) - fix: an invalid submit_answer call ended the run instead of retrying (since #43) - fix: parallel `task` calls crashed on jeen_catalog / final_result / turn_execution_start (last-value reducers; since #48) Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 20 +- agent/src/agent/config.py | 11 +- agent/src/deep_agent/agent.py | 40 +- agent/src/deep_agent/answer.py | 154 ++++++- agent/src/deep_agent/context.py | 45 ++- agent/src/deep_agent/observability.py | 11 + agent/src/deep_agent/prompt_registry.py | 4 +- agent/src/deep_agent/prompts/system.md | 4 +- agent/src/deep_agent/prompts/validator.md | 43 ++ agent/src/deep_agent/resources.py | 2 +- agent/src/deep_agent/service.py | 12 +- agent/src/deep_agent/validator.py | 300 ++++++++++++++ agent/tests/deep_agent/conftest.py | 8 + agent/tests/deep_agent/test_guidance_lint.py | 9 +- agent/tests/deep_agent/test_latency.py | 2 +- .../deep_agent/test_prompts_and_catalog.py | 10 +- agent/tests/deep_agent/test_resources.py | 6 +- .../tests/deep_agent/test_runtime_context.py | 10 +- agent/tests/deep_agent/test_service.py | 16 + agent/tests/deep_agent/test_validator.py | 382 ++++++++++++++++++ backend/app/routers/agent.py | 1 + 21 files changed, 1038 insertions(+), 52 deletions(-) create mode 100644 agent/src/deep_agent/prompts/validator.md create mode 100644 agent/src/deep_agent/validator.py create mode 100644 agent/tests/deep_agent/test_validator.py diff --git a/agent/README.md b/agent/README.md index b282f3b..d96db26 100644 --- a/agent/README.md +++ b/agent/README.md @@ -51,6 +51,24 @@ uv run deep-agent "..." --log-file runs/runs.jsonl # append one JSON line per It reads the same `agent/.env` settings as the API (LLM, Trino, Jeen metadata MCP, Langfuse). Run logs are opt-in and git-ignored (`agent/runs/`, `agent/*.jsonl`, `agent/*.csv`); Langfuse is the system of record for traces. +### Semantic validation (deep agent) + +An independent reviewer (`src/deep_agent/validator.py`) checks whether a SQL answer really answers the user's request: +a separate agent with a fresh context (the user's messages, the SQL, its rows, the stated assumptions and the catalog — +not the main agent's reasoning), read-only diagnostic tools, and a verdict of pass, or fail with issues and evidence. +Its prompt is `prompts/validator.md` (`deep-agent/validator` in Langfuse). `DEEP_AGENT_SEMANTIC_VALIDATION` picks how it is used: + +| Mode | | +|---|---| +| `on_demand` | a `semantic-validator` subagent the agent calls through `task` when it judges a review worthwhile; the verdict comes back to the agent, which decides what to do | +| `always` (default) | every submitted answer is reviewed before the run ends; on fail the agent fixes the SQL (reviewed again) or resubmits it with a justification (`validation_response`, recorded as disputed). `DEEP_AGENT_VALIDATOR_MAX_ROUNDS` optionally limits reviews per turn (default none) | +| `off` | no reviewer | + +The outcome for the final answer is the response's `semantic_validation`: `verdict` (`passed` / `failed` / `disputed` / +`not_validated`), `rounds`, `issues`, `reviewed_final_sql` (a review of an earlier SQL doesn't count for the final one). +Langfuse gets `validation_rounds` and, when the final SQL was reviewed, `semantic_validation_passed` — compare the modes +on accuracy and cost, then keep one. + ### SQL safety (deep agent) Every SQL the deep agent runs goes through `agent/utils/sql_guard.py` (sqlglot, Trino dialect): @@ -86,7 +104,7 @@ The UI → backend → agent path is the `chat_with_agent` MCP tool. It runs the The deep agent is built once per process and streams the same Redis `agent_stream:{thread_id}` events as the legacy graph (nodes `deep:` and `deep:answer`). Responses keep the legacy contract and add `engine`, `verification` (matched / re_executed / rejected / re_execution_failed / no_answer), `executed` (the final SQL ran and the rows are -Trino's), `recovered_from_text` and `confidence`. Each turn's answer is checked only against SQL executed in that turn. +Trino's), `recovered_from_text`, `semantic_validation` and `confidence`. Each turn's answer is checked only against SQL executed in that turn. Clarifications are off (`DEEP_AGENT_CLARIFICATIONS_ENABLED=false`). When on, a clarification comes back as `status: "interrupted"` with `interrupt_details.type = "hitl_escalation"` (`subtype: "clarification"`); the user's answer diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index a6092e9..436764d 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -52,6 +52,11 @@ class AgentSettings(BaseSettings): DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows DEEP_AGENT_TRACING_ENABLED: bool = True # Langfuse callbacks, span metadata and run scores DEEP_AGENT_CLARIFICATIONS_ENABLED: bool = False # let the model ask a clarifying question instead of answering + # Independent semantic review of answers (see deep_agent/validator.py): + # always = every submitted answer is reviewed before the run ends; + # on_demand = a `semantic-validator` subagent the agent calls when it judges a review worthwhile; off = no reviewer. + DEEP_AGENT_SEMANTIC_VALIDATION: Literal["always", "on_demand", "off"] = "always" + DEEP_AGENT_VALIDATOR_MAX_ROUNDS: int | None = Field(default=None, gt=0) # "always" only: reviews per turn; "none" = no limit JEEN_METADATA_CACHE_TTL_S: float = Field(default=300.0, ge=0) # metadata read cache (0 disables) JEEN_METADATA_REUSE_SESSION: bool = True # keep one MCP session open per event loop # Prompts (see deep_agent/prompt_registry.py). Off until the prompts are finalised and synced to Langfuse. @@ -113,10 +118,10 @@ class AgentSettings(BaseSettings): # ── G2-05: Redis Schema Cache ───────────────────────────────────────────── SCHEMA_CACHE_TTL: int = Field(default=600, gt=0) # seconds — DDL content - @field_validator("DEEP_AGENT_MAX_ROWS", "DEEP_AGENT_MAX_SAMPLE_ROWS", mode="before") + @field_validator("DEEP_AGENT_MAX_ROWS", "DEEP_AGENT_MAX_SAMPLE_ROWS", "DEEP_AGENT_VALIDATOR_MAX_ROUNDS", mode="before") @classmethod - def _no_row_ceiling(cls, value): - # Env vars can't hold None; these spellings mean "no ceiling". + def _no_limit(cls, value): + # Env vars can't hold None; these spellings mean "no limit". if isinstance(value, str) and value.strip().lower() in ("", "none", "null", "unlimited"): return None return value diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index a7760d7..e29c3b2 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -8,19 +8,31 @@ from deepagents import create_deep_agent as create_harness_agent from deepagents.middleware.subagents import DEFAULT_GENERAL_PURPOSE_DESCRIPTION, DEFAULT_SUBAGENT_PROMPT -from langchain.agents.structured_output import ToolStrategy from langchain_core.language_models import BaseChatModel from langgraph.checkpoint.memory import MemorySaver from agent.config import settings from agent.llm import get_llm -from deep_agent.answer import AnswerRecoveryMiddleware, AnswerVerificationMiddleware, answer_schema +from deep_agent.answer import ( + TOOL_NAME, + AnswerRecoveryMiddleware, + AnswerVerificationMiddleware, + SubmitReminderMiddleware, + answer_schema, + submission_strategy, +) from deep_agent.catalog import CatalogMiddleware from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware from deep_agent.prompt_registry import PromptRefreshMiddleware, load_prompt, local_prompt from deep_agent.resources import build_resources from deep_agent.tool_filter import BuiltinToolFilterMiddleware from deep_agent.tools import DEEP_AGENT_TOOLS +from deep_agent.validator import ( + ReviewTurnMiddleware, + SemanticValidationMiddleware, + ValidationMode, + validator_subagent, +) # Packaged system prompt (the Langfuse-managed version, when enabled, is loaded per agent build and refreshed per call). SYSTEM_PROMPT = local_prompt("system") @@ -42,7 +54,11 @@ def _general_purpose_subagent() -> dict: def create_deep_agent( - model: BaseChatModel | None = None, clarifications_enabled: bool | None = None, checkpointer=None + model: BaseChatModel | None = None, + clarifications_enabled: bool | None = None, + checkpointer=None, + semantic_validation: ValidationMode | None = None, + validator_model: BaseChatModel | None = None, ): """ Creates and returns a compiled LangGraph deep agent. @@ -54,29 +70,43 @@ def create_deep_agent( model: Chat model override (tests); defaults to the configured LLM. clarifications_enabled: Override DEEP_AGENT_CLARIFICATIONS_ENABLED (tests). checkpointer: Thread persistence (e.g. AsyncPostgresSaver); defaults to an in-memory saver. + semantic_validation: Override DEEP_AGENT_SEMANTIC_VALIDATION: on_demand | always | off (tests). + validator_model: Model for the independent reviewer; defaults to the agent's model. """ if clarifications_enabled is None: clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED + mode = semantic_validation or settings.DEEP_AGENT_SEMANTIC_VALIDATION llm = model or get_llm() memory = checkpointer or MemorySaver() resources = build_resources() suffix = CLARIFICATION_PROMPT if clarifications_enabled else "" system_prompt = load_prompt("system").text + suffix + reviewer = validator_model or llm + subagents = [_general_purpose_subagent()] + review_middleware = [] + if mode == "on_demand": + subagents.append(validator_subagent(reviewer)) + review_middleware = [ReviewTurnMiddleware()] + elif mode == "always": + review_middleware = [ReviewTurnMiddleware(), + SemanticValidationMiddleware(reviewer, settings.DEEP_AGENT_VALIDATOR_MAX_ROUNDS)] agent = create_harness_agent( model=llm, tools=DEEP_AGENT_TOOLS, system_prompt=system_prompt, - subagents=[_general_purpose_subagent()], + subagents=subagents, middleware=[ DeepAgentContextMiddleware(), CatalogMiddleware(), PromptRefreshMiddleware("system", system_prompt, suffix=suffix), AnswerRecoveryMiddleware(), + SubmitReminderMiddleware(TOOL_NAME), AnswerVerificationMiddleware(), + *review_middleware, BuiltinToolFilterMiddleware(), ], - response_format=ToolStrategy(answer_schema(clarifications_enabled)), + response_format=submission_strategy(answer_schema(clarifications_enabled, mode == "always")), context_schema=DeepAgentContext, checkpointer=memory, backend=resources.backend, diff --git a/agent/src/deep_agent/answer.py b/agent/src/deep_agent/answer.py index 394ba1f..c7f4d73 100644 --- a/agent/src/deep_agent/answer.py +++ b/agent/src/deep_agent/answer.py @@ -26,14 +26,16 @@ from typing import Any, Literal import sqlglot -from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse -from langchain_core.messages import AIMessage, ToolMessage +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse, hook_config +from langchain.agents.structured_output import ToolStrategy +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage from pydantic import BaseModel, Field, create_model from sqlglot.errors import SqlglotError from agent.config import settings from agent.utils import sql_guard from agent.utils.sql import clean_sql +from deep_agent.context import REMINDER_NAME, is_user_message from core.trino import execute_query_sync logger = logging.getLogger(__name__) @@ -42,6 +44,8 @@ TOOL_NAME = "submit_answer" +# Content of the tool message for an accepted submission (anything else there is an error or a review's feedback). +ANSWER_RECEIVED = "Answer received." _SUBMIT_DOC = "Submit your final answer. Call this exactly once, when you are done — it ends your work." @@ -77,10 +81,48 @@ class _AnswerFields(BaseModel): ) -def answer_schema(clarifications_enabled: bool | None = None) -> type[SubmitAnswer]: - """The final-answer schema; without clarifications the model must always commit to a SQL answer.""" - enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED if clarifications_enabled is None else clarifications_enabled - return SubmitAnswerWithClarification if enabled else SubmitAnswer +_VALIDATION_RESPONSE = (str | None, Field( + default=None, + description="Only when an independent review rejected your previous answer and you submit the same SQL again: " + "why that SQL is correct despite the review (Hebrew).", +)) + + +def _with_validation_response(base: type[SubmitAnswer]) -> type[SubmitAnswer]: + return create_model(TOOL_NAME, __base__=base, __doc__=_SUBMIT_DOC, validation_response=_VALIDATION_RESPONSE) + + +_SCHEMAS: dict[tuple[bool, bool], type[SubmitAnswer]] = { + (False, False): SubmitAnswer, + (True, False): SubmitAnswerWithClarification, + (False, True): _with_validation_response(SubmitAnswer), + (True, True): _with_validation_response(SubmitAnswerWithClarification), +} + + +def answer_schema( + clarifications_enabled: bool | None = None, validation_enabled: bool | None = None +) -> type[SubmitAnswer]: + """The final-answer schema; without clarifications the model must always commit to a SQL answer. + + With semantic validation "always", it also has `validation_response` (to stand by a rejected answer). + """ + if clarifications_enabled is None: + clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED + if validation_enabled is None: + validation_enabled = settings.DEEP_AGENT_SEMANTIC_VALIDATION == "always" + return _SCHEMAS[(bool(clarifications_enabled), bool(validation_enabled))] + + +def submission_strategy(schema: type[BaseModel]) -> ToolStrategy: + """ToolStrategy whose accepted-submission tool message is ANSWER_RECEIVED (see accepted_submission).""" + return ToolStrategy(schema, tool_message_content=ANSWER_RECEIVED) + + +def last_submission(messages: list, tool_name: str = TOOL_NAME) -> ToolMessage | None: + """The tool message answering a submit call, when it is the latest message (i.e. the model just submitted).""" + last = messages[-1] if messages else None + return last if isinstance(last, ToolMessage) and last.name == tool_name else None def normalize_sql(sql: str | None) -> str | None: @@ -114,7 +156,7 @@ def executed_query_record( } -def _match(answer_sql: str, executed: list[dict[str, Any]]) -> dict[str, Any] | None: +def match_execution(answer_sql: str, executed: list[dict[str, Any]]) -> dict[str, Any] | None: target = normalize_sql(answer_sql) for record in reversed(executed): # latest execution wins if target in (normalize_sql(record["submitted_sql"]), normalize_sql(record["executed_sql"])): @@ -162,7 +204,7 @@ def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any] if getattr(answer, "needs_clarification", None) or not answer.sql: return {**base, "status": "clarification", "executed": False, "sql": None, "result": None} - record = _match(answer.sql, executed) + record = match_execution(answer.sql, executed) if record is not None and not _is_sample(record): return {**base, "status": "matched", "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} @@ -225,9 +267,7 @@ def _recover(self, request: ModelRequest, response: ModelResponse) -> ModelRespo id=output.id, name=output.name, ) - tool_message = ToolMessage( - content=f"Returning structured response: {answer}", tool_call_id=call_id, name=schema.__name__, - ) + tool_message = ToolMessage(content=ANSWER_RECEIVED, tool_call_id=call_id, name=schema.__name__) return ModelResponse(result=[*response.result[:-1], repaired, tool_message], structured_response=answer) def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: @@ -240,13 +280,44 @@ async def awrap_model_call( def current_turn(messages: list) -> list: - """Messages after the latest human message (this run's turn).""" + """Messages after the latest user message (this run's turn).""" for i in range(len(messages) - 1, -1, -1): - if getattr(messages[i], "type", None) == "human": + if is_user_message(messages[i]): return messages[i + 1:] return messages +class SubmitReminderMiddleware(AgentMiddleware): + """Send the model back once per turn when it stops without calling its submit tool. + + The configured model server sometimes ends a run with plain text instead of the forced + submit call (and AnswerRecoveryMiddleware can only rescue text that is valid JSON for the + schema). The work is then lost — e.g. a reviewer that found a real problem but never + returned its verdict. One reminder (a message named REMINDER_NAME, not counted as the + user's words) asks for the submit call; if the model still doesn't comply, the run ends as before. + """ + + def __init__(self, tool_name: str) -> None: + super().__init__() + self.tool_name = tool_name + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + messages = state.get("messages") or [] + last = messages[-1] if messages else None + if not isinstance(last, AIMessage) or last.tool_calls or state.get("structured_response") is not None: + return None + if any(getattr(m, "name", None) == REMINDER_NAME for m in current_turn(messages)): + return None # already reminded this turn + reminder = (f"You stopped without calling `{self.tool_name}`. Your work is delivered only through " + f"`{self.tool_name}` — call it now with your result.") + return {"messages": [HumanMessage(reminder, name=REMINDER_NAME)], "jump_to": "model"} + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + return self.after_model(state, runtime) + + class AnswerVerificationMiddleware(AgentMiddleware): """Bind each turn's structured answer to SQL executed in that turn and its real rows. @@ -254,10 +325,25 @@ class AnswerVerificationMiddleware(AgentMiddleware): again on a turn that ends without a new one) and marks where this turn's executions start, so an answer can only match SQL that ran in its own turn. + after_model sends the model back after a rejected submit_answer call (arguments that fail the + schema). LangChain would retry on its own only while `structured_response` has never been set + in the thread; from the first reset on, it ends the run instead. + after_agent keeps the answer only as plain data in final_result and drops the pydantic object: checkpoints can't restore the dynamically built `submit_answer` class. """ + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + submission = last_submission(state.get("messages") or []) + if submission is not None and submission.text != ANSWER_RECEIVED: + return {"jump_to": "model"} + return None + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + return self.after_model(state, runtime) + def before_agent(self, state, runtime) -> dict[str, Any] | None: return {"structured_response": None, "turn_execution_start": len(state.get("executed_queries") or [])} @@ -270,12 +356,47 @@ def after_agent(self, state, runtime) -> dict[str, Any] | None: final["recovered_from_text"] = any( (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in current_turn(state.get("messages") or []) ) + final["semantic_validation"] = validation_summary(state.get("semantic_validations"), final.get("sql")) return {"final_result": final, "structured_response": None} async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: return await asyncio.to_thread(self.after_agent, state, runtime) +_VERDICTS = {"pass": "passed", "fail": "failed", "disputed": "disputed"} + + +def _covers(record: dict[str, Any], final_sql: str | None) -> bool | None: + """Did this review look at the final SQL? None when it can't be told (an on-demand brief without a ```sql block).""" + target = normalize_sql(final_sql) + if "sql" in record: + return record["sql"] == target + return (target in record["sqls"]) if record.get("sqls") else None + + +def validation_summary(records: list[dict[str, Any]] | None, final_sql: str | None = None) -> dict[str, Any] | None: + """The review outcome of the final answer, from this turn's review records (None = reviewer off). + + verdict: passed | failed | disputed (the agent resubmitted a rejected SQL with a justification) | + not_validated (no review, a review of a different SQL than the final one, round limit, or the review failed). + reviewed_final_sql: whether the last review covered the final SQL (None = can't be told). + """ + if records is None: + return None + rounds = sum(1 for r in records if r["verdict"] in ("pass", "fail")) + summary = {"verdict": "not_validated", "rounds": rounds, "issues": [], "response": None, "reason": None, + "reviewed_final_sql": None} + if not records: + return {**summary, "reason": "no review"} + last = records[-1] + covers = _covers(last, final_sql) + summary.update(issues=last.get("issues") or [], response=last.get("response"), reviewed_final_sql=covers, + reason=last.get("reason")) + if covers is False: + return {**summary, "issues": [], "reason": "the final SQL changed after the last review"} + return {**summary, "verdict": _VERDICTS.get(last["verdict"], "not_validated")} + + def _cell(value: Any) -> str: return "" if value is None else str(value).replace("|", "\\|").replace("\n", " ") @@ -303,6 +424,13 @@ def render_markdown(final_result: dict[str, Any]) -> str: elif final_result.get("error"): parts.append(f"⚠️ לא ניתן היה להריץ את השאילתה הסופית: {final_result['error']}") + review = final_result.get("semantic_validation") or {} + if review.get("verdict") in ("failed", "disputed") and review.get("issues"): + title = "בדיקה עצמאית מצאה בעיות בתשובה" if review["verdict"] == "failed" else "בדיקה עצמאית העלתה הסתייגות" + parts.append(f"⚠️ **{title}:**\n" + "\n".join(f"- {i['problem']}" for i in review["issues"])) + if review["verdict"] == "disputed" and review.get("response"): + parts.append(f"**תגובת הסוכן:** {review['response']}") + if final_result.get("sql"): parts.append(f"```sql\n{final_result['sql']}\n```") return "\n\n".join(p for p in parts if p) diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index 3737a97..05e6b8c 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -47,11 +47,44 @@ def merge_executions(left: list[dict[str, Any]] | None, right: list[dict[str, An return merged +def latest(left: Any, right: Any) -> Any: + """Last write wins. deepagents returns a subagent's whole state (minus messages) to the parent, so + parallel `task` calls write these keys in the same step; a plain key would reject that.""" + return right + + +def merge_reviews(left: list[dict[str, Any]] | None, right: list[dict[str, Any]] | None) -> list[dict[str, Any]]: + """Reducer for semantic_validations: records are merged by their `id`; `None` resets the list. + + A subagent returns the list it was given plus its own record, and parallel reviews return in the + same step, so a plain value would either duplicate records or reject the concurrent writes. + """ + if right is None: + return [] + merged = list(left or []) + seen = {r.get("id") for r in merged} + for record in right: + if record.get("id") not in seen: + merged.append(record) + seen.add(record.get("id")) + return merged + + class DeepAgentRuntimeState(AgentState): - jeen_catalog: NotRequired[str] # the connection's catalog, loaded once per run (deep_agent.catalog) + jeen_catalog: NotRequired[Annotated[str, latest]] # the connection's catalog, loaded once per run (deep_agent.catalog) executed_queries: NotRequired[Annotated[list[dict[str, Any]], merge_executions]] # successful executions - final_result: NotRequired[dict[str, Any]] # verified answer + rows (see deep_agent.answer) - turn_execution_start: NotRequired[int] # index into executed_queries where the current turn began + final_result: NotRequired[Annotated[dict[str, Any], latest]] # verified answer + rows (see deep_agent.answer) + turn_execution_start: NotRequired[Annotated[int, latest]] # index into executed_queries where the current turn began + semantic_validations: NotRequired[Annotated[list[dict[str, Any]], merge_reviews]] # this turn's reviews (deep_agent.validator) + + +# Name of the one-time "submit now" message (deep_agent.answer.SubmitReminderMiddleware): not the user's words. +REMINDER_NAME = "submit_reminder" + + +def is_user_message(msg: Any) -> bool: + """A message the user wrote (not the harness's submit reminder).""" + return isinstance(msg, HumanMessage) and getattr(msg, "name", None) != REMINDER_NAME def connection_id(runtime: ToolRuntime | None) -> int | None: @@ -71,7 +104,7 @@ def user_request(runtime: ToolRuntime | None) -> str: request being answered is the original question plus those replies — not just the last one. """ state = getattr(runtime, "state", None) or {} - texts = [msg.text for msg in state.get("messages") or [] if isinstance(msg, HumanMessage) and msg.text.strip()] + texts = [msg.text for msg in state.get("messages") or [] if is_user_message(msg) and msg.text.strip()] return "\n".join(texts) @@ -85,7 +118,7 @@ def date_line(tz: str) -> str: def _with_date(request: ModelRequest) -> ModelRequest: - """Prefix the latest human message with today's date for this model call only. + """Prefix the latest user message with today's date for this model call only. The date is deliberately *not* put in the system message: deepagents appends its skills section after user middleware, so a date there would sit mid-prompt and invalidate @@ -97,7 +130,7 @@ def _with_date(request: ModelRequest) -> ModelRequest: messages = list(request.messages) for i in range(len(messages) - 1, -1, -1): msg = messages[i] - if isinstance(msg, HumanMessage): + if is_user_message(msg): content: Any = msg.content if isinstance(content, str): new_content: Any = f"[{line}]\n\n{content}" diff --git a/agent/src/deep_agent/observability.py b/agent/src/deep_agent/observability.py index c313c41..0d3cda7 100644 --- a/agent/src/deep_agent/observability.py +++ b/agent/src/deep_agent/observability.py @@ -106,6 +106,9 @@ def annotate_current_span(metadata: dict[str, Any], level: str | None = None) -> logger.debug("annotate_current_span skipped: %s", exc) +_REVIEWED = {"passed", "failed", "disputed"} # verdicts that judged the final SQL + + @dataclass(frozen=True) class RunMetrics: """Plain counts and timing for one run, plus whether the submitted final SQL actually ran @@ -116,16 +119,22 @@ class RunMetrics: sql_executions: int latency_s: float final_sql_executed: bool = False # the submitted final SQL ran and its rows are Trino's (not a correctness check) + # Independent review (deep_agent.validator). None -> no score: reviewer off, or the final SQL wasn't reviewed. + semantic_validation_passed: bool | None = None + validation_rounds: int | None = None # reviews this turn (0 = the agent didn't ask for one); None = reviewer off def run_metrics(messages: list[BaseMessage], latency_s: float, final_result: dict | None = None) -> RunMetrics: ai = [m for m in messages if m.type == "ai"] + review = (final_result or {}).get("semantic_validation") or {} return RunMetrics( model_calls=len(ai), tool_calls=sum(len(getattr(m, "tool_calls", None) or []) for m in ai), sql_executions=sum(1 for m in messages if m.type == "tool" and m.name == "execute_trino_query"), latency_s=round(latency_s, 2), final_sql_executed=bool(final_result and final_result.get("executed")), + semantic_validation_passed=(review["verdict"] == "passed") if review.get("verdict") in _REVIEWED else None, + validation_rounds=review.get("rounds", 0) if review else None, ) @@ -137,6 +146,8 @@ def score_run(trace_id: str | None, metrics: RunMetrics) -> None: from agent.langfuse_client import langfuse_client for name, value in asdict(metrics).items(): + if value is None: + continue data_type = "BOOLEAN" if isinstance(value, bool) else "NUMERIC" langfuse_client.create_score( trace_id=trace_id, name=f"{AGENT_NAME}.{name}", value=float(value), data_type=data_type diff --git a/agent/src/deep_agent/prompt_registry.py b/agent/src/deep_agent/prompt_registry.py index 23c669d..da4544e 100644 --- a/agent/src/deep_agent/prompt_registry.py +++ b/agent/src/deep_agent/prompt_registry.py @@ -1,7 +1,7 @@ """ Prompt management for the Deep Agent. -Prompts are Langfuse text prompts named `deep-agent/` (currently only `system`), fetched by label (DEEP_AGENT_PROMPT_LABEL, default +Prompts are Langfuse text prompts named `deep-agent/` (`system`, `validator`), fetched by label (DEEP_AGENT_PROMPT_LABEL, default "production") with the SDK's TTL cache. The packaged `prompts/.md` files are the fallback when Langfuse is unreachable or the prompt doesn't exist, and the only source when DEEP_AGENT_LANGFUSE_PROMPTS is off (tests, offline dev). @@ -26,7 +26,7 @@ logger = logging.getLogger(__name__) PROMPTS_DIR = Path(__file__).resolve().parent / "prompts" -PROMPT_KEYS = ("system",) +PROMPT_KEYS = ("system", "validator") def langfuse_name(key: str) -> str: diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index 3529525..9d6c949 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -162,11 +162,13 @@ After a successful execution, validate before answering: If any check fails or you're unsure, run a targeted diagnostic query. Do not guess. +**Independent review** — if a `semantic-validator` subagent is available, ask it to review the answer (`task`) before `submit_answer` whenever the answer involves a join, aggregation or grouping, several conditions, an interpretation you had to choose, 0 rows or a surprising number. It has not seen your work, so it catches mistakes you can't see in your own reasoning — confidence is not a reason to skip it. Skip it only for simple lookups whose values you have already verified. + --- ## Skills -Before writing SQL in these areas, read the skill with `read_file`: `temporal-analyst` (dates, times, Hebrew time expressions), `spatial-analyst` (locations and geometry), `semantic-validation` (deeper verification checks and diagnostics). +Before writing SQL in these areas, read the skill with `read_file`: `temporal-analyst` (dates, times, Hebrew time expressions), `spatial-analyst` (locations and geometry). --- diff --git a/agent/src/deep_agent/prompts/validator.md b/agent/src/deep_agent/prompts/validator.md new file mode 100644 index 0000000..b0c179a --- /dev/null +++ b/agent/src/deep_agent/prompts/validator.md @@ -0,0 +1,43 @@ +You are an independent reviewer of Text-to-SQL answers. An analyst translated a user's request into Trino SQL and wants it checked before showing it to the user. You did not write this SQL and you do not see the analyst's reasoning — you get the user's request, the SQL, and usually its result rows, the explanation and the assumptions the analyst made. Your job: decide whether this SQL actually answers what the user asked, on this database. If the result rows are missing, run the SQL yourself. + +The connection's complete catalog is included at the end of this prompt ("Database Catalog"). + +## How to review + +1. **Restate the request.** In one sentence, what exactly is the user asking for? What should one output row represent (the grain)? Which conditions did the user state (entities, values, places, time ranges)? If there are several user messages, the last one is the current question and the earlier ones are its context (a follow-up such as "and from Italy?" keeps the earlier conditions and changes one). +2. **Translate the SQL back into plain language** and compare it with the request, condition by condition: + - every condition the user stated is in the SQL, on the right column; + - the SQL adds no condition the user did not ask for (unless it is stated in the assumptions and reasonable); + - the output grain and the aggregation match the question ("how many X" counts X, not rows of a joined table; "per X" groups by X; "top N" orders by the right measure in the right direction, and ties are handled sensibly); + - the selected columns are what the user asked for. + + How request wording usually maps to SQL, and what goes wrong: + + | The user says | Usually means | Watch for | + |---|---|---| + | "כמה" (how many) | `COUNT` of entities | `COUNT(*)` after a one-to-many join counts rows, not entities | + | "ממוצע" (average) | `AVG` | an average of per-group averages instead of over all rows; NULLs are ignored by `AVG` | + | "סה"כ" (total) | `SUM` | NULLs are skipped; an empty group gives NULL, not 0 | + | "הכי" / "הגבוה ביותר" (most / highest) | `ORDER BY … LIMIT` or `MAX` | ties: other rows with the same top value are silently dropped | + | "לכל" / "ל-" (per X, per capita) | a ratio at X's grain | numerator and denominator at different grains; integer division (`5 / 2 = 2`); division by zero | + | "לפי X" (by X) | `GROUP BY X` | grouped at a different level than X | +3. **Check the risky parts with evidence**, using your tools. Run small diagnostic queries rather than guessing: + - **Filter values**: a text filter must use the value as it is stored. Check it exists (`get_column_distinct_values` for `categorical` columns, `search_column_values` for `large_categorical` / `large_unit_id` columns, or the values listed in the catalog). Check that no other stored spelling of the same entity was missed. + - **Joins**: on a one-to-many join, compare counts before and after the join; `COUNT(*)` after a fan-out counts duplicated rows, not entities. + - **Time ranges**: correct column, correct boundaries (inclusive/exclusive, whole periods), correct relative dates against today's date given above, DATE vs TIMESTAMP comparison. + - **NULLs and empty results**: 0 rows, or a suspiciously round or table-sized number, means a condition is wrong or ineffective — find which one (a count equal to the whole table's count means the filter does nothing; a count far above the table's size means a join without a proper key). + - **Anti-joins** ("X with no Y"): `NOT IN (subquery)` returns nothing when the subquery has a NULL — `NOT EXISTS` or `LEFT JOIN … IS NULL` is safe. Also check the anti-join actually matches anything: if the join keys of the two sides never match, "no Y" is true for everyone. + - **Joins that drop entities**: an `INNER JOIN` removes entities with no related rows, which is wrong for "per entity" results that should show zero. + +**Judge — don't solve.** Your job is to decide whether this SQL answers the request, not to write the correct SQL. Stop investigating as soon as you can show a concrete problem with evidence; point briefly at the direction of a fix, but don't search for the full solution. Keep your checks proportionate to the risk in the SQL: a simple lookup needs little, a multi-join aggregation more. +4. **Check the explanation** the user will see: it must describe what the SQL does and what the result means, without claiming anything the result does not show. + +## Verdict + +Call `submit_verdict` exactly once, when you are done: +- `verdict: "pass"` — the answer correctly answers the request (a reasonable interpretation stated in the assumptions is fine). +- `verdict: "fail"` — at least one concrete problem would make the user's answer wrong or misleading. For each problem give `problem` (what is wrong and how to fix it) and `evidence` (the query you ran and what it returned, or the exact part of the SQL / request that disagrees). Write them in Hebrew. + +Fail only for problems you can show. Style, formatting, performance, or a different-but-equivalent way to write the SQL are not problems. If you are unsure whether something is wrong, check it with a query; if you still cannot show it, it is not a problem. + +Your tools are read-only. Never modify data. diff --git a/agent/src/deep_agent/resources.py b/agent/src/deep_agent/resources.py index ab8a258..96e20ec 100644 --- a/agent/src/deep_agent/resources.py +++ b/agent/src/deep_agent/resources.py @@ -25,7 +25,7 @@ SKILLS_ROUTE = "/skills/" -EXPECTED_SKILLS = frozenset({"temporal-analyst", "spatial-analyst", "semantic-validation"}) +EXPECTED_SKILLS = frozenset({"temporal-analyst", "spatial-analyst"}) class DeepAgentResourceError(RuntimeError): diff --git a/agent/src/deep_agent/service.py b/agent/src/deep_agent/service.py index 36a10b7..11f86f4 100644 --- a/agent/src/deep_agent/service.py +++ b/agent/src/deep_agent/service.py @@ -7,10 +7,11 @@ replicas, survives restarts), otherwise an in-memory saver. - Streaming: the same Redis events the legacy graph publishes (`agent_stream:{thread_id}`, {"thread_id", "node", "status"}), so the backend SSE relay and UI work unchanged. Nodes are - named `deep:` (e.g. deep:execute_trino_query) plus `deep:answer`. + named `deep:` (e.g. deep:execute_trino_query), `deep:review:` for the independent + reviewer's tools (deep_agent.validator), plus `deep:answer`. - Response: the legacy JSON contract (status / summary / sql_query / sql_explanation / interrupt_details / trace_id / execution_path / is_unanswerable) plus `engine`, - `verification`, `executed`, `recovered_from_text` and `confidence`. + `verification`, `executed`, `recovered_from_text`, `semantic_validation` and `confidence`. - Run limit: none by default. A caller that stops waiting after N seconds passes `timeout_s`; the run is then cancelled at that point (no tokens spent on an answer nobody receives). - Clarification (only with DEEP_AGENT_CLARIFICATIONS_ENABLED): an answer with needs_clarification returns status "interrupted" with @@ -33,6 +34,7 @@ from deep_agent import observability from deep_agent.answer import current_turn, render_markdown from deep_agent.context import DeepAgentContext +from deep_agent.validator import VALIDATOR_NAME logger = logging.getLogger(__name__) @@ -94,8 +96,9 @@ def __init__(self, thread_id: str) -> None: async def _publish(self, node: str, status: str) -> None: await publish_node_event(self.thread_id, node, status) - async def on_tool_start(self, serialized, input_str, *, run_id, **kwargs) -> None: - name = f"deep:{(serialized or {}).get('name') or kwargs.get('name') or 'tool'}" + async def on_tool_start(self, serialized, input_str, *, run_id, tags=None, **kwargs) -> None: + tool = (serialized or {}).get("name") or kwargs.get("name") or "tool" + name = f"deep:review:{tool}" if VALIDATOR_NAME in (tags or []) else f"deep:{tool}" self._names[run_id] = name self.execution_path.append(name) await self._publish(name, "active") @@ -117,6 +120,7 @@ def to_response(thread_id: str, final_result: dict[str, Any], trace_id: str | No "verification": status, "executed": bool(final_result.get("executed")), "recovered_from_text": bool(final_result.get("recovered_from_text")), + "semantic_validation": final_result.get("semantic_validation"), "confidence": answer.get("confidence"), "trace_id": trace_id, "execution_path": execution_path, diff --git a/agent/src/deep_agent/validator.py b/agent/src/deep_agent/validator.py new file mode 100644 index 0000000..3ca8ab6 --- /dev/null +++ b/agent/src/deep_agent/validator.py @@ -0,0 +1,300 @@ +""" +Independent semantic review of the Deep Agent's answers. + +The reviewer is a separate agent with a fresh context and read-only diagnostic tools. It gets +the user's request, the SQL, and (usually) the result rows and stated assumptions — never the +main agent's reasoning, so it can't simply agree with it — and returns `submit_verdict` +(pass / fail + issues with evidence). DEEP_AGENT_SEMANTIC_VALIDATION picks how it is used: + +on_demand + A `semantic-validator` subagent the agent calls through `task` when it judges a review + worthwhile (its description says when, and what to send). The verdict comes back to the + agent as JSON; acting on it is up to the agent. Each review is recorded. + +always (default) + Every accepted `submit_answer` call is reviewed before the run can end: + - pass -> the run ends normally; + - fail -> the "Answer received." tool message is replaced by the review's feedback and the + model is sent back. It either fixes the SQL and submits again (reviewed again), or submits + the same SQL with `validation_response` — a dispute, which ends the loop. If it stops + without resubmitting, its last (failed) answer stands, marked "failed". + DEEP_AGENT_VALIDATOR_MAX_ROUNDS optionally limits reviews per turn (default: no limit). + +off + No reviewer. + +Both modes record reviews in `semantic_validations`; the outcome for the final answer goes to +final_result["semantic_validation"] (deep_agent.answer.validation_summary). Semantic checks also +stay mandatory in the main agent's own prompt; the reviewer is an extra, independent check. +""" + +import logging +import re +import uuid +from typing import Any, Literal + +from langchain.agents import create_agent +from langchain.agents.middleware import AgentMiddleware, hook_config +from langchain_core.language_models import BaseChatModel +from langchain_core.messages import HumanMessage, ToolMessage +from pydantic import BaseModel, Field, create_model, model_validator + +from deep_agent.answer import ( + ANSWER_RECEIVED, + TOOL_NAME, + AnswerRecoveryMiddleware, + SubmitReminderMiddleware, + last_submission, + match_execution, + normalize_sql, + submission_strategy, +) +from deep_agent.catalog import CatalogMiddleware +from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware, DeepAgentRuntimeState, is_user_message +from deep_agent.prompt_registry import PromptRefreshMiddleware, load_prompt +from deep_agent.tools import ( + execute_trino_query, + get_column_distinct_values, + get_column_profile, + get_sample_rows, + search_column_values, +) + +logger = logging.getLogger(__name__) + +ValidationMode = Literal["on_demand", "always", "off"] + +VERDICT_TOOL = "submit_verdict" +VALIDATOR_NAME = "semantic-validator" +REVIEW_CONFIG = {"run_name": VALIDATOR_NAME, "tags": [VALIDATOR_NAME]} # the tag marks the reviewer's nested runs +VALIDATOR_TOOLS = [execute_trino_query, get_sample_rows, get_column_distinct_values, search_column_values, + get_column_profile] + +# What the main agent sees about the on-demand subagent (in the `task` tool's list of subagents). +ON_DEMAND_DESCRIPTION = ( + "Independent reviewer: checks whether a SQL answer really answers the user's request, using read-only " + "diagnostic queries, and returns JSON {verdict: pass|fail, issues: [{problem, evidence}]}. It has not seen " + "your work, which is the point. Worth it before submit_answer when the answer involves joins, aggregation " + "or grouping, date ranges, several conditions, an interpretation you had to choose, 0 rows or a surprising " + "number. Skip it for simple lookups you have already verified. In the task description send only: the " + "user's messages verbatim (all of them, for a follow-up), the SQL to review in a ```sql block, its result " + "rows, and your stated assumptions — not your reasoning or your conclusion. On fail, fix the SQL (and " + "review again if the change is substantial), or keep it only if you can show why the issue is wrong." +) + + +class Issue(BaseModel): + problem: str = Field(description="What is wrong and how to fix it (Hebrew).") + evidence: str = Field(description="The query you ran and what it returned, or the exact part of the SQL / " + "request that disagrees (Hebrew).") + + +class _VerdictFields(BaseModel): + verdict: Literal["pass", "fail"] = Field(description="pass = the answer answers the request; fail = it doesn't.") + issues: list[Issue] = Field(default_factory=list, description="Every problem found (required for fail).") + + @model_validator(mode="after") + def _fail_needs_issues(self): + if self.verdict == "fail" and not self.issues: + raise ValueError("a fail verdict needs at least one issue with evidence") + return self + + +SubmitVerdict = create_model( + VERDICT_TOOL, __base__=_VerdictFields, + __doc__="Submit your review verdict. Call this exactly once, when you are done — it ends your review.", +) + +_SQL_BLOCK = re.compile(r"```sql\s*(.*?)```", re.DOTALL | re.IGNORECASE) + + +def _record(mode: ValidationMode, verdict: Any, **fields: Any) -> dict[str, Any]: + if verdict is None: + return {"id": uuid.uuid4().hex, "mode": mode, "verdict": "error", "issues": [], **fields} + return {"id": uuid.uuid4().hex, "mode": mode, "verdict": verdict.verdict, + "issues": [issue.model_dump() for issue in verdict.issues], **fields} + + +class ReviewRecordMiddleware(AgentMiddleware): + """Inside the on-demand reviewer: record its verdict and which SQL it reviewed (```sql blocks of the brief).""" + + state_schema = DeepAgentRuntimeState + + def after_agent(self, state, runtime) -> dict[str, Any] | None: + messages = state.get("messages") or [] + brief = messages[0].text if messages else "" + sqls = [normalize_sql(block) for block in _SQL_BLOCK.findall(brief)] + reason = None if state.get("structured_response") else "the reviewer ended without a verdict" + return {"semantic_validations": [_record("on_demand", state.get("structured_response"), + sqls=[s for s in sqls if s], reason=reason)]} + + async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: + return self.after_agent(state, runtime) + + +class ReviewTurnMiddleware(AgentMiddleware): + """Start every turn with no reviews (both modes).""" + + state_schema = DeepAgentRuntimeState + + def before_agent(self, state, runtime) -> dict[str, Any] | None: + return {"semantic_validations": None} # None resets (context.merge_reviews) + + async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: + return self.before_agent(state, runtime) + + +def build_validator(model: BaseChatModel, *, on_demand: bool = False): + """The reviewer agent: catalog + date in context, read-only tools, verdict as structured output.""" + prompt = load_prompt("validator").text + agent = create_agent( + model=model, + tools=VALIDATOR_TOOLS, + system_prompt=prompt, + middleware=[ + DeepAgentContextMiddleware(), + CatalogMiddleware(), + PromptRefreshMiddleware("validator", prompt), + AnswerRecoveryMiddleware(), + SubmitReminderMiddleware(VERDICT_TOOL), + *([ReviewRecordMiddleware()] if on_demand else []), + ], + response_format=submission_strategy(SubmitVerdict), + context_schema=DeepAgentContext, + checkpointer=False, # a fresh, unsaved state per review (never the main thread's checkpointer) + name=VALIDATOR_NAME, + ) + return agent.with_config(REVIEW_CONFIG) + + +def validator_subagent(model: BaseChatModel) -> dict[str, Any]: + """The on-demand reviewer as a deepagents CompiledSubAgent (called through `task`).""" + return {"name": VALIDATOR_NAME, "description": ON_DEMAND_DESCRIPTION, "runnable": build_validator(model, on_demand=True)} + + +# ── always: review every submitted answer ──────────────────────────────────── + +def _human_messages(messages: list) -> list[str]: + return [m.text for m in messages if is_user_message(m) and m.text.strip()] + + +def _result_section(record: dict[str, Any] | None) -> str: + if record is None: + return "The analyst did not execute this exact SQL in this turn — run it yourself to see the result." + note = " (truncated by the row ceiling: more rows exist)" if record.get("truncated") else "" + lines = [f"Columns: {record['columns']}", f"Rows returned: {record['row_count']}{note}"] + lines += [str(row) for row in record["rows"]] + return "\n".join(lines) + + +def review_request(messages: list, answer: Any, executed: list[dict[str, Any]]) -> str: + """The reviewer's only input: the user's messages, the answer as the user will see it, and its rows.""" + humans = _human_messages(messages) + earlier = "\n".join(f"- {text}" for text in humans[:-1]) + parts = [] + if earlier: + parts.append(f"## Earlier user messages (context)\n{earlier}") + parts.append(f"## Current user request\n{humans[-1] if humans else ''}") + assumptions = "\n".join(f"- {a}" for a in answer.assumptions) or "(none)" + parts.append( + f"## Answer to review\n```sql\n{answer.sql}\n```\n\n" + f"Explanation shown to the user: {answer.explanation_he}\n\nStated assumptions:\n{assumptions}" + ) + parts.append(f"## Result of this SQL\n{_result_section(match_execution(answer.sql, executed))}") + return "\n\n".join(parts) + + +def feedback_text(issues: list[dict[str, str]]) -> str: + listed = "\n".join(f"{n}. {i['problem']}\n Evidence: {i['evidence']}" for n, i in enumerate(issues, 1)) + return ( + "An independent reviewer checked this answer against the user's request and found problems:\n" + f"{listed}\n\n" + f"Fix the SQL, execute it, and call {TOOL_NAME} again. If you are sure the answer is correct as it is, " + f"call {TOOL_NAME} again with the same SQL and explain why in `validation_response`." + ) + + +class SemanticValidationMiddleware(AgentMiddleware): + """`always` mode: reviews every accepted submit_answer call (see module docstring).""" + + state_schema = DeepAgentRuntimeState + + def __init__(self, model: BaseChatModel, max_rounds: int | None = None) -> None: + super().__init__() + self.model = model + self.max_rounds = max_rounds + self._validator = None + + @property + def validator(self): + if self._validator is None: + self._validator = build_validator(self.model) + return self._validator + + def _pending(self, state) -> tuple[Any, ToolMessage, list[dict[str, Any]]] | None: + """(answer, its tool message, records) when the model just made an accepted SQL submission.""" + submission = last_submission(state.get("messages") or []) + answer = state.get("structured_response") + if submission is None or submission.text != ANSWER_RECEIVED or answer is None: + return None + if getattr(answer, "needs_clarification", None) or not answer.sql: + return None + return answer, submission, list(state.get("semantic_validations") or []) + + def _without_review(self, answer: Any, records: list[dict[str, Any]]) -> dict[str, Any] | None: + """A record that ends the loop without a review (dispute / round limit), else None.""" + sql = normalize_sql(answer.sql) + previous = records[-1] if records else None + if previous and previous["verdict"] == "fail" and previous["sql"] == sql: + return {"id": uuid.uuid4().hex, "mode": "always", "verdict": "disputed", "sql": sql, + "issues": previous["issues"], "response": getattr(answer, "validation_response", None)} + reviews = sum(1 for r in records if r["verdict"] in ("pass", "fail")) + if self.max_rounds is not None and reviews >= self.max_rounds: + return {"id": uuid.uuid4().hex, "mode": "always", "verdict": "skipped", "sql": sql, "issues": [], + "reason": f"review limit reached ({self.max_rounds})"} + return None + + def _update(self, answer, submission, verdict, error: str | None) -> dict[str, Any]: + record = _record("always", verdict, sql=normalize_sql(answer.sql), + reason=None if verdict is not None else error) + if verdict is None: + logger.warning("Semantic validation produced no verdict: %s", error) + if verdict is None or verdict.verdict == "pass": + return {"semantic_validations": [record]} + feedback = ToolMessage(content=feedback_text(record["issues"]), tool_call_id=submission.tool_call_id, + name=submission.name, id=submission.id) # same id: replaces "Answer received." + return {"messages": [feedback], "semantic_validations": [record], "jump_to": "model"} + + def _review_input(self, state, answer) -> dict[str, Any]: + executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + return {"messages": [HumanMessage(review_request(state.get("messages") or [], answer, executed))]} + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + pending = self._pending(state) + if pending is None: + return None + answer, submission, records = pending + if (record := self._without_review(answer, records)) is not None: + return {"semantic_validations": [record]} + try: + out = self.validator.invoke(self._review_input(state, answer), context=runtime.context) + verdict, error = out.get("structured_response"), "the reviewer ended without a verdict" + except Exception as exc: # a broken review must not lose the answer + verdict, error = None, f"{type(exc).__name__}: {exc}" + return self._update(answer, submission, verdict, error) + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + pending = self._pending(state) + if pending is None: + return None + answer, submission, records = pending + if (record := self._without_review(answer, records)) is not None: + return {"semantic_validations": [record]} + try: + out = await self.validator.ainvoke(self._review_input(state, answer), context=runtime.context) + verdict, error = out.get("structured_response"), "the reviewer ended without a verdict" + except Exception as exc: # a broken review must not lose the answer + verdict, error = None, f"{type(exc).__name__}: {exc}" + return self._update(answer, submission, verdict, error) diff --git a/agent/tests/deep_agent/conftest.py b/agent/tests/deep_agent/conftest.py index 78f754b..89aab62 100644 --- a/agent/tests/deep_agent/conftest.py +++ b/agent/tests/deep_agent/conftest.py @@ -63,6 +63,14 @@ def _make(policy: Callable[[list[BaseMessage]], AIMessage]) -> PolicyChatModel: TEST_CATALOG = '# Database Schema\n\n## Columns\n"catalog"."schema"."orders": Orders\n - "status" (varchar) [semantic_type=categorical]' +@pytest.fixture(autouse=True) +def no_semantic_validation(monkeypatch): + """Scripted models answer the main agent only; tests that cover the reviewer turn it on explicitly.""" + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_SEMANTIC_VALIDATION", "off") + + @pytest.fixture(autouse=True) def fake_catalog(monkeypatch): """Every agent run loads the connection's catalog (CatalogMiddleware); never hit the real Jeen service in tests. diff --git a/agent/tests/deep_agent/test_guidance_lint.py b/agent/tests/deep_agent/test_guidance_lint.py index ac4431a..a779102 100644 --- a/agent/tests/deep_agent/test_guidance_lint.py +++ b/agent/tests/deep_agent/test_guidance_lint.py @@ -12,14 +12,16 @@ import sqlglot from deep_agent.agent import SYSTEM_PROMPT +from deep_agent.prompt_registry import local_prompt from deep_agent.resources import DEFAULT_SKILLS_DIR, EXPECTED_SKILLS from deep_agent.tools import DEEP_AGENT_TOOLS DOMAIN_TOOLS = {t.name for t in DEEP_AGENT_TOOLS} -HARNESS_TOOLS = {"task", "write_todos", "read_file", "ls", "submit_answer"} +HARNESS_TOOLS = {"task", "write_todos", "read_file", "ls", "submit_answer", "submit_verdict"} DOCS: dict[str, str] = { "system prompt": SYSTEM_PROMPT, + "validator prompt": local_prompt("validator"), **{f"skill {p.parent.name}": p.read_text(encoding="utf-8") for p in sorted(DEFAULT_SKILLS_DIR.glob("*/SKILL.md"))}, **{f"docstring {t.name}": t.description for t in DEEP_AGENT_TOOLS}, } @@ -47,6 +49,7 @@ (r"validate_sql_syntax", "the tool is validate_sql (#39)"), (r"needs_clarification", "clarifications are off by default; only the flag adds them to the prompt (#41)"), (r"AGENTS\.md|agent_memory", "there is no AGENTS.md memory; always-on guidance is the system prompt (#40)"), + (r"prefix pattern", "use every matching stored value, never a guessed prefix (#45)"), ] # Catalog-specific names: guidance must stay general text-to-SQL knowledge, not one deployment's data. @@ -99,7 +102,9 @@ def _sql_blocks(name: str, text: str) -> list[tuple[str, str]]: def test_guidance_contains_sql_examples(): - assert len(SQL_BLOCKS) >= 15 + # The parse check below must not pass vacuously: the system prompt and every skill carry checked SQL. + sources = {name.split("#")[0] for name, _ in SQL_BLOCKS} + assert {"system prompt", *(f"skill {s}" for s in EXPECTED_SKILLS)} <= sources @pytest.mark.parametrize("name, sql", SQL_BLOCKS, ids=[n for n, _ in SQL_BLOCKS]) diff --git a/agent/tests/deep_agent/test_latency.py b/agent/tests/deep_agent/test_latency.py index ec59068..534bae2 100644 --- a/agent/tests/deep_agent/test_latency.py +++ b/agent/tests/deep_agent/test_latency.py @@ -19,7 +19,7 @@ @pytest.mark.asyncio async def test_unused_builtin_tools_are_not_offered_to_the_model(scripted_model): - model = scripted_model(AIMessage("done")) + model = scripted_model(AIMessage("done"), AIMessage("done")) # second: reply to the submit reminder await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "t"}}) offered = set(model.bound_tool_names[-1]) assert not offered & EXCLUDED_BUILTIN_TOOLS diff --git a/agent/tests/deep_agent/test_prompts_and_catalog.py b/agent/tests/deep_agent/test_prompts_and_catalog.py index cb072aa..ecd05d0 100644 --- a/agent/tests/deep_agent/test_prompts_and_catalog.py +++ b/agent/tests/deep_agent/test_prompts_and_catalog.py @@ -21,9 +21,9 @@ @pytest.mark.asyncio async def test_catalog_is_in_every_model_call_but_not_in_history(scripted_model): model = scripted_model(AIMessage("", tool_calls=[{"name": "write_todos", "args": {"todos": []}, "id": "w"}]), - AIMessage("done")) + AIMessage("done"), AIMessage("done")) # last: reply to the submit reminder result = await create_deep_agent(model=model).ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "c"}}) - assert len(model.seen) == 2 + assert len(model.seen) == 3 assert all(TEST_CATALOG in system_text(seen) for seen in model.seen) assert all(TEST_CATALOG not in m.text for m in result["messages"]) # never duplicated into the message history assert "get_database_catalog" not in model.bound_tool_names[-1] @@ -121,14 +121,14 @@ def test_langfuse_unavailable_falls_back(langfuse_enabled, behaviour): async def test_prompt_label_change_takes_effect_without_rebuild(scripted_model, langfuse_enabled): served = {"text": local_prompt("system")} fake = MagicMock(get_prompt=MagicMock(side_effect=lambda *a, **k: _served(served["text"]))) - model = scripted_model(AIMessage("one"), AIMessage("two")) + model = scripted_model(AIMessage("one"), AIMessage("one"), AIMessage("two"), AIMessage("two")) # each + reminder reply with patch("agent.langfuse_client.langfuse_client", fake): agent = create_deep_agent(model=model) await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "p1"}}) served["text"] = "You are the NEW deep analyst prompt v4." await agent.ainvoke({"messages": [("user", "b")]}, {"configurable": {"thread_id": "p2"}}) - first, second = system_text(model.seen[0]), system_text(model.seen[1]) + first, second = system_text(model.seen[0]), system_text(model.seen[2]) assert first.startswith(local_prompt("system")[:80]) assert second.startswith("You are the NEW deep analyst prompt v4.") assert "Skills System" in second # harness / skills sections after our prompt are preserved @@ -185,7 +185,7 @@ def test_miss_expires_after_ttl(langfuse_enabled, monkeypatch): @pytest.mark.asyncio async def test_prompt_refresh_keeps_the_clarification_suffix(scripted_model, langfuse_enabled): fake = MagicMock(get_prompt=MagicMock(side_effect=lambda *a, **k: _served("NEW system prompt v5."))) - model = scripted_model(AIMessage("done")) + model = scripted_model(AIMessage("done"), AIMessage("done")) with patch("agent.langfuse_client.langfuse_client", fake): agent = create_deep_agent(model=model, clarifications_enabled=True) fake.get_prompt.side_effect = lambda *a, **k: _served("NEWER system prompt v6.") diff --git a/agent/tests/deep_agent/test_resources.py b/agent/tests/deep_agent/test_resources.py index 18a0a04..972b233 100644 --- a/agent/tests/deep_agent/test_resources.py +++ b/agent/tests/deep_agent/test_resources.py @@ -66,7 +66,7 @@ def test_skill_name_must_match_directory(skills_copy): @pytest.mark.asyncio async def test_skills_and_system_prompt_reach_the_model_without_memory(scripted_model): - model = scripted_model(AIMessage("done")) + model = scripted_model(AIMessage("done"), AIMessage("done")) # second: reply to the submit reminder agent = create_deep_agent(model=model) await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-prompt"}}) @@ -88,7 +88,7 @@ async def test_agent_cannot_write_skills(scripted_model): {"name": "write_file", "args": {"file_path": "/skills/evil/SKILL.md", "content": "x"}, "id": "w1"}, {"name": "edit_file", "args": {"file_path": "/skills/temporal-analyst/SKILL.md", "old_string": "Temporal", "new_string": "X"}, "id": "w2"}, ]) - model = scripted_model(write, AIMessage("done")) + model = scripted_model(write, AIMessage("done"), AIMessage("done")) agent = create_deep_agent(model=model) result = await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-write"}}) @@ -105,7 +105,7 @@ async def test_agent_can_read_a_skill_file(scripted_model): read = AIMessage("", tool_calls=[ {"name": "read_file", "args": {"file_path": "/skills/temporal-analyst/SKILL.md"}, "id": "r1"}, ]) - model = scripted_model(read, AIMessage("done")) + model = scripted_model(read, AIMessage("done"), AIMessage("done")) agent = create_deep_agent(model=model) result = await agent.ainvoke({"messages": [("user", "hi")]}, {"configurable": {"thread_id": "t-read"}}) diff --git a/agent/tests/deep_agent/test_runtime_context.py b/agent/tests/deep_agent/test_runtime_context.py index 9214f78..9f1e0df 100644 --- a/agent/tests/deep_agent/test_runtime_context.py +++ b/agent/tests/deep_agent/test_runtime_context.py @@ -90,7 +90,7 @@ def test_date_is_computed_in_jerusalem_time(monkeypatch): @pytest.mark.asyncio async def test_date_is_injected_per_model_call_not_at_construction(scripted_model, monkeypatch): monkeypatch.setattr(context_module, "datetime", _FrozenDatetime) - model = scripted_model(AIMessage("first"), AIMessage("second")) + model = scripted_model(AIMessage("first"), AIMessage("first"), AIMessage("second"), AIMessage("second")) # + reminder replies agent = create_deep_agent(model=model) # built "yesterday" _FrozenDatetime.instant = datetime(2026, 10, 20, 20, 30, tzinfo=timezone.utc) # 23:30 Oct 20 in Israel @@ -102,15 +102,15 @@ def last_human(messages): return next(m for m in reversed(messages) if m.type == "human").text assert last_human(model.seen[0]).startswith("[Today's date: 2026-10-20") - assert last_human(model.seen[1]).startswith("[Today's date: 2026-10-21") - assert last_human(model.seen[1]).endswith("b") + assert last_human(model.seen[2]).startswith("[Today's date: 2026-10-21") + assert last_human(model.seen[2]).endswith("b") # The system prompt is byte-identical across days, so provider prompt caching keeps working. - assert system_text(model.seen[0]) == system_text(model.seen[1]) + assert system_text(model.seen[0]) == system_text(model.seen[2]) assert "Today's date" not in system_text(model.seen[1]) @pytest.mark.asyncio async def test_date_prefix_is_not_persisted_to_state(scripted_model): - agent = create_deep_agent(model=scripted_model(AIMessage("ok"))) + agent = create_deep_agent(model=scripted_model(AIMessage("ok"), AIMessage("ok"))) result = await agent.ainvoke({"messages": [("user", "שאלה")]}, {"configurable": {"thread_id": "p1"}}) assert result["messages"][0].text == "שאלה" diff --git a/agent/tests/deep_agent/test_service.py b/agent/tests/deep_agent/test_service.py index 17fb2a1..f8b5978 100644 --- a/agent/tests/deep_agent/test_service.py +++ b/agent/tests/deep_agent/test_service.py @@ -100,6 +100,7 @@ async def test_turn_without_new_answer_does_not_repeat_the_previous_one(scripted AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), _answer(), AIMessage("small talk, no answer"), + AIMessage("still no answer"), # reply to the submit reminder ) agent = create_deep_agent(model=model) with patch.object(tools, "execute_query_sync", return_value=OK): @@ -222,3 +223,18 @@ async def test_threads_survive_a_restart_with_postgres(scripted_model, monkeypat state = await second_process.aget_state({"configurable": {"thread_id": thread}}) assert [m.text for m in state.values["messages"] if m.type == "human"] == ["שאלה ראשונה"] await service._pg_pool.close() + + +@pytest.mark.asyncio +async def test_reviewer_tools_are_labelled_in_the_stream(scripted_model, published): + main = scripted_model( + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), _answer()) + reviewer = scripted_model( + AIMessage("", tool_calls=[{"name": "get_sample_rows", "args": {"table_name": "orders"}, "id": "r1"}]), + AIMessage("", tool_calls=[{"name": "submit_verdict", "args": {"verdict": "pass"}, "id": "v1"}]), + ) + agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) + with patch.object(tools, "execute_query_sync", return_value=OK): + r = await run_deep_chat(connection_id=89, query="q", thread_id="deep-t6", agent=agent) + assert r["execution_path"] == ["deep:execute_trino_query", "deep:review:get_sample_rows"] + assert r["semantic_validation"]["verdict"] == "passed" diff --git a/agent/tests/deep_agent/test_validator.py b/agent/tests/deep_agent/test_validator.py new file mode 100644 index 0000000..bf3690b --- /dev/null +++ b/agent/tests/deep_agent/test_validator.py @@ -0,0 +1,382 @@ +"""Independent semantic review of answers (deep_agent.validator): "always" gate and "on_demand" subagent.""" + +from unittest.mock import patch + +import itertools +from types import SimpleNamespace +from contextlib import contextmanager + +import pytest +from langchain_core.messages import AIMessage + +from core.trino import TrinoExecutionResult +from deep_agent import answer, tools +from deep_agent.agent import create_deep_agent +from deep_agent.answer import ANSWER_RECEIVED, answer_schema, render_markdown, validation_summary +from deep_agent.observability import run_metrics +from deep_agent.validator import VALIDATOR_TOOLS, SubmitVerdict, feedback_text + +SQL = "SELECT COUNT(*) AS n FROM orders WHERE status = 'shipped'" +FIXED = "SELECT COUNT(DISTINCT order_id) AS n FROM orders WHERE status = 'shipped'" +_ids = itertools.count() + + +def _trino(*args, **kwargs): + """A successful execution with a fresh query id per run, like real Trino.""" + return TrinoExecutionResult(success=True, rows=[[42]], columns=["n"], row_count=1, query_id=f"q{next(_ids)}") + + +@contextmanager +def _fake_trino(): + """Every execution in the run (agent, reviewer, re-execution) — never the real Trino.""" + with patch.object(tools, "execute_query_sync", side_effect=_trino), \ + patch.object(answer, "execute_query_sync", side_effect=_trino): + yield +ISSUE = {"problem": "סופרים שורות ולא הזמנות", "evidence": "COUNT(*)=42 אבל COUNT(DISTINCT order_id)=40"} + + +def _execute(sql, call_id="e1"): + return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": sql}, "id": call_id}]) + + +def _submit(sql=SQL, call_id="s1", **extra): + return AIMessage("", tool_calls=[{"name": "submit_answer", "id": call_id, "args": { + "sql": sql, "explanation_he": "מספר ההזמנות שנשלחו", "confidence": "high", **extra}}]) + + +def _verdict(verdict, issues=(), call_id="v1"): + return AIMessage("", tool_calls=[{"name": "submit_verdict", "id": call_id, + "args": {"verdict": verdict, "issues": list(issues)}}]) + + +async def _run(main, reviewer, question="כמה הזמנות נשלחו?", thread="t"): + agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) + with _fake_trino(): + return await agent.ainvoke({"messages": [("user", question)]}, {"configurable": {"thread_id": thread}}) + + +def _texts(messages): + return "\n".join(m.text for m in messages) + + +# ── always: every submitted answer is reviewed ─────────────────────────────── + +@pytest.mark.asyncio +async def test_pass_ends_the_run(scripted_model): + main = scripted_model(AIMessage("my private reasoning", tool_calls=_execute(SQL).tool_calls), _submit()) + reviewer = scripted_model(_verdict("pass")) + state = await _run(main, reviewer) + + final = state["final_result"] + assert final["status"] == "matched" + assert final["semantic_validation"] == {"verdict": "passed", "rounds": 1, "issues": [], "response": None, + "reason": None, "reviewed_final_sql": True} + # Fresh context: the reviewer sees the request, the SQL, the explanation and the rows — not the reasoning. + review = _texts(reviewer.seen[0]) + assert "כמה הזמנות נשלחו?" in review and SQL in review and "מספר ההזמנות שנשלחו" in review and "[42]" in review + assert "my private reasoning" not in review + assert '"catalog"."schema"."orders"' in review # the catalog is in the reviewer's system prompt + assert state["messages"][-1].text == ANSWER_RECEIVED + + +@pytest.mark.asyncio +async def test_fail_sends_feedback_and_the_revision_is_reviewed_again(scripted_model): + main = scripted_model(_execute(SQL), _submit(), _execute(FIXED, "e2"), _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("fail", [ISSUE]), _verdict("pass", call_id="v2")) + state = await _run(main, reviewer) + + # The model saw the review instead of "Answer received." for its first submission. + after_fail = _texts(main.seen[2]) + assert ISSUE["problem"] in after_fail and ISSUE["evidence"] in after_fail + first_submission = next(m for m in state["messages"] if m.type == "tool" and m.tool_call_id == "s1") + assert first_submission.text == feedback_text([ISSUE]) + + final = state["final_result"] + assert final["sql"] == FIXED and final["status"] == "matched" + assert final["semantic_validation"]["verdict"] == "passed" and final["semantic_validation"]["rounds"] == 2 + assert FIXED in _texts(reviewer.seen[1]) + + +@pytest.mark.asyncio +async def test_resubmitting_the_same_sql_with_a_justification_is_a_dispute(scripted_model): + main = scripted_model(_execute(SQL), _submit(), + _submit(SQL, "s2", validation_response="כל שורה היא הזמנה אחת, אין כפילויות")) + reviewer = scripted_model(_verdict("fail", [ISSUE])) + state = await _run(main, reviewer) + + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "disputed" and review["rounds"] == 1 + assert review["issues"] == [ISSUE] and review["response"] == "כל שורה היא הזמנה אחת, אין כפילויות" + assert len(reviewer.seen) == 1 # the dispute ends the loop without another review + shown = render_markdown(state["final_result"]) + assert "בדיקה עצמאית העלתה הסתייגות" in shown and ISSUE["problem"] in shown and "תגובת הסוכן" in shown + + +@pytest.mark.asyncio +async def test_stopping_after_a_fail_keeps_the_answer_marked_failed(scripted_model): + main = scripted_model(_execute(SQL), _submit(), AIMessage("I think it is fine.")) + reviewer = scripted_model(_verdict("fail", [ISSUE])) + state = await _run(main, reviewer) + + final = state["final_result"] + assert final["sql"] == SQL and final["executed"] is True + assert final["semantic_validation"]["verdict"] == "failed" + assert "בדיקה עצמאית מצאה בעיות בתשובה" in render_markdown(final) + + +@pytest.mark.asyncio +async def test_review_limit_is_optional(scripted_model, monkeypatch): + from agent.config import settings + + monkeypatch.setattr(settings, "DEEP_AGENT_VALIDATOR_MAX_ROUNDS", 1) + main = scripted_model(_execute(SQL), _submit(), _execute(FIXED, "e2"), _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("fail", [ISSUE])) + state = await _run(main, reviewer) + + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "not_validated" and review["reason"] == "review limit reached (1)" + assert len(reviewer.seen) == 1 + + +@pytest.mark.asyncio +async def test_a_broken_review_does_not_lose_the_answer(scripted_model): + main = scripted_model(_execute(SQL), _submit()) + reviewer = scripted_model() # no scripted reply: the reviewer's model call raises + state = await _run(main, reviewer) + + final = state["final_result"] + assert final["status"] == "matched" + assert final["semantic_validation"]["verdict"] == "not_validated" + assert final["semantic_validation"]["reason"] + + +@pytest.mark.asyncio +async def test_follow_up_turn_is_reviewed_with_its_context(scripted_model): + main = scripted_model(_execute(SQL), _submit(), _execute(FIXED, "e2"), _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) + agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) + config = {"configurable": {"thread_id": "follow-up"}} + with _fake_trino(): + await agent.ainvoke({"messages": [("user", "כמה הזמנות נשלחו?")]}, config) + state = await agent.ainvoke({"messages": [("user", "ובלי כפילויות?")]}, config) + + second = _texts(reviewer.seen[1]) + assert "Earlier user messages" in second and "כמה הזמנות נשלחו?" in second + assert "Current user request\nובלי כפילויות?" in second + assert state["final_result"]["semantic_validation"]["rounds"] == 1 # counted per turn + + +# ── on_demand: the agent calls the reviewer through `task` ─────────────────── + +def _review(sql=SQL, call_id="r1", extra=""): + brief = f"User request: כמה הזמנות נשלחו?\n```sql\n{sql}\n```\nResult: [[42]]{extra}" + return {"name": "task", "id": call_id, "args": {"description": brief, "subagent_type": "semantic-validator"}} + + +async def _run_on_demand(main, reviewer, thread="od"): + agent = create_deep_agent(model=main, semantic_validation="on_demand", validator_model=reviewer) + with _fake_trino(): + return await agent.ainvoke({"messages": [("user", "כמה הזמנות נשלחו?")]}, {"configurable": {"thread_id": thread}}) + + +@pytest.mark.asyncio +async def test_on_demand_review_returns_the_verdict_to_the_agent(scripted_model): + main = scripted_model(_execute(SQL), AIMessage("my private reasoning", tool_calls=[_review()]), _submit()) + reviewer = scripted_model(_verdict("pass")) + state = await _run_on_demand(main, reviewer) + + assert '"verdict":"pass"' in _texts(main.seen[2]) # the verdict came back as the task result (JSON) + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "passed" and review["rounds"] == 1 and review["reviewed_final_sql"] is True + seen = _texts(reviewer.seen[0]) + assert SQL in seen and "my private reasoning" not in seen # fresh context: only the brief + assert '"catalog"."schema"."orders"' in seen + assert "`semantic-validator` subagent is available" in _texts(main.seen[0]) # the Phase 6 nudge + + +@pytest.mark.asyncio +async def test_on_demand_review_of_a_different_sql_does_not_count(scripted_model): + main = scripted_model(_execute(SQL), AIMessage("", tool_calls=[_review()]), + _execute(FIXED, "e2"), _submit(FIXED)) + reviewer = scripted_model(_verdict("fail", [ISSUE])) + state = await _run_on_demand(main, reviewer) + + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "not_validated" and review["reviewed_final_sql"] is False + assert review["reason"] == "the final SQL changed after the last review" and review["rounds"] == 1 + assert "בדיקה עצמאית" not in render_markdown(state["final_result"]) # no warning about issues that were fixed + assert run_metrics([], 1.0, state["final_result"]).semantic_validation_passed is None + + +@pytest.mark.asyncio +async def test_on_demand_without_a_review(scripted_model): + state = await _run_on_demand(scripted_model(_execute(SQL), _submit()), scripted_model()) + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "not_validated" and review["rounds"] == 0 and review["reason"] == "no review" + + +@pytest.mark.asyncio +async def test_on_demand_failed_review_of_the_final_sql_is_shown(scripted_model): + main = scripted_model(_execute(SQL), AIMessage("", tool_calls=[_review()]), _submit()) + state = await _run_on_demand(main, scripted_model(_verdict("fail", [ISSUE]))) + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "failed" and review["issues"] == [ISSUE] + assert "בדיקה עצמאית מצאה בעיות בתשובה" in render_markdown(state["final_result"]) + + +@pytest.mark.asyncio +async def test_parallel_on_demand_reviews_are_both_recorded(policy_model): + def main_policy(messages): + tool_names = [m.name for m in messages if m.type == "tool"] + if not tool_names: + return _execute(SQL) + if "task" not in tool_names: + return AIMessage("", tool_calls=[_review(call_id="r1"), _review(FIXED, "r2")]) + return _submit() + + def reviewer_policy(messages): + return _verdict("pass") + + state = await _run_on_demand(policy_model(main_policy), policy_model(reviewer_policy)) + records = state["semantic_validations"] + assert len(records) == 2 and len({r["id"] for r in records}) == 2 + assert state["final_result"]["semantic_validation"]["rounds"] == 2 + + +def test_modes_wire_the_reviewer(scripted_model): + for mode, subagent in [("on_demand", True), ("always", False), ("off", False)]: + agent = create_deep_agent(model=scripted_model(), semantic_validation=mode) + tools_desc = str(agent.get_graph().nodes) # built without errors in every mode + assert tools_desc + assert ("semantic-validator" in _task_description(agent)) is subagent, mode + + +def _task_description(agent) -> str: + node = agent.nodes["tools"].bound + task = node.tools_by_name.get("task") + return task.description if task else "" + + +def test_reviewer_tools_are_read_only_diagnostics(): + assert {t.name for t in VALIDATOR_TOOLS} == { + "execute_trino_query", "get_sample_rows", "get_column_distinct_values", "search_column_values", + "get_column_profile"} + + +def test_fail_verdict_needs_evidence(): + with pytest.raises(ValueError): + SubmitVerdict(verdict="fail", issues=[]) + assert SubmitVerdict(verdict="pass").issues == [] + + +def test_validation_response_only_exists_with_validation(): + assert "validation_response" in answer_schema(False, True).model_fields # "always" mode only + assert "validation_response" not in answer_schema(False, False).model_fields + + +def test_summary_and_scores(): + assert validation_summary(None) is None # reviewer off + assert validation_summary([])["verdict"] == "not_validated" + unreviewed = run_metrics([], 1.0, {"semantic_validation": validation_summary([])}) + assert unreviewed.semantic_validation_passed is None and unreviewed.validation_rounds == 0 + metrics = run_metrics([], 1.0, {"semantic_validation": {"verdict": "passed", "rounds": 2}}) + assert metrics.semantic_validation_passed is True and metrics.validation_rounds == 2 + off = run_metrics([], 1.0, {"semantic_validation": None}) + assert off.semantic_validation_passed is None and off.validation_rounds is None # no score when off + + +# ── rejected submit_answer arguments are retried (every turn) ──────────────── + +@pytest.mark.asyncio +@pytest.mark.parametrize("validation", ["off", "always", "on_demand"]) +async def test_invalid_submission_is_retried_on_every_turn(scripted_model, validation): + bad = AIMessage("", tool_calls=[{"name": "submit_answer", "id": "bad", "args": {"sql": SQL}}]) # missing fields + main = scripted_model(_execute(SQL), bad, _submit(), _execute(SQL, "e2"), bad, _submit(call_id="s2")) + reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) + agent = create_deep_agent(model=main, semantic_validation=validation, validator_model=reviewer) + config = {"configurable": {"thread_id": f"retry-{validation}"}} + with _fake_trino(): + first = await agent.ainvoke({"messages": [("user", "q1")]}, config) + second = await agent.ainvoke({"messages": [("user", "q2")]}, config) + assert first["final_result"]["status"] == "matched" + assert second["final_result"]["status"] == "matched" + + +@pytest.mark.asyncio +async def test_parallel_general_purpose_tasks_do_not_collide(policy_model): + """Every subagent returns the parent's state keys; two in one step must not be rejected.""" + def main_policy(messages): + if not [m for m in messages if m.type == "tool"]: + return AIMessage("", tool_calls=[ + {"name": "task", "id": f"g{i}", "args": {"description": "look", "subagent_type": "general-purpose"}} + for i in (1, 2)]) + return AIMessage("done") + + agent = create_deep_agent(model=policy_model(main_policy), semantic_validation="off") + state = await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "gp"}}) + assert [m.name for m in state["messages"] if m.type == "tool"] == ["task", "task"] + + +# ── submit reminder (model ends with text instead of the submit call) ──────── + +def test_default_mode_is_always(): + from agent.config import AgentSettings + + assert AgentSettings.model_fields["DEEP_AGENT_SEMANTIC_VALIDATION"].default == "always" + + +@pytest.mark.asyncio +async def test_reviewer_that_forgets_its_verdict_is_reminded_once(scripted_model): + reviewer = scripted_model(AIMessage("I found the join is broken."), _verdict("fail", [ISSUE])) + main = scripted_model(_execute(SQL), _submit(), _submit(SQL, "s2", validation_response="בטוח")) + state = await _run(main, reviewer) + + assert "submit_verdict" in _texts(reviewer.seen[1]) # the reminder + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "disputed" and review["issues"] == [ISSUE] # the verdict was not lost + + +@pytest.mark.asyncio +async def test_main_agent_that_answers_in_text_is_reminded_once(scripted_model): + main = scripted_model(_execute(SQL), AIMessage("There are 42 shipped orders."), _submit()) + agent = create_deep_agent(model=main, semantic_validation="off") + with _fake_trino(): + state = await agent.ainvoke({"messages": [("user", "כמה הזמנות נשלחו?")]}, {"configurable": {"thread_id": "rm"}}) + assert state["final_result"]["status"] == "matched" + reminder = main.seen[2][-1] + assert reminder.type == "human" and reminder.name == "submit_reminder" and "submit_answer" in reminder.text + assert not reminder.text.startswith("[Today") # the date stays on the user's message + assert main.seen[2][[m.type for m in main.seen[2]].index("human")].text.startswith("[Today") + + +@pytest.mark.asyncio +async def test_reminder_is_sent_only_once_per_turn(scripted_model): + main = scripted_model(AIMessage("no"), AIMessage("still no"), AIMessage("next turn"), AIMessage("still not")) + agent = create_deep_agent(model=main, semantic_validation="off") + config = {"configurable": {"thread_id": "once"}} + first = await agent.ainvoke({"messages": [("user", "q1")]}, config) + second = await agent.ainvoke({"messages": [("user", "q2")]}, config) + reminders = [m for m in second["messages"] if getattr(m, "name", None) == "submit_reminder"] + assert len(reminders) == 2 # one per turn, not more + assert first["final_result"]["status"] == second["final_result"]["status"] == "no_answer" + assert len(main.seen) == 4 + + +@pytest.mark.asyncio +async def test_no_reminder_after_a_failed_review(scripted_model): + """The agent may stop after a fail: its (failed) answer stands — that is not a missing answer.""" + main = scripted_model(_execute(SQL), _submit(), AIMessage("I think it is fine.")) + state = await _run(main, scripted_model(_verdict("fail", [ISSUE]))) + assert not [m for m in state["messages"] if getattr(m, "name", None) == "submit_reminder"] + assert state["final_result"]["semantic_validation"]["verdict"] == "failed" + + +def test_reminder_is_not_the_users_words(): + from langchain_core.messages import HumanMessage + + from deep_agent.answer import current_turn + from deep_agent.context import REMINDER_NAME, user_request + + messages = [HumanMessage("the question"), AIMessage("text"), HumanMessage("submit!", name=REMINDER_NAME)] + assert current_turn(messages) == messages[1:] + assert user_request(SimpleNamespace(state={"messages": messages})) == "the question" diff --git a/backend/app/routers/agent.py b/backend/app/routers/agent.py index a3dcf38..26b7a4d 100644 --- a/backend/app/routers/agent.py +++ b/backend/app/routers/agent.py @@ -80,6 +80,7 @@ class ChatResponse(BaseModel): confidence: str | None = None # Deep Agent self-reported confidence (high / medium / low) executed: bool | None = None # Deep Agent: the submitted final SQL ran and the rows are Trino's recovered_from_text: bool | None = None # Deep Agent: final answer was written as text and recovered + semantic_validation: dict | None = None # Deep Agent: independent review (verdict, rounds, issues, response) # --------------------------------------------------------------------------- From 9565089d12a844a36c94cfedaa9c3064a95dc23a Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 29 Oct 2026 16:19:39 +0200 Subject: [PATCH 22/37] docs(deep-agent): Israel-time date boundaries, coordinate rules and geo parsing/performance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merged from the Trino text-to-SQL skill, each claim checked on our Trino (480): - system prompt: half-open time filters on the raw column; named dates are Israel time (TIMESTAMP '... Asia/Jerusalem', not UTC — 455 vs 452 alerts for July 1-14); coordinate order and degrees vs metres; error row for st_contains on SphericalGeography - temporal-analyst: Israel-time boundaries, Israel-day bucketing, UTC date partitions - spatial-analyst: ST_Buffer in degrees, km² areas, WKT/WKB/GeoJSON parsing (from_geojson_geometry returns SphericalGeography — wrap in to_geometry for containment), bbox pre-filter, time-filter CTE before spatial joins, bing-tile proximity joins - guidance lint: placeholder regex no longer swallows `a <= x AND b >` Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/prompts/system.md | 3 ++ .../skills/spatial-analyst/SKILL.md | 25 ++++++++++++++ .../skills/temporal-analyst/SKILL.md | 33 +++++++++++++++++++ agent/tests/deep_agent/test_guidance_lint.py | 2 +- 4 files changed, 62 insertions(+), 1 deletion(-) diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index 9d6c949..b77985a 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -84,6 +84,8 @@ The user's word is almost never the stored string — the value may be spelled d - **Per-entity ratios**: mind the granularity of numerator vs denominator — "orders per resident" is `COUNT(orders) / SUM(population)`, not `AVG(count_per_row)`. When the denominator comes from another table, aggregate each side in its own CTE, then join and divide. - **Set operations**: prefer `UNION ALL`; `UNION` adds an expensive distributed de-duplication — use it only when de-duplication is required. - **Arrays**: membership `contains(arr, 'v')`; expand with `CROSS JOIN UNNEST(arr) AS t(element)`. +- **Time filters**: a half-open range on the raw column (`col >= start AND col < end`), never a function around the filtered column. Dates the user names are **Israel time** — write `TIMESTAMP '2024-07-01 00:00:00 Asia/Jerusalem'`, not `... UTC` (2–3 hours off at each end). Details in the `temporal-analyst` skill. +- **Coordinates**: `ST_Point(lon, lat)` and WKT are longitude first; `great_circle_distance(lat1, lon1, lat2, lon2)` is latitude first and returns km. Distances and areas on plain geometry are in degrees — wrap in `to_spherical_geography(...)` for metres. Details in the `spatial-analyst` skill. - **When several logic paths seem plausible** (INNER vs LEFT JOIN, different grouping), run 2–3 variants with `LIMIT 10` and compare before choosing — don't guess. **Functions that do NOT exist in Trino:** @@ -131,6 +133,7 @@ The user's word is almost never the stored string — the value may be spelled d | `INVALID_CAST_ARGUMENT` (`Value cannot be cast to timestamp`) | The text has `T` / `Z` or a custom format — `from_iso8601_timestamp(col)` or `date_parse(col, fmt)` | | `INVALID_FUNCTION_ARGUMENT` (`Invalid format` in `date_parse`) | Wrong format specifiers — MySQL style, `%i` is minutes (not `%M`) | | `INVALID_FUNCTION_ARGUMENT` (`Latitude must be between -90 and 90`) | Coordinates swapped — `ST_Point(lon, lat)`, longitude first | +| `FUNCTION_NOT_FOUND` (`Unexpected parameters (SphericalGeography...)` for `st_contains` etc.) | Containment needs geometry — keep `ST_Point` / `ST_GeometryFromText`, or `to_geometry(...)` a geography | | `DIVISION_BY_ZERO` | Wrap the divisor in `NULLIF(divisor, 0)` | | `SUBQUERY_MULTIPLE_ROWS` | Aggregate or `LIMIT 1` the scalar subquery, or turn it into a JOIN | | `EXCEEDED_*` (memory / time limits) | Narrow the time or partition range, select fewer columns, pre-aggregate in a CTE | diff --git a/agent/src/deep_agent/skills/spatial-analyst/SKILL.md b/agent/src/deep_agent/skills/spatial-analyst/SKILL.md index e5b0511..6c06232 100644 --- a/agent/src/deep_agent/skills/spatial-analyst/SKILL.md +++ b/agent/src/deep_agent/skills/spatial-analyst/SKILL.md @@ -136,6 +136,31 @@ When the user asks for relative spatial relations, translate the intent into pre - **Never**: `ST_GeomFromText()` or `ST_PolygonFromText()` — they do not exist in Trino. - `ST_Distance` on WGS84 geometries returns **degrees**, not meters. For meters, wrap both sides in `to_spherical_geography(...)`. - `ST_Contains` works on `geometry` (degrees), **NOT** on `SphericalGeography`. +- `ST_Buffer(geom, r)` takes **degrees**: `ST_Buffer(p, 0.01)` is about 1 km, not 0.01 km. For "within X metres" use a + distance in metres (`great_circle_distance` or spherical `ST_Distance`) instead of a buffer. +- Area / length in real units: `ST_Area(to_spherical_geography(g)) / 1e6` is km², `ST_Length(to_spherical_geography(g))` is metres. + +### Parsing geometries +- WKT text → `ST_GeometryFromText(col)`; unparsable rows → `try(ST_GeometryFromText(col))` and skip the NULLs. +- WKB hex string → `ST_GeomFromBinary(from_hex(col))`. +- GeoJSON text → `from_geojson_geometry(col)` returns a **SphericalGeography**: for `ST_Contains` and other geometry + functions wrap it, `to_geometry(from_geojson_geometry(col))`. + +### Performance +- **Cheap bounding box first**: filter the raw numeric `lat` / `lon` columns with `BETWEEN` before any `ST_` function or + distance. Around Israel, 1° latitude ≈ 111 km and 1° longitude ≈ 94 km. +- Filter time (and other plain conditions) in a CTE first, so the spatial join only sees the rows it needs. +- Large point-to-point proximity joins: join on a bing tile first, then check the exact distance + (`bing_tile_quadkey(bing_tile_at(lat, lon, 15))` on both sides; pairs across tile edges need `bing_tiles_around`). + +```sql +SELECT e.event_id, great_circle_distance(e.lat, e.lon, 32.08, 34.78) AS dist_km +FROM "catalog"."schema"."events" e +WHERE e.lat BETWEEN 32.05 AND 32.11 + AND e.lon BETWEEN 34.74 AND 34.82 + AND great_circle_distance(e.lat, e.lon, 32.08, 34.78) <= 3 +ORDER BY dist_km +``` ### Spatial Joins Acceleration Put `ST_Contains` directly in the `JOIN ... ON` clause so Trino invokes its internal spatial join optimization: diff --git a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md index c5c56d0..54e8064 100644 --- a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md +++ b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md @@ -115,10 +115,43 @@ ORDER BY 1 `year(d)`, `month(d)`, `day_of_week(d)` and `extract(year FROM d)` are fine in `SELECT` and `GROUP BY` — just not in `WHERE` on a native column you are filtering. +Group by the **Israel** day / hour, not the UTC one — convert before truncating: + +```sql +SELECT date_trunc('day', event_at AT TIME ZONE 'Asia/Jerusalem') AS day_il, count(*) AS events +FROM "catalog"."schema"."events" +GROUP BY 1 +ORDER BY 1 +``` + --- ## Time zones +**Dates and periods the user names are Israel time.** "On July 1st", "the first two weeks of July", "yesterday" start +and end at midnight in Israel, not in UTC. Write the boundaries as Israel-time literals and let Trino convert them: + +```sql +SELECT count(*) AS events +FROM "catalog"."schema"."events" +WHERE event_at >= TIMESTAMP '2024-07-01 00:00:00 Asia/Jerusalem' + AND event_at < TIMESTAMP '2024-07-15 00:00:00 Asia/Jerusalem' +``` + +`TIMESTAMP '... UTC'` boundaries are off by 2–3 hours at each end and change the counts. The session time zone is +Israel, so `current_date`, `current_timestamp` and `date_trunc('day', current_timestamp)` are already Israel time. + +If a table is partitioned by a UTC date string (e.g. `dt`), an Israel day spans two UTC partitions — widen the +partition filter by a day and keep the exact Israel-time filter on the timestamp column: + +```sql +SELECT count(*) AS events +FROM "catalog"."schema"."events" +WHERE dt >= '2024-04-30' AND dt <= '2024-05-01' + AND event_at >= TIMESTAMP '2024-05-01 00:00:00 Asia/Jerusalem' + AND event_at < TIMESTAMP '2024-05-02 00:00:00 Asia/Jerusalem' +``` + A naive `timestamp` has no zone. To treat it as UTC and show Israel local time: ```sql diff --git a/agent/tests/deep_agent/test_guidance_lint.py b/agent/tests/deep_agent/test_guidance_lint.py index a779102..d78c698 100644 --- a/agent/tests/deep_agent/test_guidance_lint.py +++ b/agent/tests/deep_agent/test_guidance_lint.py @@ -110,5 +110,5 @@ def test_guidance_contains_sql_examples(): @pytest.mark.parametrize("name, sql", SQL_BLOCKS, ids=[n for n, _ in SQL_BLOCKS]) def test_guidance_sql_parses_as_trino(name, sql): # Template placeholders like stand for a boolean expression. - sql = re.sub(r"<[^<>]+>", "1 = 1", sql) + sql = re.sub(r"<[A-Za-z_][\w ]*>", "1 = 1", sql) # placeholders only — not `a <= x AND b >= y` sqlglot.parse_one(sql, read="trino") From 414f175d35df5b438e81b3a474f9b990ff9ec62b Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Thu, 29 Oct 2026 16:55:17 +0200 Subject: [PATCH 23/37] refactor(deep-agent): group into tools/ answer/ validator/ middleware/ prompts/, drop 7 unused tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pure move/split — no behaviour change: - tools/: sql, metadata, enrichment, location (+ envelope, trino_errors); __init__ holds DEEP_AGENT_TOOLS - answer/: schema, verification, middleware, render - validator/: reviewer (the reviewer agent) and modes (always gate / on_demand subagent) - middleware/: catalog, tool_filter; prompts/: system.md, validator.md + registry - current_turn() and the tool Runtime type moved to context.py - removed the 7 unregistered metadata tools (get_database_tables, get_table_columns, get_table_profile, get_table_relationships, search_metadata, search_business_terms, search_knowledge_pairs) and their tests; the catalog already carries their information - tests patch Trino / Jeen in the module that uses them; README code map Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 19 +- agent/scripts/sync_deep_agent_prompts.py | 2 +- agent/src/agent/config.py | 4 +- agent/src/deep_agent/agent.py | 29 +- agent/src/deep_agent/answer.py | 436 ------------ agent/src/deep_agent/answer/__init__.py | 8 + agent/src/deep_agent/answer/middleware.py | 167 +++++ agent/src/deep_agent/answer/render.py | 45 ++ agent/src/deep_agent/answer/schema.py | 92 +++ agent/src/deep_agent/answer/verification.py | 154 +++++ agent/src/deep_agent/cli.py | 2 +- agent/src/deep_agent/context.py | 20 +- agent/src/deep_agent/middleware/__init__.py | 9 + .../deep_agent/{ => middleware}/catalog.py | 0 .../{ => middleware}/tool_filter.py | 0 agent/src/deep_agent/observability.py | 4 +- agent/src/deep_agent/prompts/__init__.py | 4 + .../registry.py} | 2 +- agent/src/deep_agent/service.py | 6 +- agent/src/deep_agent/tools.py | 634 ------------------ agent/src/deep_agent/tools/__init__.py | 34 + agent/src/deep_agent/tools/enrichment.py | 101 +++ agent/src/deep_agent/{ => tools}/envelope.py | 2 +- agent/src/deep_agent/tools/location.py | 37 + agent/src/deep_agent/tools/metadata.py | 130 ++++ agent/src/deep_agent/tools/sql.py | 212 ++++++ .../deep_agent/{ => tools}/trino_errors.py | 2 +- agent/src/deep_agent/validator.py | 300 --------- agent/src/deep_agent/validator/__init__.py | 32 + agent/src/deep_agent/validator/modes.py | 149 ++++ agent/src/deep_agent/validator/reviewer.py | 140 ++++ agent/tests/deep_agent/conftest.py | 2 +- agent/tests/deep_agent/test_answer.py | 20 +- agent/tests/deep_agent/test_catalog_state.py | 3 +- agent/tests/deep_agent/test_guidance_lint.py | 2 +- agent/tests/deep_agent/test_latency.py | 13 +- agent/tests/deep_agent/test_observability.py | 24 +- .../deep_agent/test_prompts_and_catalog.py | 10 +- .../tests/deep_agent/test_runtime_context.py | 4 +- agent/tests/deep_agent/test_service.py | 20 +- agent/tests/deep_agent/test_tool_contracts.py | 55 +- agent/tests/deep_agent/test_trino_errors.py | 18 +- agent/tests/deep_agent/test_trino_tools.py | 11 +- agent/tests/deep_agent/test_validator.py | 24 +- 44 files changed, 1476 insertions(+), 1506 deletions(-) delete mode 100644 agent/src/deep_agent/answer.py create mode 100644 agent/src/deep_agent/answer/__init__.py create mode 100644 agent/src/deep_agent/answer/middleware.py create mode 100644 agent/src/deep_agent/answer/render.py create mode 100644 agent/src/deep_agent/answer/schema.py create mode 100644 agent/src/deep_agent/answer/verification.py create mode 100644 agent/src/deep_agent/middleware/__init__.py rename agent/src/deep_agent/{ => middleware}/catalog.py (100%) rename agent/src/deep_agent/{ => middleware}/tool_filter.py (100%) create mode 100644 agent/src/deep_agent/prompts/__init__.py rename agent/src/deep_agent/{prompt_registry.py => prompts/registry.py} (98%) delete mode 100644 agent/src/deep_agent/tools.py create mode 100644 agent/src/deep_agent/tools/__init__.py create mode 100644 agent/src/deep_agent/tools/enrichment.py rename agent/src/deep_agent/{ => tools}/envelope.py (97%) create mode 100644 agent/src/deep_agent/tools/location.py create mode 100644 agent/src/deep_agent/tools/metadata.py create mode 100644 agent/src/deep_agent/tools/sql.py rename agent/src/deep_agent/{ => tools}/trino_errors.py (96%) delete mode 100644 agent/src/deep_agent/validator.py create mode 100644 agent/src/deep_agent/validator/__init__.py create mode 100644 agent/src/deep_agent/validator/modes.py create mode 100644 agent/src/deep_agent/validator/reviewer.py diff --git a/agent/README.md b/agent/README.md index d96db26..3ca63d1 100644 --- a/agent/README.md +++ b/agent/README.md @@ -38,6 +38,23 @@ graph TD ## Running the deep agent locally +Code layout (`src/deep_agent/`): + +``` +agent.py create_deep_agent(): wires model, tools, prompt, skills, middleware, subagents +service.py run_deep_chat(): serving behind chat_with_agent (threads, timeout_s, streaming, response) +cli.py developer CLI +context.py per-request context, state fields, user-message helpers, date prefix +observability.py Langfuse run config and scores +resources.py skills wiring (read-only /skills/) +tools/ what the model can call: sql, metadata, enrichment, location (+ envelope, trino_errors) +answer/ the final answer: schema, verification (did the SQL run), middleware, render +validator/ independent semantic review: reviewer (the agent), modes (always / on_demand) +middleware/ cross-cutting: catalog in every model call, built-in tool filter +prompts/ system.md, validator.md + registry.py (Langfuse / packaged) +skills/ temporal-analyst, spatial-analyst +``` + The deep agent (`src/deep_agent/`) has a CLI entry point: ```bash @@ -53,7 +70,7 @@ Run logs are opt-in and git-ignored (`agent/runs/`, `agent/*.jsonl`, `agent/*.cs ### Semantic validation (deep agent) -An independent reviewer (`src/deep_agent/validator.py`) checks whether a SQL answer really answers the user's request: +An independent reviewer (`src/deep_agent/validator/`) checks whether a SQL answer really answers the user's request: a separate agent with a fresh context (the user's messages, the SQL, its rows, the stated assumptions and the catalog — not the main agent's reasoning), read-only diagnostic tools, and a verdict of pass, or fail with issues and evidence. Its prompt is `prompts/validator.md` (`deep-agent/validator` in Langfuse). `DEEP_AGENT_SEMANTIC_VALIDATION` picks how it is used: diff --git a/agent/scripts/sync_deep_agent_prompts.py b/agent/scripts/sync_deep_agent_prompts.py index 33d051a..fa040ab 100644 --- a/agent/scripts/sync_deep_agent_prompts.py +++ b/agent/scripts/sync_deep_agent_prompts.py @@ -11,7 +11,7 @@ import argparse -from deep_agent.prompt_registry import PROMPT_KEYS, langfuse_name, local_prompt +from deep_agent.prompts.registry import PROMPT_KEYS, langfuse_name, local_prompt def sync(client, label: str, dry_run: bool = False) -> list[str]: diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 436764d..0ed390f 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -52,14 +52,14 @@ class AgentSettings(BaseSettings): DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows DEEP_AGENT_TRACING_ENABLED: bool = True # Langfuse callbacks, span metadata and run scores DEEP_AGENT_CLARIFICATIONS_ENABLED: bool = False # let the model ask a clarifying question instead of answering - # Independent semantic review of answers (see deep_agent/validator.py): + # Independent semantic review of answers (see deep_agent/validator/): # always = every submitted answer is reviewed before the run ends; # on_demand = a `semantic-validator` subagent the agent calls when it judges a review worthwhile; off = no reviewer. DEEP_AGENT_SEMANTIC_VALIDATION: Literal["always", "on_demand", "off"] = "always" DEEP_AGENT_VALIDATOR_MAX_ROUNDS: int | None = Field(default=None, gt=0) # "always" only: reviews per turn; "none" = no limit JEEN_METADATA_CACHE_TTL_S: float = Field(default=300.0, ge=0) # metadata read cache (0 disables) JEEN_METADATA_REUSE_SESSION: bool = True # keep one MCP session open per event loop - # Prompts (see deep_agent/prompt_registry.py). Off until the prompts are finalised and synced to Langfuse. + # Prompts (see deep_agent/prompts/registry.py). Off until the prompts are finalised and synced to Langfuse. DEEP_AGENT_LANGFUSE_PROMPTS: bool = False # serve deep-agent/ prompts from Langfuse (packaged .md fallback) DEEP_AGENT_PROMPT_LABEL: str = "production" # Langfuse prompt label to serve DEEP_AGENT_PROMPT_CACHE_TTL_S: int = Field(default=60, ge=0) diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index e29c3b2..71c6cc2 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -1,11 +1,12 @@ """ Agent logic and LangGraph harness for the Deep Agent. -The system prompt is served by deep_agent.prompt_registry (Langfuse `deep-agent/system` when +The system prompt is served by deep_agent.prompts.registry (Langfuse `deep-agent/system` when DEEP_AGENT_LANGFUSE_PROMPTS is on, else the packaged prompts/system.md). The connection's catalog -is added to every model call by CatalogMiddleware (deep_agent.catalog). +is added to every model call by CatalogMiddleware (deep_agent.middleware.catalog). """ + from deepagents import create_deep_agent as create_harness_agent from deepagents.middleware.subagents import DEFAULT_GENERAL_PURPOSE_DESCRIPTION, DEFAULT_SUBAGENT_PROMPT from langchain_core.language_models import BaseChatModel @@ -13,26 +14,16 @@ from agent.config import settings from agent.llm import get_llm -from deep_agent.answer import ( - TOOL_NAME, - AnswerRecoveryMiddleware, - AnswerVerificationMiddleware, - SubmitReminderMiddleware, - answer_schema, - submission_strategy, -) -from deep_agent.catalog import CatalogMiddleware +from deep_agent.answer.middleware import AnswerRecoveryMiddleware, AnswerVerificationMiddleware, SubmitReminderMiddleware +from deep_agent.answer.schema import TOOL_NAME, answer_schema, submission_strategy from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware -from deep_agent.prompt_registry import PromptRefreshMiddleware, load_prompt, local_prompt +from deep_agent.middleware.catalog import CatalogMiddleware +from deep_agent.middleware.tool_filter import BuiltinToolFilterMiddleware +from deep_agent.prompts.registry import PromptRefreshMiddleware, load_prompt, local_prompt from deep_agent.resources import build_resources -from deep_agent.tool_filter import BuiltinToolFilterMiddleware from deep_agent.tools import DEEP_AGENT_TOOLS -from deep_agent.validator import ( - ReviewTurnMiddleware, - SemanticValidationMiddleware, - ValidationMode, - validator_subagent, -) +from deep_agent.validator.modes import ReviewTurnMiddleware, SemanticValidationMiddleware, validator_subagent +from deep_agent.validator.reviewer import ValidationMode # Packaged system prompt (the Langfuse-managed version, when enabled, is loaded per agent build and refreshed per call). SYSTEM_PROMPT = local_prompt("system") diff --git a/agent/src/deep_agent/answer.py b/agent/src/deep_agent/answer.py deleted file mode 100644 index c7f4d73..0000000 --- a/agent/src/deep_agent/answer.py +++ /dev/null @@ -1,436 +0,0 @@ -""" -Structured final answer for the Deep Agent, bound to SQL that actually ran. - -The model finishes by calling the `submit_answer` tool (ToolStrategy structured output). -AnswerVerificationMiddleware then binds it to evidence. `final_result.executed` says whether -the final SQL ran and the rows shown are Trino's — it does NOT mean the answer was checked -to be semantically correct. - -- "matched": answer.sql equals (sqlglot-normalised) a query that executed successfully in - this run -> the result rows are that execution's rows -- "re_executed": no match, or the match was only a smaller sample than the configured row - ceiling -> answer.sql is run once through the read-only guard; rows come from that run -- "rejected" / "re_execution_failed": the answer's SQL is forbidden or fails -> not executed -- "clarification": the model asked a clarifying question instead of answering - (only possible when DEEP_AGENT_CLARIFICATIONS_ENABLED is on) - -The result table shown to users is always built from Trino rows, never from model text. -""" - -import asyncio -import json -import logging -import re -import uuid -from collections.abc import Awaitable, Callable -from typing import Any, Literal - -import sqlglot -from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse, hook_config -from langchain.agents.structured_output import ToolStrategy -from langchain_core.messages import AIMessage, HumanMessage, ToolMessage -from pydantic import BaseModel, Field, create_model -from sqlglot.errors import SqlglotError - -from agent.config import settings -from agent.utils import sql_guard -from agent.utils.sql import clean_sql -from deep_agent.context import REMINDER_NAME, is_user_message -from core.trino import execute_query_sync - -logger = logging.getLogger(__name__) - -VerificationStatus = Literal["matched", "re_executed", "rejected", "re_execution_failed", "clarification", "no_answer"] - - -TOOL_NAME = "submit_answer" -# Content of the tool message for an accepted submission (anything else there is an error or a review's feedback). -ANSWER_RECEIVED = "Answer received." -_SUBMIT_DOC = "Submit your final answer. Call this exactly once, when you are done — it ends your work." - - -class _AnswerFields(BaseModel): - sql: str = Field( - description="The exact final Trino SQL whose results answer the question — the same query you executed " - "successfully with execute_trino_query.", - ) - explanation_he: str = Field(description="Brief Hebrew explanation of what the SQL does and what the result means.") - assumptions: list[str] = Field( - default_factory=list, description="Interpretation choices you made (in Hebrew), e.g. which column means 'city'." - ) - confidence: Literal["high", "medium", "low"] = Field(description="Confidence that the SQL answers the question.") - - -# The final-answer tool. LangChain's ToolStrategy names the tool after the schema's __name__, so the -# model sees a tool called `submit_answer` (the "I'm done" submit convention). -SubmitAnswer = create_model(TOOL_NAME, __base__=_AnswerFields, __doc__=_SUBMIT_DOC) - -# Same tool name, plus the option to ask a clarifying question instead of answering. -SubmitAnswerWithClarification = create_model( - TOOL_NAME, - __base__=SubmitAnswer, - __doc__=_SUBMIT_DOC, - sql=(str | None, Field( - default=None, - description="The exact final Trino SQL whose results answer the question — the same query you executed " - "successfully with execute_trino_query. Null only when asking for clarification.", - )), - needs_clarification=(str | None, Field( - default=None, description="If the question is ambiguous, the clarifying question to ask the user (Hebrew).", - )), -) - - -_VALIDATION_RESPONSE = (str | None, Field( - default=None, - description="Only when an independent review rejected your previous answer and you submit the same SQL again: " - "why that SQL is correct despite the review (Hebrew).", -)) - - -def _with_validation_response(base: type[SubmitAnswer]) -> type[SubmitAnswer]: - return create_model(TOOL_NAME, __base__=base, __doc__=_SUBMIT_DOC, validation_response=_VALIDATION_RESPONSE) - - -_SCHEMAS: dict[tuple[bool, bool], type[SubmitAnswer]] = { - (False, False): SubmitAnswer, - (True, False): SubmitAnswerWithClarification, - (False, True): _with_validation_response(SubmitAnswer), - (True, True): _with_validation_response(SubmitAnswerWithClarification), -} - - -def answer_schema( - clarifications_enabled: bool | None = None, validation_enabled: bool | None = None -) -> type[SubmitAnswer]: - """The final-answer schema; without clarifications the model must always commit to a SQL answer. - - With semantic validation "always", it also has `validation_response` (to stand by a rejected answer). - """ - if clarifications_enabled is None: - clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED - if validation_enabled is None: - validation_enabled = settings.DEEP_AGENT_SEMANTIC_VALIDATION == "always" - return _SCHEMAS[(bool(clarifications_enabled), bool(validation_enabled))] - - -def submission_strategy(schema: type[BaseModel]) -> ToolStrategy: - """ToolStrategy whose accepted-submission tool message is ANSWER_RECEIVED (see accepted_submission).""" - return ToolStrategy(schema, tool_message_content=ANSWER_RECEIVED) - - -def last_submission(messages: list, tool_name: str = TOOL_NAME) -> ToolMessage | None: - """The tool message answering a submit call, when it is the latest message (i.e. the model just submitted).""" - last = messages[-1] if messages else None - return last if isinstance(last, ToolMessage) and last.name == tool_name else None - - -def normalize_sql(sql: str | None) -> str | None: - """Canonical form for comparing two SQL strings (whitespace, keyword case, trailing ';', fences).""" - if not sql: - return None - cleaned = clean_sql(sql) - try: - return sqlglot.parse_one(cleaned, read="trino").sql(dialect="trino") - except SqlglotError: - return " ".join(cleaned.split()) - - -def executed_query_record( - submitted_sql: str, executed_sql: str, payload: dict[str, Any], row_cap: int | None -) -> dict[str, Any]: - """State entry for one successful execution (see DeepAgentRuntimeState.executed_queries). - - row_cap is the ceiling that execution ran under (None = none), so verification can tell an - exploration sample (e.g. limit=5) from the full answer. - """ - return { - "submitted_sql": clean_sql(submitted_sql), - "executed_sql": executed_sql, - "columns": payload["columns"], - "rows": payload["rows"], - "row_count": payload["row_count"], - "truncated": payload["truncated"], - "query_id": payload.get("query_id"), - "row_cap": row_cap, - } - - -def match_execution(answer_sql: str, executed: list[dict[str, Any]]) -> dict[str, Any] | None: - target = normalize_sql(answer_sql) - for record in reversed(executed): # latest execution wins - if target in (normalize_sql(record["submitted_sql"]), normalize_sql(record["executed_sql"])): - return record - return None - - -def _is_sample(record: dict[str, Any]) -> bool: - """The matched execution was cut short by a smaller limit than the configured row ceiling.""" - if not record.get("truncated"): - return False - ceiling = settings.DEEP_AGENT_MAX_ROWS - cap = record.get("row_cap") - return cap is not None and (ceiling is None or cap < ceiling) - - -def _re_execute(answer_sql: str) -> tuple[VerificationStatus, dict[str, Any] | None, str | None]: - row_cap = settings.DEEP_AGENT_MAX_ROWS - try: - guarded = sql_guard.prepare(clean_sql(answer_sql), row_cap) - except sql_guard.GuardError as e: - return "rejected", None, str(e) - res = execute_query_sync(guarded.sql, reuse_connection=True) - if not res.success: - return "re_execution_failed", None, res.error_message - rows = res.rows or [] - truncated = row_cap is not None and len(rows) > row_cap - if truncated: - rows = rows[:row_cap] - payload = {"columns": res.columns, "rows": rows, "row_count": len(rows), "truncated": truncated, - "query_id": res.query_id} - return "re_executed", executed_query_record(answer_sql, guarded.sql, payload, row_cap), None - - -def _result_view(record: dict[str, Any]) -> dict[str, Any]: - return {k: record[k] for k in ("columns", "rows", "row_count", "truncated", "query_id")} - - -def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any]: - """Build `final_result` from the structured answer and the run's successful executions.""" - if not isinstance(answer, SubmitAnswer): - return {"status": "no_answer", "executed": False, "answer": None, "sql": None, "result": None, "error": None} - - base = {"answer": answer.model_dump(), "error": None} - if getattr(answer, "needs_clarification", None) or not answer.sql: - return {**base, "status": "clarification", "executed": False, "sql": None, "result": None} - - record = match_execution(answer.sql, executed) - if record is not None and not _is_sample(record): - return {**base, "status": "matched", "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} - - status, record, error = _re_execute(answer.sql) - if record is None: - return {**base, "status": status, "executed": False, "sql": clean_sql(answer.sql), "result": None, "error": error} - return {**base, "status": status, "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} - - -RECOVERED_FLAG = "deep_agent_recovered_answer" -_FENCED_JSON = re.compile(r"^```(?:json)?\s*(\{.*\})\s*```$", re.DOTALL) - - -def _answer_from_text(text: str, schema: type[BaseModel]) -> tuple[dict, BaseModel] | None: - """The message text as a valid final answer (a JSON object that passes the answer schema), else None.""" - body = text.strip() - fenced = _FENCED_JSON.match(body) - if fenced: - body = fenced.group(1) - if not (body.startswith("{") and body.endswith("}")): - return None - try: - args = json.loads(body) - return args, schema(**args) - except (ValueError, TypeError): - return None - - -class AnswerRecoveryMiddleware(AgentMiddleware): - """Recover a final answer the model wrote as text instead of calling submit_answer. - - With gpt-oss behind the configured OpenAI-compatible server, forced tool choice is not always - honoured late in a run: the model sometimes writes the submit_answer JSON as plain text - (finish_reason "tool_calls", no parsed tool call). LangChain then sees no tool call and the run - ends without an answer. When — and only when — the text is a JSON object that validates against - the answer schema, this turns it into the same result a real submit_answer call produces (the - tool call, its tool message and `structured_response`), marked with RECOVERED_FLAG. - Anything else is left untouched. - """ - - def _recover(self, request: ModelRequest, response: ModelResponse) -> ModelResponse: - schema = getattr(request.response_format, "schema", None) - if response.structured_response is not None or schema is None or not response.result: - return response - output = response.result[-1] - if not isinstance(output, AIMessage) or output.tool_calls: - return response - parsed = _answer_from_text(output.text, schema) - if parsed is None: - return response - args, answer = parsed - call_id = f"recovered_{uuid.uuid4().hex[:12]}" - logger.warning("Recovered a final answer the model wrote as text instead of a submit_answer call") - repaired = AIMessage( - content="", - tool_calls=[{"name": schema.__name__, "args": args, "id": call_id, "type": "tool_call"}], - additional_kwargs={**output.additional_kwargs, RECOVERED_FLAG: True}, - response_metadata=output.response_metadata, - usage_metadata=output.usage_metadata, - id=output.id, - name=output.name, - ) - tool_message = ToolMessage(content=ANSWER_RECEIVED, tool_call_id=call_id, name=schema.__name__) - return ModelResponse(result=[*response.result[:-1], repaired, tool_message], structured_response=answer) - - def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: - return self._recover(request, handler(request)) - - async def awrap_model_call( - self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] - ) -> ModelResponse: - return self._recover(request, await handler(request)) - - -def current_turn(messages: list) -> list: - """Messages after the latest user message (this run's turn).""" - for i in range(len(messages) - 1, -1, -1): - if is_user_message(messages[i]): - return messages[i + 1:] - return messages - - -class SubmitReminderMiddleware(AgentMiddleware): - """Send the model back once per turn when it stops without calling its submit tool. - - The configured model server sometimes ends a run with plain text instead of the forced - submit call (and AnswerRecoveryMiddleware can only rescue text that is valid JSON for the - schema). The work is then lost — e.g. a reviewer that found a real problem but never - returned its verdict. One reminder (a message named REMINDER_NAME, not counted as the - user's words) asks for the submit call; if the model still doesn't comply, the run ends as before. - """ - - def __init__(self, tool_name: str) -> None: - super().__init__() - self.tool_name = tool_name - - @hook_config(can_jump_to=["model"]) - def after_model(self, state, runtime) -> dict[str, Any] | None: - messages = state.get("messages") or [] - last = messages[-1] if messages else None - if not isinstance(last, AIMessage) or last.tool_calls or state.get("structured_response") is not None: - return None - if any(getattr(m, "name", None) == REMINDER_NAME for m in current_turn(messages)): - return None # already reminded this turn - reminder = (f"You stopped without calling `{self.tool_name}`. Your work is delivered only through " - f"`{self.tool_name}` — call it now with your result.") - return {"messages": [HumanMessage(reminder, name=REMINDER_NAME)], "jump_to": "model"} - - @hook_config(can_jump_to=["model"]) - async def aafter_model(self, state, runtime) -> dict[str, Any] | None: - return self.after_model(state, runtime) - - -class AnswerVerificationMiddleware(AgentMiddleware): - """Bind each turn's structured answer to SQL executed in that turn and its real rows. - - before_agent clears the previous turn's structured answer (it would otherwise be reported - again on a turn that ends without a new one) and marks where this turn's executions start, - so an answer can only match SQL that ran in its own turn. - - after_model sends the model back after a rejected submit_answer call (arguments that fail the - schema). LangChain would retry on its own only while `structured_response` has never been set - in the thread; from the first reset on, it ends the run instead. - - after_agent keeps the answer only as plain data in final_result and drops the pydantic object: - checkpoints can't restore the dynamically built `submit_answer` class. - """ - - @hook_config(can_jump_to=["model"]) - def after_model(self, state, runtime) -> dict[str, Any] | None: - submission = last_submission(state.get("messages") or []) - if submission is not None and submission.text != ANSWER_RECEIVED: - return {"jump_to": "model"} - return None - - @hook_config(can_jump_to=["model"]) - async def aafter_model(self, state, runtime) -> dict[str, Any] | None: - return self.after_model(state, runtime) - - def before_agent(self, state, runtime) -> dict[str, Any] | None: - return {"structured_response": None, "turn_execution_start": len(state.get("executed_queries") or [])} - - async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: - return self.before_agent(state, runtime) - - def after_agent(self, state, runtime) -> dict[str, Any] | None: - executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] - final = verify_answer(state.get("structured_response"), executed) - final["recovered_from_text"] = any( - (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in current_turn(state.get("messages") or []) - ) - final["semantic_validation"] = validation_summary(state.get("semantic_validations"), final.get("sql")) - return {"final_result": final, "structured_response": None} - - async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: - return await asyncio.to_thread(self.after_agent, state, runtime) - - -_VERDICTS = {"pass": "passed", "fail": "failed", "disputed": "disputed"} - - -def _covers(record: dict[str, Any], final_sql: str | None) -> bool | None: - """Did this review look at the final SQL? None when it can't be told (an on-demand brief without a ```sql block).""" - target = normalize_sql(final_sql) - if "sql" in record: - return record["sql"] == target - return (target in record["sqls"]) if record.get("sqls") else None - - -def validation_summary(records: list[dict[str, Any]] | None, final_sql: str | None = None) -> dict[str, Any] | None: - """The review outcome of the final answer, from this turn's review records (None = reviewer off). - - verdict: passed | failed | disputed (the agent resubmitted a rejected SQL with a justification) | - not_validated (no review, a review of a different SQL than the final one, round limit, or the review failed). - reviewed_final_sql: whether the last review covered the final SQL (None = can't be told). - """ - if records is None: - return None - rounds = sum(1 for r in records if r["verdict"] in ("pass", "fail")) - summary = {"verdict": "not_validated", "rounds": rounds, "issues": [], "response": None, "reason": None, - "reviewed_final_sql": None} - if not records: - return {**summary, "reason": "no review"} - last = records[-1] - covers = _covers(last, final_sql) - summary.update(issues=last.get("issues") or [], response=last.get("response"), reviewed_final_sql=covers, - reason=last.get("reason")) - if covers is False: - return {**summary, "issues": [], "reason": "the final SQL changed after the last review"} - return {**summary, "verdict": _VERDICTS.get(last["verdict"], "not_validated")} - - -def _cell(value: Any) -> str: - return "" if value is None else str(value).replace("|", "\\|").replace("\n", " ") - - -def render_markdown(final_result: dict[str, Any]) -> str: - """User-facing Hebrew answer: explanation, table from real rows, SQL block.""" - answer = final_result.get("answer") or {} - if final_result.get("status") == "clarification": - return answer.get("needs_clarification") or answer.get("explanation_he", "") - parts = [answer.get("explanation_he", "")] - if answer.get("assumptions"): - parts.append("**הנחות:**\n" + "\n".join(f"- {a}" for a in answer["assumptions"])) - - result = final_result.get("result") - if result: - header = "| " + " | ".join(_cell(c) for c in result["columns"]) + " |" - sep = "|" + "---|" * len(result["columns"]) - body = ["| " + " | ".join(_cell(v) for v in row) + " |" for row in result["rows"]] - parts.append("\n".join([header, sep, *body])) - if result.get("truncated"): - parts.append(f"_מוצגות {result['row_count']} השורות הראשונות בלבד._") - elif final_result.get("status") == "no_answer": - reason = final_result.get("error") - parts.append("⚠️ לא התקבלה תשובה סופית" + (f": {reason}" if reason else ".")) - elif final_result.get("error"): - parts.append(f"⚠️ לא ניתן היה להריץ את השאילתה הסופית: {final_result['error']}") - - review = final_result.get("semantic_validation") or {} - if review.get("verdict") in ("failed", "disputed") and review.get("issues"): - title = "בדיקה עצמאית מצאה בעיות בתשובה" if review["verdict"] == "failed" else "בדיקה עצמאית העלתה הסתייגות" - parts.append(f"⚠️ **{title}:**\n" + "\n".join(f"- {i['problem']}" for i in review["issues"])) - if review["verdict"] == "disputed" and review.get("response"): - parts.append(f"**תגובת הסוכן:** {review['response']}") - - if final_result.get("sql"): - parts.append(f"```sql\n{final_result['sql']}\n```") - return "\n\n".join(p for p in parts if p) diff --git a/agent/src/deep_agent/answer/__init__.py b/agent/src/deep_agent/answer/__init__.py new file mode 100644 index 0000000..1c74b47 --- /dev/null +++ b/agent/src/deep_agent/answer/__init__.py @@ -0,0 +1,8 @@ +""" +The final answer: the `submit_answer` format, keeping it bound to SQL that actually ran, and what the user sees. + +- schema.py the submit_answer tool format (+ clarification / validation_response variants) +- verification.py did the answer's SQL really run? -> final_result (matched / re_executed / ...) +- middleware.py answer recovery, submit reminder, invalid-submission retry, final_result at the end of a turn +- render.py the Hebrew markdown shown to the user +""" diff --git a/agent/src/deep_agent/answer/middleware.py b/agent/src/deep_agent/answer/middleware.py new file mode 100644 index 0000000..3c2d237 --- /dev/null +++ b/agent/src/deep_agent/answer/middleware.py @@ -0,0 +1,167 @@ +""" +Middleware around the final answer: + +- AnswerRecoveryMiddleware answer written as JSON text instead of a submit_answer call -> the real call +- SubmitReminderMiddleware the model stopped without its submit call -> one reminder per turn +- AnswerVerificationMiddleware each turn starts clean; invalid submissions are retried; at the end of + the turn the answer is verified (deep_agent.answer.verification) -> final_result +""" + +import asyncio +import json +import logging +import re +import uuid +from collections.abc import Awaitable, Callable +from typing import Any + +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse, hook_config +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage +from pydantic import BaseModel + +from deep_agent.answer.schema import ANSWER_RECEIVED, last_submission +from deep_agent.answer.verification import validation_summary, verify_answer +from deep_agent.context import REMINDER_NAME, current_turn + +logger = logging.getLogger(__name__) + + +RECOVERED_FLAG = "deep_agent_recovered_answer" +_FENCED_JSON = re.compile(r"^```(?:json)?\s*(\{.*\})\s*```$", re.DOTALL) + + +def _answer_from_text(text: str, schema: type[BaseModel]) -> tuple[dict, BaseModel] | None: + """The message text as a valid final answer (a JSON object that passes the answer schema), else None.""" + body = text.strip() + fenced = _FENCED_JSON.match(body) + if fenced: + body = fenced.group(1) + if not (body.startswith("{") and body.endswith("}")): + return None + try: + args = json.loads(body) + return args, schema(**args) + except (ValueError, TypeError): + return None + + +class AnswerRecoveryMiddleware(AgentMiddleware): + """Recover a final answer the model wrote as text instead of calling submit_answer. + + With gpt-oss behind the configured OpenAI-compatible server, forced tool choice is not always + honoured late in a run: the model sometimes writes the submit_answer JSON as plain text + (finish_reason "tool_calls", no parsed tool call). LangChain then sees no tool call and the run + ends without an answer. When — and only when — the text is a JSON object that validates against + the answer schema, this turns it into the same result a real submit_answer call produces (the + tool call, its tool message and `structured_response`), marked with RECOVERED_FLAG. + Anything else is left untouched. + """ + + def _recover(self, request: ModelRequest, response: ModelResponse) -> ModelResponse: + schema = getattr(request.response_format, "schema", None) + if response.structured_response is not None or schema is None or not response.result: + return response + output = response.result[-1] + if not isinstance(output, AIMessage) or output.tool_calls: + return response + parsed = _answer_from_text(output.text, schema) + if parsed is None: + return response + args, answer = parsed + call_id = f"recovered_{uuid.uuid4().hex[:12]}" + logger.warning("Recovered a final answer the model wrote as text instead of a submit_answer call") + repaired = AIMessage( + content="", + tool_calls=[{"name": schema.__name__, "args": args, "id": call_id, "type": "tool_call"}], + additional_kwargs={**output.additional_kwargs, RECOVERED_FLAG: True}, + response_metadata=output.response_metadata, + usage_metadata=output.usage_metadata, + id=output.id, + name=output.name, + ) + tool_message = ToolMessage(content=ANSWER_RECEIVED, tool_call_id=call_id, name=schema.__name__) + return ModelResponse(result=[*response.result[:-1], repaired, tool_message], structured_response=answer) + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return self._recover(request, handler(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return self._recover(request, await handler(request)) + + +class SubmitReminderMiddleware(AgentMiddleware): + """Send the model back once per turn when it stops without calling its submit tool. + + The configured model server sometimes ends a run with plain text instead of the forced + submit call (and AnswerRecoveryMiddleware can only rescue text that is valid JSON for the + schema). The work is then lost — e.g. a reviewer that found a real problem but never + returned its verdict. One reminder (a message named REMINDER_NAME, not counted as the + user's words) asks for the submit call; if the model still doesn't comply, the run ends as before. + """ + + def __init__(self, tool_name: str) -> None: + super().__init__() + self.tool_name = tool_name + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + messages = state.get("messages") or [] + last = messages[-1] if messages else None + if not isinstance(last, AIMessage) or last.tool_calls or state.get("structured_response") is not None: + return None + if any(getattr(m, "name", None) == REMINDER_NAME for m in current_turn(messages)): + return None # already reminded this turn + reminder = (f"You stopped without calling `{self.tool_name}`. Your work is delivered only through " + f"`{self.tool_name}` — call it now with your result.") + return {"messages": [HumanMessage(reminder, name=REMINDER_NAME)], "jump_to": "model"} + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + return self.after_model(state, runtime) + + +class AnswerVerificationMiddleware(AgentMiddleware): + """Bind each turn's structured answer to SQL executed in that turn and its real rows. + + before_agent clears the previous turn's structured answer (it would otherwise be reported + again on a turn that ends without a new one) and marks where this turn's executions start, + so an answer can only match SQL that ran in its own turn. + + after_model sends the model back after a rejected submit_answer call (arguments that fail the + schema). LangChain would retry on its own only while `structured_response` has never been set + in the thread; from the first reset on, it ends the run instead. + + after_agent keeps the answer only as plain data in final_result and drops the pydantic object: + checkpoints can't restore the dynamically built `submit_answer` class. + """ + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + submission = last_submission(state.get("messages") or []) + if submission is not None and submission.text != ANSWER_RECEIVED: + return {"jump_to": "model"} + return None + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + return self.after_model(state, runtime) + + def before_agent(self, state, runtime) -> dict[str, Any] | None: + return {"structured_response": None, "turn_execution_start": len(state.get("executed_queries") or [])} + + async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: + return self.before_agent(state, runtime) + + def after_agent(self, state, runtime) -> dict[str, Any] | None: + executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + final = verify_answer(state.get("structured_response"), executed) + final["recovered_from_text"] = any( + (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in current_turn(state.get("messages") or []) + ) + final["semantic_validation"] = validation_summary(state.get("semantic_validations"), final.get("sql")) + return {"final_result": final, "structured_response": None} + + async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: + return await asyncio.to_thread(self.after_agent, state, runtime) diff --git a/agent/src/deep_agent/answer/render.py b/agent/src/deep_agent/answer/render.py new file mode 100644 index 0000000..adae12e --- /dev/null +++ b/agent/src/deep_agent/answer/render.py @@ -0,0 +1,45 @@ +""" +The user-facing answer: Hebrew explanation, assumptions, a table built from Trino's rows (never from +model text), warnings, and the SQL. +""" + +from typing import Any + + +def _cell(value: Any) -> str: + return "" if value is None else str(value).replace("|", "\\|").replace("\n", " ") + + +def render_markdown(final_result: dict[str, Any]) -> str: + """User-facing Hebrew answer: explanation, table from real rows, SQL block.""" + answer = final_result.get("answer") or {} + if final_result.get("status") == "clarification": + return answer.get("needs_clarification") or answer.get("explanation_he", "") + parts = [answer.get("explanation_he", "")] + if answer.get("assumptions"): + parts.append("**הנחות:**\n" + "\n".join(f"- {a}" for a in answer["assumptions"])) + + result = final_result.get("result") + if result: + header = "| " + " | ".join(_cell(c) for c in result["columns"]) + " |" + sep = "|" + "---|" * len(result["columns"]) + body = ["| " + " | ".join(_cell(v) for v in row) + " |" for row in result["rows"]] + parts.append("\n".join([header, sep, *body])) + if result.get("truncated"): + parts.append(f"_מוצגות {result['row_count']} השורות הראשונות בלבד._") + elif final_result.get("status") == "no_answer": + reason = final_result.get("error") + parts.append("⚠️ לא התקבלה תשובה סופית" + (f": {reason}" if reason else ".")) + elif final_result.get("error"): + parts.append(f"⚠️ לא ניתן היה להריץ את השאילתה הסופית: {final_result['error']}") + + review = final_result.get("semantic_validation") or {} + if review.get("verdict") in ("failed", "disputed") and review.get("issues"): + title = "בדיקה עצמאית מצאה בעיות בתשובה" if review["verdict"] == "failed" else "בדיקה עצמאית העלתה הסתייגות" + parts.append(f"⚠️ **{title}:**\n" + "\n".join(f"- {i['problem']}" for i in review["issues"])) + if review["verdict"] == "disputed" and review.get("response"): + parts.append(f"**תגובת הסוכן:** {review['response']}") + + if final_result.get("sql"): + parts.append(f"```sql\n{final_result['sql']}\n```") + return "\n\n".join(p for p in parts if p) diff --git a/agent/src/deep_agent/answer/schema.py b/agent/src/deep_agent/answer/schema.py new file mode 100644 index 0000000..0c26faa --- /dev/null +++ b/agent/src/deep_agent/answer/schema.py @@ -0,0 +1,92 @@ +""" +The `submit_answer` tool: the format the model finishes with (LangChain ToolStrategy structured output). +""" + +from typing import Literal + +from langchain.agents.structured_output import ToolStrategy +from langchain_core.messages import ToolMessage +from pydantic import BaseModel, Field, create_model + +from agent.config import settings + +TOOL_NAME = "submit_answer" +# Content of the tool message for an accepted submission (anything else there is an error or a review's feedback). +ANSWER_RECEIVED = "Answer received." +_SUBMIT_DOC = "Submit your final answer. Call this exactly once, when you are done — it ends your work." + + +class _AnswerFields(BaseModel): + sql: str = Field( + description="The exact final Trino SQL whose results answer the question — the same query you executed " + "successfully with execute_trino_query.", + ) + explanation_he: str = Field(description="Brief Hebrew explanation of what the SQL does and what the result means.") + assumptions: list[str] = Field( + default_factory=list, description="Interpretation choices you made (in Hebrew), e.g. which column means 'city'." + ) + confidence: Literal["high", "medium", "low"] = Field(description="Confidence that the SQL answers the question.") + + +# The final-answer tool. LangChain's ToolStrategy names the tool after the schema's __name__, so the +# model sees a tool called `submit_answer` (the "I'm done" submit convention). +SubmitAnswer = create_model(TOOL_NAME, __base__=_AnswerFields, __doc__=_SUBMIT_DOC) + +# Same tool name, plus the option to ask a clarifying question instead of answering. +SubmitAnswerWithClarification = create_model( + TOOL_NAME, + __base__=SubmitAnswer, + __doc__=_SUBMIT_DOC, + sql=(str | None, Field( + default=None, + description="The exact final Trino SQL whose results answer the question — the same query you executed " + "successfully with execute_trino_query. Null only when asking for clarification.", + )), + needs_clarification=(str | None, Field( + default=None, description="If the question is ambiguous, the clarifying question to ask the user (Hebrew).", + )), +) + + +_VALIDATION_RESPONSE = (str | None, Field( + default=None, + description="Only when an independent review rejected your previous answer and you submit the same SQL again: " + "why that SQL is correct despite the review (Hebrew).", +)) + + +def _with_validation_response(base: type[SubmitAnswer]) -> type[SubmitAnswer]: + return create_model(TOOL_NAME, __base__=base, __doc__=_SUBMIT_DOC, validation_response=_VALIDATION_RESPONSE) + + +_SCHEMAS: dict[tuple[bool, bool], type[SubmitAnswer]] = { + (False, False): SubmitAnswer, + (True, False): SubmitAnswerWithClarification, + (False, True): _with_validation_response(SubmitAnswer), + (True, True): _with_validation_response(SubmitAnswerWithClarification), +} + + +def answer_schema( + clarifications_enabled: bool | None = None, validation_enabled: bool | None = None +) -> type[SubmitAnswer]: + """The final-answer schema; without clarifications the model must always commit to a SQL answer. + + With semantic validation "always", it also has `validation_response` (to stand by a rejected answer). + """ + if clarifications_enabled is None: + clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED + if validation_enabled is None: + validation_enabled = settings.DEEP_AGENT_SEMANTIC_VALIDATION == "always" + return _SCHEMAS[(bool(clarifications_enabled), bool(validation_enabled))] + + +def submission_strategy(schema: type[BaseModel]) -> ToolStrategy: + """ToolStrategy whose accepted-submission tool message is ANSWER_RECEIVED (see accepted_submission).""" + return ToolStrategy(schema, tool_message_content=ANSWER_RECEIVED) + + +def last_submission(messages: list, tool_name: str = TOOL_NAME) -> ToolMessage | None: + """The tool message answering a submit call, when it is the latest message (i.e. the model just submitted).""" + last = messages[-1] if messages else None + return last if isinstance(last, ToolMessage) and last.name == tool_name else None diff --git a/agent/src/deep_agent/answer/verification.py b/agent/src/deep_agent/answer/verification.py new file mode 100644 index 0000000..67f27d1 --- /dev/null +++ b/agent/src/deep_agent/answer/verification.py @@ -0,0 +1,154 @@ +""" +Binding the submitted answer to SQL that actually ran (final_result). + +The model finishes by calling the `submit_answer` tool (ToolStrategy structured output). +AnswerVerificationMiddleware then binds it to evidence. `final_result.executed` says whether +the final SQL ran and the rows shown are Trino's — it does NOT mean the answer was checked +to be semantically correct. + +- "matched": answer.sql equals (sqlglot-normalised) a query that executed successfully in + this run -> the result rows are that execution's rows +- "re_executed": no match, or the match was only a smaller sample than the configured row + ceiling -> answer.sql is run once through the read-only guard; rows come from that run +- "rejected" / "re_execution_failed": the answer's SQL is forbidden or fails -> not executed +- "clarification": the model asked a clarifying question instead of answering + (only possible when DEEP_AGENT_CLARIFICATIONS_ENABLED is on) + +The result table shown to users is always built from Trino rows, never from model text. +""" + +from typing import Any, Literal + +import sqlglot +from sqlglot.errors import SqlglotError + +from agent.config import settings +from agent.utils import sql_guard +from agent.utils.sql import clean_sql +from core.trino import execute_query_sync +from deep_agent.answer.schema import SubmitAnswer + +VerificationStatus = Literal["matched", "re_executed", "rejected", "re_execution_failed", "clarification", "no_answer"] + + +def normalize_sql(sql: str | None) -> str | None: + """Canonical form for comparing two SQL strings (whitespace, keyword case, trailing ';', fences).""" + if not sql: + return None + cleaned = clean_sql(sql) + try: + return sqlglot.parse_one(cleaned, read="trino").sql(dialect="trino") + except SqlglotError: + return " ".join(cleaned.split()) + + +def executed_query_record( + submitted_sql: str, executed_sql: str, payload: dict[str, Any], row_cap: int | None +) -> dict[str, Any]: + """State entry for one successful execution (see DeepAgentRuntimeState.executed_queries). + + row_cap is the ceiling that execution ran under (None = none), so verification can tell an + exploration sample (e.g. limit=5) from the full answer. + """ + return { + "submitted_sql": clean_sql(submitted_sql), + "executed_sql": executed_sql, + "columns": payload["columns"], + "rows": payload["rows"], + "row_count": payload["row_count"], + "truncated": payload["truncated"], + "query_id": payload.get("query_id"), + "row_cap": row_cap, + } + + +def match_execution(answer_sql: str, executed: list[dict[str, Any]]) -> dict[str, Any] | None: + target = normalize_sql(answer_sql) + for record in reversed(executed): # latest execution wins + if target in (normalize_sql(record["submitted_sql"]), normalize_sql(record["executed_sql"])): + return record + return None + + +def _is_sample(record: dict[str, Any]) -> bool: + """The matched execution was cut short by a smaller limit than the configured row ceiling.""" + if not record.get("truncated"): + return False + ceiling = settings.DEEP_AGENT_MAX_ROWS + cap = record.get("row_cap") + return cap is not None and (ceiling is None or cap < ceiling) + + +def _re_execute(answer_sql: str) -> tuple[VerificationStatus, dict[str, Any] | None, str | None]: + row_cap = settings.DEEP_AGENT_MAX_ROWS + try: + guarded = sql_guard.prepare(clean_sql(answer_sql), row_cap) + except sql_guard.GuardError as e: + return "rejected", None, str(e) + res = execute_query_sync(guarded.sql, reuse_connection=True) + if not res.success: + return "re_execution_failed", None, res.error_message + rows = res.rows or [] + truncated = row_cap is not None and len(rows) > row_cap + if truncated: + rows = rows[:row_cap] + payload = {"columns": res.columns, "rows": rows, "row_count": len(rows), "truncated": truncated, + "query_id": res.query_id} + return "re_executed", executed_query_record(answer_sql, guarded.sql, payload, row_cap), None + + +def _result_view(record: dict[str, Any]) -> dict[str, Any]: + return {k: record[k] for k in ("columns", "rows", "row_count", "truncated", "query_id")} + + +def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any]: + """Build `final_result` from the structured answer and the run's successful executions.""" + if not isinstance(answer, SubmitAnswer): + return {"status": "no_answer", "executed": False, "answer": None, "sql": None, "result": None, "error": None} + + base = {"answer": answer.model_dump(), "error": None} + if getattr(answer, "needs_clarification", None) or not answer.sql: + return {**base, "status": "clarification", "executed": False, "sql": None, "result": None} + + record = match_execution(answer.sql, executed) + if record is not None and not _is_sample(record): + return {**base, "status": "matched", "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} + + status, record, error = _re_execute(answer.sql) + if record is None: + return {**base, "status": status, "executed": False, "sql": clean_sql(answer.sql), "result": None, "error": error} + return {**base, "status": status, "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} + + +_VERDICTS = {"pass": "passed", "fail": "failed", "disputed": "disputed"} + + +def _covers(record: dict[str, Any], final_sql: str | None) -> bool | None: + """Did this review look at the final SQL? None when it can't be told (an on-demand brief without a ```sql block).""" + target = normalize_sql(final_sql) + if "sql" in record: + return record["sql"] == target + return (target in record["sqls"]) if record.get("sqls") else None + + +def validation_summary(records: list[dict[str, Any]] | None, final_sql: str | None = None) -> dict[str, Any] | None: + """The review outcome of the final answer, from this turn's review records (None = reviewer off). + + verdict: passed | failed | disputed (the agent resubmitted a rejected SQL with a justification) | + not_validated (no review, a review of a different SQL than the final one, round limit, or the review failed). + reviewed_final_sql: whether the last review covered the final SQL (None = can't be told). + """ + if records is None: + return None + rounds = sum(1 for r in records if r["verdict"] in ("pass", "fail")) + summary = {"verdict": "not_validated", "rounds": rounds, "issues": [], "response": None, "reason": None, + "reviewed_final_sql": None} + if not records: + return {**summary, "reason": "no review"} + last = records[-1] + covers = _covers(last, final_sql) + summary.update(issues=last.get("issues") or [], response=last.get("response"), reviewed_final_sql=covers, + reason=last.get("reason")) + if covers is False: + return {**summary, "issues": [], "reason": "the final SQL changed after the last review"} + return {**summary, "verdict": _VERDICTS.get(last["verdict"], "not_validated")} diff --git a/agent/src/deep_agent/cli.py b/agent/src/deep_agent/cli.py index 466f2b9..ed4e20d 100644 --- a/agent/src/deep_agent/cli.py +++ b/agent/src/deep_agent/cli.py @@ -22,7 +22,7 @@ from agent.utils.jeen_metadata_client import close_mcp_sessions from deep_agent.agent import create_deep_agent from deep_agent import observability -from deep_agent.answer import render_markdown +from deep_agent.answer.render import render_markdown from deep_agent.context import DeepAgentContext # ANSI Colors for terminal output diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index 05e6b8c..d910f9a 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -4,7 +4,7 @@ Nothing request-specific lives in module globals: - DeepAgentContext is passed per invocation (`agent.ainvoke(..., context=DeepAgentContext(...))`) and read by tools through `ToolRuntime.context`. -- The connection's catalog is loaded once per run by CatalogMiddleware (deep_agent.catalog) +- The connection's catalog is loaded once per run by CatalogMiddleware (deep_agent.middleware.catalog) into graph state (`jeen_catalog`) and read back by tools through `ToolRuntime.state`. - Today's date is added to the latest human message on every model call, in the context's timezone, so long-running processes never serve a stale date. @@ -30,6 +30,10 @@ class DeepAgentContext: timezone: str = DEFAULT_TIMEZONE +# What tools receive as `runtime`: state, config, tool_call_id and our per-request context. +Runtime = ToolRuntime[DeepAgentContext] + + def merge_executions(left: list[dict[str, Any]] | None, right: list[dict[str, Any]] | None) -> list[dict[str, Any]]: """Append-only reducer for executed_queries that ignores records already present. @@ -71,14 +75,14 @@ def merge_reviews(left: list[dict[str, Any]] | None, right: list[dict[str, Any]] class DeepAgentRuntimeState(AgentState): - jeen_catalog: NotRequired[Annotated[str, latest]] # the connection's catalog, loaded once per run (deep_agent.catalog) + jeen_catalog: NotRequired[Annotated[str, latest]] # the connection's catalog, loaded once per run (deep_agent.middleware.catalog) executed_queries: NotRequired[Annotated[list[dict[str, Any]], merge_executions]] # successful executions - final_result: NotRequired[Annotated[dict[str, Any], latest]] # verified answer + rows (see deep_agent.answer) + final_result: NotRequired[Annotated[dict[str, Any], latest]] # verified answer + rows (see deep_agent.answer.verification) turn_execution_start: NotRequired[Annotated[int, latest]] # index into executed_queries where the current turn began semantic_validations: NotRequired[Annotated[list[dict[str, Any]], merge_reviews]] # this turn's reviews (deep_agent.validator) -# Name of the one-time "submit now" message (deep_agent.answer.SubmitReminderMiddleware): not the user's words. +# Name of the one-time "submit now" message (deep_agent.answer.middleware.SubmitReminderMiddleware): not the user's words. REMINDER_NAME = "submit_reminder" @@ -87,6 +91,14 @@ def is_user_message(msg: Any) -> bool: return isinstance(msg, HumanMessage) and getattr(msg, "name", None) != REMINDER_NAME +def current_turn(messages: list) -> list: + """Messages after the latest user message (this run's turn).""" + for i in range(len(messages) - 1, -1, -1): + if is_user_message(messages[i]): + return messages[i + 1:] + return messages + + def connection_id(runtime: ToolRuntime | None) -> int | None: ctx = getattr(runtime, "context", None) return getattr(ctx, "connection_id", None) diff --git a/agent/src/deep_agent/middleware/__init__.py b/agent/src/deep_agent/middleware/__init__.py new file mode 100644 index 0000000..257b627 --- /dev/null +++ b/agent/src/deep_agent/middleware/__init__.py @@ -0,0 +1,9 @@ +""" +Cross-cutting middleware (runs around every model call). + +- catalog.py loads the connection's catalog once per turn and appends it to the system prompt +- tool_filter.py hides deepagents built-in tools we don't use + +Middleware that belongs to one concern lives with it: the answer pipeline in deep_agent.answer.middleware, +the reviewer in deep_agent.validator.modes, the request context and date in deep_agent.context. +""" diff --git a/agent/src/deep_agent/catalog.py b/agent/src/deep_agent/middleware/catalog.py similarity index 100% rename from agent/src/deep_agent/catalog.py rename to agent/src/deep_agent/middleware/catalog.py diff --git a/agent/src/deep_agent/tool_filter.py b/agent/src/deep_agent/middleware/tool_filter.py similarity index 100% rename from agent/src/deep_agent/tool_filter.py rename to agent/src/deep_agent/middleware/tool_filter.py diff --git a/agent/src/deep_agent/observability.py b/agent/src/deep_agent/observability.py index 0d3cda7..6405ea4 100644 --- a/agent/src/deep_agent/observability.py +++ b/agent/src/deep_agent/observability.py @@ -69,7 +69,7 @@ def build_run_config( if user_id: metadata["langfuse_user_id"] = user_id if handlers: - from deep_agent.prompt_registry import load_prompt + from deep_agent.prompts.registry import load_prompt prompt = load_prompt("system") if prompt.client is not None: @@ -112,7 +112,7 @@ def annotate_current_span(metadata: dict[str, Any], level: str | None = None) -> @dataclass(frozen=True) class RunMetrics: """Plain counts and timing for one run, plus whether the submitted final SQL actually ran - (from the structured-answer verification in deep_agent.answer).""" + (from the structured-answer verification in deep_agent.answer.verification).""" model_calls: int tool_calls: int diff --git a/agent/src/deep_agent/prompts/__init__.py b/agent/src/deep_agent/prompts/__init__.py new file mode 100644 index 0000000..0356420 --- /dev/null +++ b/agent/src/deep_agent/prompts/__init__.py @@ -0,0 +1,4 @@ +""" +Prompts: system.md (main agent) and validator.md (reviewer), served by registry.py +(Langfuse `deep-agent/` when DEEP_AGENT_LANGFUSE_PROMPTS is on, else these packaged files). +""" diff --git a/agent/src/deep_agent/prompt_registry.py b/agent/src/deep_agent/prompts/registry.py similarity index 98% rename from agent/src/deep_agent/prompt_registry.py rename to agent/src/deep_agent/prompts/registry.py index da4544e..51e93fc 100644 --- a/agent/src/deep_agent/prompt_registry.py +++ b/agent/src/deep_agent/prompts/registry.py @@ -25,7 +25,7 @@ logger = logging.getLogger(__name__) -PROMPTS_DIR = Path(__file__).resolve().parent / "prompts" +PROMPTS_DIR = Path(__file__).resolve().parent # the .md files sit next to this module PROMPT_KEYS = ("system", "validator") diff --git a/agent/src/deep_agent/service.py b/agent/src/deep_agent/service.py index 11f86f4..4dbcef3 100644 --- a/agent/src/deep_agent/service.py +++ b/agent/src/deep_agent/service.py @@ -32,9 +32,9 @@ from agent.config import settings from agent.utils.redis_publisher import publish_node_event from deep_agent import observability -from deep_agent.answer import current_turn, render_markdown -from deep_agent.context import DeepAgentContext -from deep_agent.validator import VALIDATOR_NAME +from deep_agent.answer.render import render_markdown +from deep_agent.context import DeepAgentContext, current_turn +from deep_agent.validator.reviewer import VALIDATOR_NAME logger = logging.getLogger(__name__) diff --git a/agent/src/deep_agent/tools.py b/agent/src/deep_agent/tools.py deleted file mode 100644 index ca74e68..0000000 --- a/agent/src/deep_agent/tools.py +++ /dev/null @@ -1,634 +0,0 @@ -""" -Deep Agent tools. - -Every tool returns the same JSON envelope (see deep_agent.envelope): - {"ok": true, "data": ..., "error": null} | {"ok": false, "data": null, "error": {"name", "message", ...}} - -The connection's catalog is not a tool: it is loaded for every run and shown to the model by -CatalogMiddleware (deep_agent.catalog). DEEP_AGENT_TOOLS (bottom of this file) is what the model -gets; a few metadata tools are kept here unregistered because the catalog already contains -their information. -""" - -import logging -from typing import Any, Optional - -from langchain.tools import ToolRuntime -from langchain_core.messages import ToolMessage -from langchain_core.tools import tool -from langgraph.types import Command - -from agent.config import settings -from agent.services.geo_utils import geojson_to_simplified_wkt, get_geojson_polygon -from agent.utils import sql_guard -from agent.utils.jeen_metadata_client import get_jeen_metadata_client -from agent.utils.sql import clean_sql -from agent.utils.sql_guard import effective_cap -from core.trino import execute_query_sync -from deep_agent import trino_errors -from deep_agent.answer import executed_query_record -from deep_agent.context import DeepAgentContext, cached_catalog, connection_id, user_request -from deep_agent.envelope import ( - ENRICHMENT_ERROR, - LOCATION_NOT_FOUND, - METADATA_ERROR, - NOT_FOUND, - error, - fail, - ok, -) -from deep_agent.observability import annotate_current_span - -logger = logging.getLogger(__name__) - - -# --------------------------------------------------------------------------- -# Metadata (beyond the catalog) -# --------------------------------------------------------------------------- - -Runtime = ToolRuntime[DeepAgentContext] - - -def _metadata_failure(what: str, exc: Exception) -> str: - logger.warning("%s failed: %s", what, exc) - return fail(error( - METADATA_ERROR, - f"{what} failed: {exc}. The metadata service failed — this does not mean the data is empty.", - )) - - -@tool -async def get_database_tables(runtime: Runtime = None) -> str: - """ - Returns the list of all tables in the connection with their business descriptions and - exact quoted identifiers ("catalog"."schema"."table") for querying. - Use this for a quick, clean roster of available tables. - """ - try: - return ok(await get_jeen_metadata_client().get_tables(connection_id=connection_id(runtime))) - except Exception as e: - return _metadata_failure("get_database_tables", e) - - -@tool -async def get_table_columns(table_name: str, runtime: Runtime = None) -> str: - """ - Returns the columns for a specific table: data type, primary key flag, business description, - real example values, and profiling statistics. - - Args: - table_name (str): The table identifier (e.g. '"catalog"."schema"."orders"' or 'orders'). - """ - try: - return ok(await get_jeen_metadata_client().get_columns(table_name, connection_id=connection_id(runtime))) - except Exception as e: - return _metadata_failure(f"get_table_columns({table_name})", e) - - -@tool -async def get_table_relationships(runtime: Runtime = None) -> str: - """ - Returns the source-scoped foreign-key and semantic join relationships between tables. - Use this to identify exact join paths and foreign key pairs. - """ - try: - rels = await get_jeen_metadata_client().get_relationships(connection_id=connection_id(runtime)) - return ok({"relationships": rels}) - except Exception as e: - return _metadata_failure("get_table_relationships", e) - - -@tool -async def get_table_profile(table_name: str, runtime: Runtime = None) -> str: - """ - Retrieves the latest stored schema and statistics for one specific table. - - Use this to understand a single table's row counts, column roles, null ratios, distinct counts, - and min/max values before writing SQL against it. - Do NOT use this to fetch raw data rows; use `get_sample_rows` or `execute_trino_query` instead. - - Args: - table_name (str): The fully qualified, exact 3-part name of the table, - e.g., '"catalog"."schema"."table"'. - """ - try: - profile = await get_jeen_metadata_client().get_table_profile(table_name, connection_id=connection_id(runtime)) - except Exception as e: - return _metadata_failure(f"get_table_profile({table_name})", e) - if not profile: - return fail(error(NOT_FOUND, f"No stored profile for table {table_name}")) - return ok(profile) - - -@tool -async def get_column_profile(table_name: str, column_name: str, runtime: Runtime = None) -> str: - """ - Retrieves the full stored statistics of one column — detail the catalog does not show: - null count / ratio, top values with their frequencies, string lengths, quartiles and a histogram. - - The catalog already lists each column's type, semantic_type, distinct count, range and example - values (all values when the domain is complete), so call this only when you need that extra - detail — e.g. checking NULLs when a query returns 0 rows, or a value distribution. - - Args: - table_name (str): The fully qualified exact name of the table, e.g., '"catalog"."schema"."table"'. - column_name (str): The exact name of the column to profile. - """ - try: - profile = await get_jeen_metadata_client().get_column_profile( - table_name, column_name, connection_id=connection_id(runtime) - ) - except Exception as e: - return _metadata_failure(f"get_column_profile({table_name}.{column_name})", e) - if not profile: - return fail(error(NOT_FOUND, f"No stored profile for column {table_name}.{column_name}")) - return ok(profile) - - -# --------------------------------------------------------------------------- -# Query Execution -# --------------------------------------------------------------------------- - -def _run_sql(sql: str, row_cap: int | None) -> str: - return _execute(sql, row_cap)[0] - - -def _execute(sql: str, row_cap: int | None) -> tuple[str, dict | None]: - """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation. - - Returns (envelope, success payload or None). - row_cap=None means no ceiling: every returned row is passed through. - Telemetry (query id, timing, row count / Trino error) goes both into the envelope - and onto the current Langfuse tool observation. - """ - try: - res = execute_query_sync(sql, reuse_connection=True) - except Exception as e: - err = trino_errors.from_exception(e) - annotate_current_span({"error_name": err["name"]}, level="ERROR") - return fail(err), None - if not res.success: - err = trino_errors.from_result(res) - err["execution_time_ms"] = res.execution_time_ms - annotate_current_span({ - "trino_query_id": res.query_id, - "execution_time_ms": res.execution_time_ms, - "error_name": err["name"], - "error_type": err.get("type"), - }, level="ERROR") - return fail(err), None - - rows = res.rows or [] - truncated = row_cap is not None and len(rows) > row_cap - if truncated: - rows = rows[:row_cap] - annotate_current_span({ - "trino_query_id": res.query_id, - "execution_time_ms": res.execution_time_ms, - "row_count": len(rows), - "truncated": truncated, - }) - payload = { - "columns": res.columns, - "row_count": len(rows), - "truncated": truncated, - "rows": rows, - "query_id": res.query_id, - "execution_time_ms": res.execution_time_ms, - } - return ok(payload), payload - - -@tool -def execute_trino_query(sql: str, limit: int | None = None, runtime: Runtime = None) -> str | Command: - """ - Executes a read-only Trino SQL query and returns the resulting rows. - - Use this to test SQL queries against the actual database and perform exploratory data analysis. - Only a single SELECT / WITH (or SHOW / DESCRIBE) statement is accepted; anything that writes, - multiple statements, SQL comments and TABLE(...) pass-through functions are rejected with - error.name FORBIDDEN_STATEMENT. - - Results are capped at a configured row ceiling (when one is set): an outer LIMIT is enforced - automatically, and data.truncated is true when more rows existed than were returned. - - On failure, error carries Trino's own error, unmodified: - - error.name: Trino's error code (e.g. SYNTAX_ERROR, COLUMN_NOT_FOUND, TYPE_MISMATCH, - EXPRESSION_NOT_AGGREGATE, DIVISION_BY_ZERO) - - error.type: Trino's error class — USER_ERROR means the SQL itself is wrong; - INSUFFICIENT_RESOURCES, INTERNAL_ERROR and EXTERNAL come from the cluster or the source database - - error.message: Trino's message; error.location: {line, column} of the offending token - Two errors don't come from Trino: FORBIDDEN_STATEMENT (rejected before reaching Trino — rewrite - as a single read-only query without comments) and CONNECTION_ERROR (Trino could not be reached). - - Args: - sql (str): The exact Trino SQL query string to execute. Markdown fences and trailing - semicolons are stripped automatically. - limit (int, optional): Maximum number of rows to return. Defaults to the configured row - ceiling; a larger value is reduced to that ceiling. - """ - row_cap = effective_cap(limit, settings.DEEP_AGENT_MAX_ROWS) - try: - guarded = sql_guard.prepare(clean_sql(sql), row_cap) - except sql_guard.GuardError as e: - return fail(trino_errors.forbidden(str(e))) - content, payload = _execute(guarded.sql, guarded.row_cap if guarded.is_query else settings.DEEP_AGENT_MAX_ROWS) - if payload is None or not guarded.is_query or runtime is None or not runtime.tool_call_id: - return content - # Record the successful execution so the final answer can be bound to it (deep_agent.answer). - return Command(update={ - "executed_queries": [executed_query_record(sql, guarded.sql, payload, row_cap)], - "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="execute_trino_query")], - }) - - -@tool -def get_sample_rows(table_name: str, limit: int = 5) -> str: - """ - Retrieves a small number of raw data rows from a table using a live Trino query. - - Use this only when schema profiles don't provide enough context and you must see exact raw - data formats (e.g., date formatting, nested JSON structure, exact string casing). - Do NOT use this for counting or aggregating data. - - Args: - table_name (str): The fully qualified exact name of the table, e.g. '"catalog"."schema"."table"'. - limit (int): The number of rows to sample. Defaults to 5 (bounded by the configured sample ceiling). - """ - row_cap = effective_cap(limit if limit is not None else 5, settings.DEEP_AGENT_MAX_SAMPLE_ROWS) - try: - sql = sql_guard.sample_rows_sql(table_name, row_cap) - except sql_guard.GuardError as e: - return fail(trino_errors.forbidden(str(e))) - return _run_sql(sql, row_cap) - - -@tool -def get_column_distinct_values(table_name: str, column_name: str, limit: int = 50) -> str: - """ - Executes a live Trino query to fetch unique values for a specific column. - Use this to see exact existing strings in the database before writing an exact-match WHERE clause. - - BEST USED FOR: - - Low-cardinality `categorical` columns (e.g. status, priority, category) where you want to see all - 5-20 possible valid values, and the catalog doesn't already list all of them. - - DO NOT USE FOR: - - High-cardinality columns (`large_categorical`, `large_unit_id`, names, SKUs, cities). Dumping 50-100 - random values from a table with thousands of entities wastes tokens and latency without finding the - specific entity you need. Use `search_column_values` instead for targeted entity search. - - Numeric, date, or continuous columns (checking unique values is meaningless for value matching). - - Columns whose values the catalog already lists in full ("values (all)"). - - Args: - table_name (str): The fully qualified exact name of the table. - column_name (str): The exact name of the column (plain or double-quoted; spaces and Hebrew are fine). - limit (int): Maximum distinct values to return. Defaults to 50 (bounded by the configured row ceiling). - """ - row_cap = effective_cap(limit if limit is not None else 50, settings.DEEP_AGENT_MAX_ROWS) - try: - sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) - except sql_guard.GuardError as e: - return fail(trino_errors.forbidden(str(e))) - return _run_sql(sql, row_cap) - - -# --------------------------------------------------------------------------- -# SQL Quality -# --------------------------------------------------------------------------- - -_VALIDATE_PREFIX = "EXPLAIN (TYPE VALIDATE) " - - -@tool -def validate_sql(sql: str) -> str: - """ - Asks Trino to check a query without running it (EXPLAIN (TYPE VALIDATE)). Trino parses it and - resolves it against the catalog: syntax, table and column names, types and function signatures. - No data is read. - - Optional. For an invalid query, execute_trino_query fails at the same checking step, just as - fast and without reading data, with the same error fields — so validating first usually - saves nothing. Use it only to check a draft you do not want to run yet. It cannot tell you - whether the query returns rows. - - Returns ok=true with data.valid=true, or ok=false with the same error fields as - execute_trino_query (error.name, error.type, error.message, error.location). - - Args: - sql (str): The exact Trino SQL query string to validate. - """ - sql_clean = clean_sql(sql) - try: - sql_guard.parse_read_statement(sql_clean) - except sql_guard.GuardError as e: - return fail(trino_errors.forbidden(str(e))) - try: - res = execute_query_sync(f"{_VALIDATE_PREFIX}{sql_clean}", reuse_connection=True) - except Exception as e: - return fail(trino_errors.from_exception(e)) - if res.success: - return ok({"valid": True}) - err = trino_errors.from_result(res) - location = err.get("location") - if location and location["line"] == 1: - # Trino counts columns from the start of "EXPLAIN (TYPE VALIDATE) ..."; report them against the caller's SQL. - location["column"] = max(1, location["column"] - len(_VALIDATE_PREFIX)) - return fail(err) - - -# --------------------------------------------------------------------------- -# Metadata Search -# --------------------------------------------------------------------------- - -@tool -async def search_metadata(query: str, limit: int = 10, runtime: Runtime = None) -> str: - """ - Searches the metadata catalog across all tables, columns, relationships, and business terms. - - Use this to quickly discover relevant schema or glossary context when you aren't sure which - table to look at. Works well with Hebrew or English terms. - Do NOT use this to search for specific data row values (e.g., 'John Doe'); use - `search_column_values` instead. - - Args: - query (str): The search text (multilingual/Hebrew support) to match against metadata. - limit (int): Maximum number of results to return. Defaults to 10. - """ - try: - return ok(await get_jeen_metadata_client().search(query, limit, connection_id=connection_id(runtime))) - except Exception as e: - return _metadata_failure("search_metadata", e) - - -@tool -async def search_business_terms(query: str, limit: int = 10, runtime: Runtime = None) -> str: - """ - Searches the business glossary for terms relevant to a natural language question. - - Use this to bridge the gap between user vocabulary and database terminology - (e.g., matching 'מכירות' to the 'Revenue' column). Ranked by semantic meaning, not keywords. - Do NOT use this to search for database tables or column names directly. - - Args: - query (str): A natural language question or phrase (multilingual support). - limit (int): Maximum number of results to return. Defaults to 10. - """ - try: - terms = await get_jeen_metadata_client().search_business_terms(query, limit, connection_id=connection_id(runtime)) - return ok(terms) - except Exception as e: - return _metadata_failure("search_business_terms", e) - - -@tool -async def search_knowledge_pairs(query: str, limit: int = 10, runtime: Runtime = None) -> str: - """ - Searches saved question-and-query examples that are semantically similar to the user's question. - - Use this to find few-shot examples of how similar questions were solved previously. Even if you - think you know how to write the query, similar past examples often reveal domain-specific SQL - conventions, exact JOIN paths, or edge cases you haven't considered. - - Pass the raw Hebrew natural language question exactly as the user wrote it — never SQL keywords. - Only the stored question is matched (never the query text), so full sentences work best. - - Args: - query (str): The natural language user question (multilingual/Hebrew support). - limit (int): Maximum number of results to return. Defaults to 10. - """ - try: - pairs = await get_jeen_metadata_client().search_knowledge_pairs(query, limit, connection_id=connection_id(runtime)) - return ok(pairs) - except Exception as e: - return _metadata_failure("search_knowledge_pairs", e) - - -def _round_or_none(value: Any) -> float | None: - try: - return round(float(value), 3) - except (TypeError, ValueError): - return None - - -def _value_match(v: Any) -> dict: - if not isinstance(v, dict): - return {"value": v} - return { - "value": v.get("value"), - "table": v.get("table_name") or v.get("table"), - "column": v.get("column_name") or v.get("column"), - "keyword_similarity": _round_or_none(v.get("keyword_similarity")), - "semantic_distance": _round_or_none(v.get("semantic_distance")), - } - - -@tool -async def search_column_values( - search_term: str, - table: Optional[str] = None, - column: Optional[str] = None, - limit: int = 10, - runtime: Runtime = None, -) -> str: - """ - Searches for exact real values contained within indexed columns across the database. - - SUPPORTED COLUMN TYPES: - Works exclusively on high-cardinality columns profiled as: - - `large_categorical` - - `large_unit_id` - ⚠️ Do NOT use on standard `categorical` or `boolean` columns (e.g. a `status` column) — they are - not indexed in vector search and will return 0 matches! Use `get_column_distinct_values` or the catalog instead. - Do NOT use on numeric, date/timestamp, or geometry columns. - - WHEN TO USE: - - Use whenever you need to find how a high-cardinality entity is represented or spelled in the database - (e.g., finding 'Acme Corporation LLC' from 'Acme Corp', or the stored spelling of a Hebrew term). Multilingual, - keyword, and vector search finds the exact database spelling. - - Returns data.matches — up to `limit` matching values (use each 'value' verbatim in SQL) with: - - 'keyword_similarity' close to 1.0 = strong lexical match - - 'semantic_distance' close to 0.0 = strong semantic match - data.limit_reached is true when exactly `limit` matches came back: there may be more — call again - with a higher `limit` before filtering on the list. - - Args: - search_term (str): The specific value to look for (partial or full string, Hebrew or English). - table (str, optional): Restrict search to one table name. Omit to search all tables. - column (str, optional): Restrict search to one column name. Omit to search all columns. - limit (int): Maximum number of results to return. Defaults to 10. - """ - try: - res = await get_jeen_metadata_client().search_column_values( - search_term=search_term, table=table, column=column, limit=limit, raw=True, - connection_id=connection_id(runtime), - ) - except Exception as e: - return _metadata_failure("search_column_values", e) - - values = (res.get("values") or []) if isinstance(res, dict) else [] - matches = [_value_match(v) for v in values] - limit_reached = len(matches) >= limit - if not matches: - notice = "No matches — the value may not exist in this column, or the column is not indexed (only large_categorical / large_unit_id are)." - elif limit_reached: - notice = f"Returned the first {limit} matches (the limit); there may be more — call again with a higher limit." - else: - notice = None - return ok({ - "search_term": search_term, - "matches": matches, - "limit_reached": limit_reached, - "notice": notice, - }) - - -# --------------------------------------------------------------------------- -# Category Enrichment (Automatic Filter Value Correction) -# --------------------------------------------------------------------------- - -@tool -async def enrich_sql_filters(sql: str, runtime: Runtime = None) -> str | Command: - """ - Automatically corrects categorical filter values in a draft SQL query to match exact - database spellings using semantic search and LLM-guided AST transformation. - - Use this AFTER you have written a draft SQL query that contains WHERE clause filters on - categorical (text) columns. It will: - 1. Parse the SQL AST to find comparison filters - 2. Semantically search the database for canonical matching values - 3. Use an LLM to select the best match - 4. Rewrite the SQL with exact canonical values (AST-level, not string replacement) - - The catalog and the user's question are taken from the conversation automatically — - pass only the SQL. - - This is especially powerful for Hebrew→English column value resolution and large categorical - columns where manually calling search_column_values for every filter would be tedious. - - Do NOT use this on purely numeric SQL or when you already have exact confirmed values. - - Returns data.sql (the enriched SQL, or the original if nothing changed), data.enriched and - data.changes (one entry per corrected filter). - - Args: - sql (str): The draft SQL query to enrich. - """ - from agent.nodes.refiner import parse_jeen_catalog_tables - from agent.services.enrichment_orchestrator import EnrichmentOrchestrator - - sql_clean = clean_sql(sql) - - catalog = cached_catalog(runtime) - fetched_catalog = False - if not catalog: - try: - catalog = await get_jeen_metadata_client().get_catalog_prompt(connection_id=connection_id(runtime)) - except Exception as e: - return _metadata_failure("enrich_sql_filters (catalog fetch)", e) - fetched_catalog = True - - try: - schema, tables = parse_jeen_catalog_tables(catalog) - if not tables: - return fail(error(ENRICHMENT_ERROR, "No tables could be parsed from the connection catalog. The SQL is unchanged.", - original_sql=sql_clean)) - - refined_sql, plan, enriched = await EnrichmentOrchestrator.enrich_query( - user_request=user_request(runtime), - initial_sql=sql_clean, - schema=schema, - tables=tables, - config=runtime.config if runtime is not None else None, - ) - except Exception as e: - logger.error("enrich_sql_filters failed: %s", e, exc_info=True) - return fail(error(ENRICHMENT_ERROR, f"{e}. The SQL is unchanged.", original_sql=sql_clean)) - - changes = [] - if enriched and plan: - changes = [ - { - "column": tf.column, - "original_value": tf.original_value, - "refined_values": tf.refined_values, - "old_operator": tf.old_operator, - "new_operator": tf.new_operator, - } - for tf in plan.enrichment_details - if tf.changed_filter - ] - is_enriched = bool(enriched and plan) - content = ok({"enriched": is_enriched, "sql": refined_sql if is_enriched else sql_clean, "changes": changes}) - - if fetched_catalog and runtime is not None and runtime.tool_call_id: - # Cache the catalog we had to fetch so the next call in this thread doesn't refetch it. - return Command(update={ - "jeen_catalog": catalog, - "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="enrich_sql_filters")], - }) - return content - - -# --------------------------------------------------------------------------- -# Geospatial -# --------------------------------------------------------------------------- - -@tool -def resolve_location_to_wkt(location_name: str) -> str: - """ - Resolves a geographic location name to its WKT (Well-Known Text) polygon representation. - - Use this whenever the user's query involves a geographic area and you need a WKT polygon for - a Trino ST_GeometryFromText() / ST_Within() / ST_Contains() call. - - Supports Hebrew location names directly (e.g., 'תל אביב', 'ירושלים', 'חיפה'). - Returns data.wkt — the polygon as plain (unquoted) WKT, e.g. POLYGON((...)). In SQL, wrap it - in single quotes: ST_GeometryFromText(''). - - The function uses rate-limited Nominatim geocoding with caching and automatic WKT - simplification (binary search). Only area geometries are returned (never points). - - Do NOT use this for exact addresses (e.g., "Rothschild 10, Tel Aviv"); it is designed for - administrative areas: cities, regions, districts, and countries. - - Args: - location_name (str): The geographic location name to resolve. Hebrew names are - accepted and preferred for Israeli locations. - """ - geojson = get_geojson_polygon(location_name) - quoted = geojson_to_simplified_wkt(geojson) if geojson else None # returns a single-quoted literal - if not quoted: - return fail(error(LOCATION_NOT_FOUND, f"Could not resolve location '{location_name}' to an area polygon.")) - return ok({"location": location_name, "wkt": quoted.strip("'")}) - - -# The tools the model gets (order = order shown to the model). The catalog itself is loaded for -# every run by CatalogMiddleware, so there is no catalog tool. -DEEP_AGENT_TOOLS = [ - # Values & places - search_column_values, - get_column_distinct_values, - get_column_profile, - resolve_location_to_wkt, - # Query execution - execute_trino_query, - get_sample_rows, - validate_sql, - # Post-processing - enrich_sql_filters, -] - -# Implemented but not registered: the catalog already contains their information (tables, columns, -# profile stats, relationships, business terms, knowledge pairs). Register again if a connection's -# catalog grows too large to load whole, or when targeted search over those sections pays off. -UNREGISTERED_TOOLS = [ - get_database_tables, - get_table_columns, - get_table_profile, - get_table_relationships, - search_metadata, - search_business_terms, - search_knowledge_pairs, -] diff --git a/agent/src/deep_agent/tools/__init__.py b/agent/src/deep_agent/tools/__init__.py new file mode 100644 index 0000000..6d8e748 --- /dev/null +++ b/agent/src/deep_agent/tools/__init__.py @@ -0,0 +1,34 @@ +""" +The Deep Agent's tools. + +Every tool returns the same JSON envelope (deep_agent.tools.envelope): + {"ok": true, "data": ..., "error": null} | {"ok": false, "data": null, "error": {"name", "message", ...}} + +- sql.py execute_trino_query, get_sample_rows, get_column_distinct_values, validate_sql +- metadata.py search_column_values, get_column_profile +- enrichment.py enrich_sql_filters +- location.py resolve_location_to_wkt + +The connection's catalog is not a tool: CatalogMiddleware (deep_agent.middleware.catalog) loads it +for every run and puts it in the prompt. +""" + +from deep_agent.tools.enrichment import enrich_sql_filters +from deep_agent.tools.location import resolve_location_to_wkt +from deep_agent.tools.metadata import get_column_profile, search_column_values +from deep_agent.tools.sql import execute_trino_query, get_column_distinct_values, get_sample_rows, validate_sql + +# The tools the model gets (order = order shown to the model). +DEEP_AGENT_TOOLS = [ + # Values & places + search_column_values, + get_column_distinct_values, + get_column_profile, + resolve_location_to_wkt, + # Query execution + execute_trino_query, + get_sample_rows, + validate_sql, + # Post-processing + enrich_sql_filters, +] diff --git a/agent/src/deep_agent/tools/enrichment.py b/agent/src/deep_agent/tools/enrichment.py new file mode 100644 index 0000000..a8deb1e --- /dev/null +++ b/agent/src/deep_agent/tools/enrichment.py @@ -0,0 +1,101 @@ +""" +enrich_sql_filters: correct categorical filter values in a draft SQL to the stored spellings, +reusing the legacy graph's enrichment pipeline (agent.services.enrichment_orchestrator). +""" + +import logging + +from langchain_core.messages import ToolMessage +from langchain_core.tools import tool +from langgraph.types import Command + +from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from agent.utils.sql import clean_sql +from deep_agent.context import Runtime, cached_catalog, connection_id, user_request +from deep_agent.tools.envelope import ENRICHMENT_ERROR, error, fail, ok +from deep_agent.tools.metadata import metadata_failure + +logger = logging.getLogger(__name__) + + +@tool +async def enrich_sql_filters(sql: str, runtime: Runtime = None) -> str | Command: + """ + Automatically corrects categorical filter values in a draft SQL query to match exact + database spellings using semantic search and LLM-guided AST transformation. + + Use this AFTER you have written a draft SQL query that contains WHERE clause filters on + categorical (text) columns. It will: + 1. Parse the SQL AST to find comparison filters + 2. Semantically search the database for canonical matching values + 3. Use an LLM to select the best match + 4. Rewrite the SQL with exact canonical values (AST-level, not string replacement) + + The catalog and the user's question are taken from the conversation automatically — + pass only the SQL. + + This is especially powerful for Hebrew→English column value resolution and large categorical + columns where manually calling search_column_values for every filter would be tedious. + + Do NOT use this on purely numeric SQL or when you already have exact confirmed values. + + Returns data.sql (the enriched SQL, or the original if nothing changed), data.enriched and + data.changes (one entry per corrected filter). + + Args: + sql (str): The draft SQL query to enrich. + """ + from agent.nodes.refiner import parse_jeen_catalog_tables + from agent.services.enrichment_orchestrator import EnrichmentOrchestrator + + sql_clean = clean_sql(sql) + + catalog = cached_catalog(runtime) + fetched_catalog = False + if not catalog: + try: + catalog = await get_jeen_metadata_client().get_catalog_prompt(connection_id=connection_id(runtime)) + except Exception as e: + return metadata_failure("enrich_sql_filters (catalog fetch)", e) + fetched_catalog = True + + try: + schema, tables = parse_jeen_catalog_tables(catalog) + if not tables: + return fail(error(ENRICHMENT_ERROR, "No tables could be parsed from the connection catalog. The SQL is unchanged.", + original_sql=sql_clean)) + + refined_sql, plan, enriched = await EnrichmentOrchestrator.enrich_query( + user_request=user_request(runtime), + initial_sql=sql_clean, + schema=schema, + tables=tables, + config=runtime.config if runtime is not None else None, + ) + except Exception as e: + logger.error("enrich_sql_filters failed: %s", e, exc_info=True) + return fail(error(ENRICHMENT_ERROR, f"{e}. The SQL is unchanged.", original_sql=sql_clean)) + + changes = [] + if enriched and plan: + changes = [ + { + "column": tf.column, + "original_value": tf.original_value, + "refined_values": tf.refined_values, + "old_operator": tf.old_operator, + "new_operator": tf.new_operator, + } + for tf in plan.enrichment_details + if tf.changed_filter + ] + is_enriched = bool(enriched and plan) + content = ok({"enriched": is_enriched, "sql": refined_sql if is_enriched else sql_clean, "changes": changes}) + + if fetched_catalog and runtime is not None and runtime.tool_call_id: + # Cache the catalog we had to fetch so the next call in this thread doesn't refetch it. + return Command(update={ + "jeen_catalog": catalog, + "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="enrich_sql_filters")], + }) + return content diff --git a/agent/src/deep_agent/envelope.py b/agent/src/deep_agent/tools/envelope.py similarity index 97% rename from agent/src/deep_agent/envelope.py rename to agent/src/deep_agent/tools/envelope.py index 986bcab..e03d639 100644 --- a/agent/src/deep_agent/envelope.py +++ b/agent/src/deep_agent/tools/envelope.py @@ -4,7 +4,7 @@ {"ok": true, "data": , "error": null} {"ok": false, "data": null, "error": {"name", "message", ...details}} -error.name is Trino's own errorName for SQL failures (see deep_agent.trino_errors), or one of +error.name is Trino's own errorName for SQL failures (see deep_agent.tools.trino_errors), or one of the names below for failures of our own tools. Serialised compactly (no indentation whitespace, raw Unicode) to keep tool output tokens low. diff --git a/agent/src/deep_agent/tools/location.py b/agent/src/deep_agent/tools/location.py new file mode 100644 index 0000000..7e6c669 --- /dev/null +++ b/agent/src/deep_agent/tools/location.py @@ -0,0 +1,37 @@ +""" +resolve_location_to_wkt: a place name (Hebrew or English) to its area polygon as WKT, via Nominatim. +""" + +from langchain_core.tools import tool + +from agent.services.geo_utils import geojson_to_simplified_wkt, get_geojson_polygon +from deep_agent.tools.envelope import LOCATION_NOT_FOUND, error, fail, ok + + +@tool +def resolve_location_to_wkt(location_name: str) -> str: + """ + Resolves a geographic location name to its WKT (Well-Known Text) polygon representation. + + Use this whenever the user's query involves a geographic area and you need a WKT polygon for + a Trino ST_GeometryFromText() / ST_Within() / ST_Contains() call. + + Supports Hebrew location names directly (e.g., 'תל אביב', 'ירושלים', 'חיפה'). + Returns data.wkt — the polygon as plain (unquoted) WKT, e.g. POLYGON((...)). In SQL, wrap it + in single quotes: ST_GeometryFromText(''). + + The function uses rate-limited Nominatim geocoding with caching and automatic WKT + simplification (binary search). Only area geometries are returned (never points). + + Do NOT use this for exact addresses (e.g., "Rothschild 10, Tel Aviv"); it is designed for + administrative areas: cities, regions, districts, and countries. + + Args: + location_name (str): The geographic location name to resolve. Hebrew names are + accepted and preferred for Israeli locations. + """ + geojson = get_geojson_polygon(location_name) + quoted = geojson_to_simplified_wkt(geojson) if geojson else None # returns a single-quoted literal + if not quoted: + return fail(error(LOCATION_NOT_FOUND, f"Could not resolve location '{location_name}' to an area polygon.")) + return ok({"location": location_name, "wkt": quoted.strip("'")}) diff --git a/agent/src/deep_agent/tools/metadata.py b/agent/src/deep_agent/tools/metadata.py new file mode 100644 index 0000000..4d31314 --- /dev/null +++ b/agent/src/deep_agent/tools/metadata.py @@ -0,0 +1,130 @@ +""" +Metadata tools: stored column statistics and value search, from the Jeen metadata service. + +The connection's catalog itself is not a tool: it is loaded for every run and shown to the +model by CatalogMiddleware (deep_agent.middleware.catalog). +""" + +import logging +from typing import Any, Optional + +from langchain_core.tools import tool + +from agent.utils.jeen_metadata_client import get_jeen_metadata_client +from deep_agent.context import Runtime, connection_id +from deep_agent.tools.envelope import METADATA_ERROR, NOT_FOUND, error, fail, ok + +logger = logging.getLogger(__name__) + + +def metadata_failure(what: str, exc: Exception) -> str: + logger.warning("%s failed: %s", what, exc) + return fail(error( + METADATA_ERROR, + f"{what} failed: {exc}. The metadata service failed — this does not mean the data is empty.", + )) + + +@tool +async def get_column_profile(table_name: str, column_name: str, runtime: Runtime = None) -> str: + """ + Retrieves the full stored statistics of one column — detail the catalog does not show: + null count / ratio, top values with their frequencies, string lengths, quartiles and a histogram. + + The catalog already lists each column's type, semantic_type, distinct count, range and example + values (all values when the domain is complete), so call this only when you need that extra + detail — e.g. checking NULLs when a query returns 0 rows, or a value distribution. + + Args: + table_name (str): The fully qualified exact name of the table, e.g., '"catalog"."schema"."table"'. + column_name (str): The exact name of the column to profile. + """ + try: + profile = await get_jeen_metadata_client().get_column_profile( + table_name, column_name, connection_id=connection_id(runtime) + ) + except Exception as e: + return metadata_failure(f"get_column_profile({table_name}.{column_name})", e) + if not profile: + return fail(error(NOT_FOUND, f"No stored profile for column {table_name}.{column_name}")) + return ok(profile) + + +def _round_or_none(value: Any) -> float | None: + try: + return round(float(value), 3) + except (TypeError, ValueError): + return None + + +def _value_match(v: Any) -> dict: + if not isinstance(v, dict): + return {"value": v} + return { + "value": v.get("value"), + "table": v.get("table_name") or v.get("table"), + "column": v.get("column_name") or v.get("column"), + "keyword_similarity": _round_or_none(v.get("keyword_similarity")), + "semantic_distance": _round_or_none(v.get("semantic_distance")), + } + + +@tool +async def search_column_values( + search_term: str, + table: Optional[str] = None, + column: Optional[str] = None, + limit: int = 10, + runtime: Runtime = None, +) -> str: + """ + Searches for exact real values contained within indexed columns across the database. + + SUPPORTED COLUMN TYPES: + Works exclusively on high-cardinality columns profiled as: + - `large_categorical` + - `large_unit_id` + ⚠️ Do NOT use on standard `categorical` or `boolean` columns (e.g. a `status` column) — they are + not indexed in vector search and will return 0 matches! Use `get_column_distinct_values` or the catalog instead. + Do NOT use on numeric, date/timestamp, or geometry columns. + + WHEN TO USE: + - Use whenever you need to find how a high-cardinality entity is represented or spelled in the database + (e.g., finding 'Acme Corporation LLC' from 'Acme Corp', or the stored spelling of a Hebrew term). Multilingual, + keyword, and vector search finds the exact database spelling. + + Returns data.matches — up to `limit` matching values (use each 'value' verbatim in SQL) with: + - 'keyword_similarity' close to 1.0 = strong lexical match + - 'semantic_distance' close to 0.0 = strong semantic match + data.limit_reached is true when exactly `limit` matches came back: there may be more — call again + with a higher `limit` before filtering on the list. + + Args: + search_term (str): The specific value to look for (partial or full string, Hebrew or English). + table (str, optional): Restrict search to one table name. Omit to search all tables. + column (str, optional): Restrict search to one column name. Omit to search all columns. + limit (int): Maximum number of results to return. Defaults to 10. + """ + try: + res = await get_jeen_metadata_client().search_column_values( + search_term=search_term, table=table, column=column, limit=limit, raw=True, + connection_id=connection_id(runtime), + ) + except Exception as e: + return metadata_failure("search_column_values", e) + + values = (res.get("values") or []) if isinstance(res, dict) else [] + matches = [_value_match(v) for v in values] + limit_reached = len(matches) >= limit + if not matches: + notice = "No matches — the value may not exist in this column, or the column is not indexed (only large_categorical / large_unit_id are)." + elif limit_reached: + notice = f"Returned the first {limit} matches (the limit); there may be more — call again with a higher limit." + else: + notice = None + return ok({ + "search_term": search_term, + "matches": matches, + "limit_reached": limit_reached, + "notice": notice, + }) diff --git a/agent/src/deep_agent/tools/sql.py b/agent/src/deep_agent/tools/sql.py new file mode 100644 index 0000000..087f71d --- /dev/null +++ b/agent/src/deep_agent/tools/sql.py @@ -0,0 +1,212 @@ +""" +SQL tools: run read-only queries on Trino, sample a table, list a column's distinct values, and +dry-run a query (validate_sql). + +Every statement goes through agent.utils.sql_guard (one read-only statement, row ceiling, safe +identifiers). Failures carry Trino's own error unchanged (deep_agent.tools.trino_errors). A +successful execute_trino_query is recorded in state so the final answer can be bound to it +(deep_agent.answer.verification). +""" + +import logging + +from langchain_core.messages import ToolMessage +from langchain_core.tools import tool +from langgraph.types import Command + +import deep_agent.tools.trino_errors as trino_errors +from agent.config import settings +from agent.utils import sql_guard +from agent.utils.sql import clean_sql +from agent.utils.sql_guard import effective_cap +from core.trino import execute_query_sync +from deep_agent.answer.verification import executed_query_record +from deep_agent.context import Runtime +from deep_agent.observability import annotate_current_span +from deep_agent.tools.envelope import fail, ok + +logger = logging.getLogger(__name__) + + +def _run_sql(sql: str, row_cap: int | None) -> str: + return _execute(sql, row_cap)[0] + + +def _execute(sql: str, row_cap: int | None) -> tuple[str, dict | None]: + """Execute already-guarded SQL that fetches up to row_cap + 1 rows; report truncation. + + Returns (envelope, success payload or None). + row_cap=None means no ceiling: every returned row is passed through. + Telemetry (query id, timing, row count / Trino error) goes both into the envelope + and onto the current Langfuse tool observation. + """ + try: + res = execute_query_sync(sql, reuse_connection=True) + except Exception as e: + err = trino_errors.from_exception(e) + annotate_current_span({"error_name": err["name"]}, level="ERROR") + return fail(err), None + if not res.success: + err = trino_errors.from_result(res) + err["execution_time_ms"] = res.execution_time_ms + annotate_current_span({ + "trino_query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, + "error_name": err["name"], + "error_type": err.get("type"), + }, level="ERROR") + return fail(err), None + + rows = res.rows or [] + truncated = row_cap is not None and len(rows) > row_cap + if truncated: + rows = rows[:row_cap] + annotate_current_span({ + "trino_query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, + "row_count": len(rows), + "truncated": truncated, + }) + payload = { + "columns": res.columns, + "row_count": len(rows), + "truncated": truncated, + "rows": rows, + "query_id": res.query_id, + "execution_time_ms": res.execution_time_ms, + } + return ok(payload), payload + + +@tool +def execute_trino_query(sql: str, limit: int | None = None, runtime: Runtime = None) -> str | Command: + """ + Executes a read-only Trino SQL query and returns the resulting rows. + + Use this to test SQL queries against the actual database and perform exploratory data analysis. + Only a single SELECT / WITH (or SHOW / DESCRIBE) statement is accepted; anything that writes, + multiple statements, SQL comments and TABLE(...) pass-through functions are rejected with + error.name FORBIDDEN_STATEMENT. + + Results are capped at a configured row ceiling (when one is set): an outer LIMIT is enforced + automatically, and data.truncated is true when more rows existed than were returned. + + On failure, error carries Trino's own error, unmodified: + - error.name: Trino's error code (e.g. SYNTAX_ERROR, COLUMN_NOT_FOUND, TYPE_MISMATCH, + EXPRESSION_NOT_AGGREGATE, DIVISION_BY_ZERO) + - error.type: Trino's error class — USER_ERROR means the SQL itself is wrong; + INSUFFICIENT_RESOURCES, INTERNAL_ERROR and EXTERNAL come from the cluster or the source database + - error.message: Trino's message; error.location: {line, column} of the offending token + Two errors don't come from Trino: FORBIDDEN_STATEMENT (rejected before reaching Trino — rewrite + as a single read-only query without comments) and CONNECTION_ERROR (Trino could not be reached). + + Args: + sql (str): The exact Trino SQL query string to execute. Markdown fences and trailing + semicolons are stripped automatically. + limit (int, optional): Maximum number of rows to return. Defaults to the configured row + ceiling; a larger value is reduced to that ceiling. + """ + row_cap = effective_cap(limit, settings.DEEP_AGENT_MAX_ROWS) + try: + guarded = sql_guard.prepare(clean_sql(sql), row_cap) + except sql_guard.GuardError as e: + return fail(trino_errors.forbidden(str(e))) + content, payload = _execute(guarded.sql, guarded.row_cap if guarded.is_query else settings.DEEP_AGENT_MAX_ROWS) + if payload is None or not guarded.is_query or runtime is None or not runtime.tool_call_id: + return content + # Record the successful execution so the final answer can be bound to it (deep_agent.answer.verification). + return Command(update={ + "executed_queries": [executed_query_record(sql, guarded.sql, payload, row_cap)], + "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="execute_trino_query")], + }) + + +@tool +def get_sample_rows(table_name: str, limit: int = 5) -> str: + """ + Retrieves a small number of raw data rows from a table using a live Trino query. + + Use this only when schema profiles don't provide enough context and you must see exact raw + data formats (e.g., date formatting, nested JSON structure, exact string casing). + Do NOT use this for counting or aggregating data. + + Args: + table_name (str): The fully qualified exact name of the table, e.g. '"catalog"."schema"."table"'. + limit (int): The number of rows to sample. Defaults to 5 (bounded by the configured sample ceiling). + """ + row_cap = effective_cap(limit if limit is not None else 5, settings.DEEP_AGENT_MAX_SAMPLE_ROWS) + try: + sql = sql_guard.sample_rows_sql(table_name, row_cap) + except sql_guard.GuardError as e: + return fail(trino_errors.forbidden(str(e))) + return _run_sql(sql, row_cap) + + +@tool +def get_column_distinct_values(table_name: str, column_name: str, limit: int = 50) -> str: + """ + Executes a live Trino query to fetch unique values for a specific column. + Use this to see exact existing strings in the database before writing an exact-match WHERE clause. + + BEST USED FOR: + - Low-cardinality `categorical` columns (e.g. status, priority, category) where you want to see all + 5-20 possible valid values, and the catalog doesn't already list all of them. + + DO NOT USE FOR: + - High-cardinality columns (`large_categorical`, `large_unit_id`, names, SKUs, cities). Dumping 50-100 + random values from a table with thousands of entities wastes tokens and latency without finding the + specific entity you need. Use `search_column_values` instead for targeted entity search. + - Numeric, date, or continuous columns (checking unique values is meaningless for value matching). + - Columns whose values the catalog already lists in full ("values (all)"). + + Args: + table_name (str): The fully qualified exact name of the table. + column_name (str): The exact name of the column (plain or double-quoted; spaces and Hebrew are fine). + limit (int): Maximum distinct values to return. Defaults to 50 (bounded by the configured row ceiling). + """ + row_cap = effective_cap(limit if limit is not None else 50, settings.DEEP_AGENT_MAX_ROWS) + try: + sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) + except sql_guard.GuardError as e: + return fail(trino_errors.forbidden(str(e))) + return _run_sql(sql, row_cap) + + +_VALIDATE_PREFIX = "EXPLAIN (TYPE VALIDATE) " + + +@tool +def validate_sql(sql: str) -> str: + """ + Asks Trino to check a query without running it (EXPLAIN (TYPE VALIDATE)). Trino parses it and + resolves it against the catalog: syntax, table and column names, types and function signatures. + No data is read. + + Optional. For an invalid query, execute_trino_query fails at the same checking step, just as + fast and without reading data, with the same error fields — so validating first usually + saves nothing. Use it only to check a draft you do not want to run yet. It cannot tell you + whether the query returns rows. + + Returns ok=true with data.valid=true, or ok=false with the same error fields as + execute_trino_query (error.name, error.type, error.message, error.location). + + Args: + sql (str): The exact Trino SQL query string to validate. + """ + sql_clean = clean_sql(sql) + try: + sql_guard.parse_read_statement(sql_clean) + except sql_guard.GuardError as e: + return fail(trino_errors.forbidden(str(e))) + try: + res = execute_query_sync(f"{_VALIDATE_PREFIX}{sql_clean}", reuse_connection=True) + except Exception as e: + return fail(trino_errors.from_exception(e)) + if res.success: + return ok({"valid": True}) + err = trino_errors.from_result(res) + location = err.get("location") + if location and location["line"] == 1: + # Trino counts columns from the start of "EXPLAIN (TYPE VALIDATE) ..."; report them against the caller's SQL. + location["column"] = max(1, location["column"] - len(_VALIDATE_PREFIX)) + return fail(err) diff --git a/agent/src/deep_agent/trino_errors.py b/agent/src/deep_agent/tools/trino_errors.py similarity index 96% rename from agent/src/deep_agent/trino_errors.py rename to agent/src/deep_agent/tools/trino_errors.py index 8a01cf1..b7643c6 100644 --- a/agent/src/deep_agent/trino_errors.py +++ b/agent/src/deep_agent/tools/trino_errors.py @@ -10,7 +10,7 @@ """ from core.trino import TrinoExecutionResult -from deep_agent.envelope import error +from deep_agent.tools.envelope import error FORBIDDEN_STATEMENT = "FORBIDDEN_STATEMENT" CONNECTION_ERROR = "CONNECTION_ERROR" diff --git a/agent/src/deep_agent/validator.py b/agent/src/deep_agent/validator.py deleted file mode 100644 index 3ca8ab6..0000000 --- a/agent/src/deep_agent/validator.py +++ /dev/null @@ -1,300 +0,0 @@ -""" -Independent semantic review of the Deep Agent's answers. - -The reviewer is a separate agent with a fresh context and read-only diagnostic tools. It gets -the user's request, the SQL, and (usually) the result rows and stated assumptions — never the -main agent's reasoning, so it can't simply agree with it — and returns `submit_verdict` -(pass / fail + issues with evidence). DEEP_AGENT_SEMANTIC_VALIDATION picks how it is used: - -on_demand - A `semantic-validator` subagent the agent calls through `task` when it judges a review - worthwhile (its description says when, and what to send). The verdict comes back to the - agent as JSON; acting on it is up to the agent. Each review is recorded. - -always (default) - Every accepted `submit_answer` call is reviewed before the run can end: - - pass -> the run ends normally; - - fail -> the "Answer received." tool message is replaced by the review's feedback and the - model is sent back. It either fixes the SQL and submits again (reviewed again), or submits - the same SQL with `validation_response` — a dispute, which ends the loop. If it stops - without resubmitting, its last (failed) answer stands, marked "failed". - DEEP_AGENT_VALIDATOR_MAX_ROUNDS optionally limits reviews per turn (default: no limit). - -off - No reviewer. - -Both modes record reviews in `semantic_validations`; the outcome for the final answer goes to -final_result["semantic_validation"] (deep_agent.answer.validation_summary). Semantic checks also -stay mandatory in the main agent's own prompt; the reviewer is an extra, independent check. -""" - -import logging -import re -import uuid -from typing import Any, Literal - -from langchain.agents import create_agent -from langchain.agents.middleware import AgentMiddleware, hook_config -from langchain_core.language_models import BaseChatModel -from langchain_core.messages import HumanMessage, ToolMessage -from pydantic import BaseModel, Field, create_model, model_validator - -from deep_agent.answer import ( - ANSWER_RECEIVED, - TOOL_NAME, - AnswerRecoveryMiddleware, - SubmitReminderMiddleware, - last_submission, - match_execution, - normalize_sql, - submission_strategy, -) -from deep_agent.catalog import CatalogMiddleware -from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware, DeepAgentRuntimeState, is_user_message -from deep_agent.prompt_registry import PromptRefreshMiddleware, load_prompt -from deep_agent.tools import ( - execute_trino_query, - get_column_distinct_values, - get_column_profile, - get_sample_rows, - search_column_values, -) - -logger = logging.getLogger(__name__) - -ValidationMode = Literal["on_demand", "always", "off"] - -VERDICT_TOOL = "submit_verdict" -VALIDATOR_NAME = "semantic-validator" -REVIEW_CONFIG = {"run_name": VALIDATOR_NAME, "tags": [VALIDATOR_NAME]} # the tag marks the reviewer's nested runs -VALIDATOR_TOOLS = [execute_trino_query, get_sample_rows, get_column_distinct_values, search_column_values, - get_column_profile] - -# What the main agent sees about the on-demand subagent (in the `task` tool's list of subagents). -ON_DEMAND_DESCRIPTION = ( - "Independent reviewer: checks whether a SQL answer really answers the user's request, using read-only " - "diagnostic queries, and returns JSON {verdict: pass|fail, issues: [{problem, evidence}]}. It has not seen " - "your work, which is the point. Worth it before submit_answer when the answer involves joins, aggregation " - "or grouping, date ranges, several conditions, an interpretation you had to choose, 0 rows or a surprising " - "number. Skip it for simple lookups you have already verified. In the task description send only: the " - "user's messages verbatim (all of them, for a follow-up), the SQL to review in a ```sql block, its result " - "rows, and your stated assumptions — not your reasoning or your conclusion. On fail, fix the SQL (and " - "review again if the change is substantial), or keep it only if you can show why the issue is wrong." -) - - -class Issue(BaseModel): - problem: str = Field(description="What is wrong and how to fix it (Hebrew).") - evidence: str = Field(description="The query you ran and what it returned, or the exact part of the SQL / " - "request that disagrees (Hebrew).") - - -class _VerdictFields(BaseModel): - verdict: Literal["pass", "fail"] = Field(description="pass = the answer answers the request; fail = it doesn't.") - issues: list[Issue] = Field(default_factory=list, description="Every problem found (required for fail).") - - @model_validator(mode="after") - def _fail_needs_issues(self): - if self.verdict == "fail" and not self.issues: - raise ValueError("a fail verdict needs at least one issue with evidence") - return self - - -SubmitVerdict = create_model( - VERDICT_TOOL, __base__=_VerdictFields, - __doc__="Submit your review verdict. Call this exactly once, when you are done — it ends your review.", -) - -_SQL_BLOCK = re.compile(r"```sql\s*(.*?)```", re.DOTALL | re.IGNORECASE) - - -def _record(mode: ValidationMode, verdict: Any, **fields: Any) -> dict[str, Any]: - if verdict is None: - return {"id": uuid.uuid4().hex, "mode": mode, "verdict": "error", "issues": [], **fields} - return {"id": uuid.uuid4().hex, "mode": mode, "verdict": verdict.verdict, - "issues": [issue.model_dump() for issue in verdict.issues], **fields} - - -class ReviewRecordMiddleware(AgentMiddleware): - """Inside the on-demand reviewer: record its verdict and which SQL it reviewed (```sql blocks of the brief).""" - - state_schema = DeepAgentRuntimeState - - def after_agent(self, state, runtime) -> dict[str, Any] | None: - messages = state.get("messages") or [] - brief = messages[0].text if messages else "" - sqls = [normalize_sql(block) for block in _SQL_BLOCK.findall(brief)] - reason = None if state.get("structured_response") else "the reviewer ended without a verdict" - return {"semantic_validations": [_record("on_demand", state.get("structured_response"), - sqls=[s for s in sqls if s], reason=reason)]} - - async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: - return self.after_agent(state, runtime) - - -class ReviewTurnMiddleware(AgentMiddleware): - """Start every turn with no reviews (both modes).""" - - state_schema = DeepAgentRuntimeState - - def before_agent(self, state, runtime) -> dict[str, Any] | None: - return {"semantic_validations": None} # None resets (context.merge_reviews) - - async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: - return self.before_agent(state, runtime) - - -def build_validator(model: BaseChatModel, *, on_demand: bool = False): - """The reviewer agent: catalog + date in context, read-only tools, verdict as structured output.""" - prompt = load_prompt("validator").text - agent = create_agent( - model=model, - tools=VALIDATOR_TOOLS, - system_prompt=prompt, - middleware=[ - DeepAgentContextMiddleware(), - CatalogMiddleware(), - PromptRefreshMiddleware("validator", prompt), - AnswerRecoveryMiddleware(), - SubmitReminderMiddleware(VERDICT_TOOL), - *([ReviewRecordMiddleware()] if on_demand else []), - ], - response_format=submission_strategy(SubmitVerdict), - context_schema=DeepAgentContext, - checkpointer=False, # a fresh, unsaved state per review (never the main thread's checkpointer) - name=VALIDATOR_NAME, - ) - return agent.with_config(REVIEW_CONFIG) - - -def validator_subagent(model: BaseChatModel) -> dict[str, Any]: - """The on-demand reviewer as a deepagents CompiledSubAgent (called through `task`).""" - return {"name": VALIDATOR_NAME, "description": ON_DEMAND_DESCRIPTION, "runnable": build_validator(model, on_demand=True)} - - -# ── always: review every submitted answer ──────────────────────────────────── - -def _human_messages(messages: list) -> list[str]: - return [m.text for m in messages if is_user_message(m) and m.text.strip()] - - -def _result_section(record: dict[str, Any] | None) -> str: - if record is None: - return "The analyst did not execute this exact SQL in this turn — run it yourself to see the result." - note = " (truncated by the row ceiling: more rows exist)" if record.get("truncated") else "" - lines = [f"Columns: {record['columns']}", f"Rows returned: {record['row_count']}{note}"] - lines += [str(row) for row in record["rows"]] - return "\n".join(lines) - - -def review_request(messages: list, answer: Any, executed: list[dict[str, Any]]) -> str: - """The reviewer's only input: the user's messages, the answer as the user will see it, and its rows.""" - humans = _human_messages(messages) - earlier = "\n".join(f"- {text}" for text in humans[:-1]) - parts = [] - if earlier: - parts.append(f"## Earlier user messages (context)\n{earlier}") - parts.append(f"## Current user request\n{humans[-1] if humans else ''}") - assumptions = "\n".join(f"- {a}" for a in answer.assumptions) or "(none)" - parts.append( - f"## Answer to review\n```sql\n{answer.sql}\n```\n\n" - f"Explanation shown to the user: {answer.explanation_he}\n\nStated assumptions:\n{assumptions}" - ) - parts.append(f"## Result of this SQL\n{_result_section(match_execution(answer.sql, executed))}") - return "\n\n".join(parts) - - -def feedback_text(issues: list[dict[str, str]]) -> str: - listed = "\n".join(f"{n}. {i['problem']}\n Evidence: {i['evidence']}" for n, i in enumerate(issues, 1)) - return ( - "An independent reviewer checked this answer against the user's request and found problems:\n" - f"{listed}\n\n" - f"Fix the SQL, execute it, and call {TOOL_NAME} again. If you are sure the answer is correct as it is, " - f"call {TOOL_NAME} again with the same SQL and explain why in `validation_response`." - ) - - -class SemanticValidationMiddleware(AgentMiddleware): - """`always` mode: reviews every accepted submit_answer call (see module docstring).""" - - state_schema = DeepAgentRuntimeState - - def __init__(self, model: BaseChatModel, max_rounds: int | None = None) -> None: - super().__init__() - self.model = model - self.max_rounds = max_rounds - self._validator = None - - @property - def validator(self): - if self._validator is None: - self._validator = build_validator(self.model) - return self._validator - - def _pending(self, state) -> tuple[Any, ToolMessage, list[dict[str, Any]]] | None: - """(answer, its tool message, records) when the model just made an accepted SQL submission.""" - submission = last_submission(state.get("messages") or []) - answer = state.get("structured_response") - if submission is None or submission.text != ANSWER_RECEIVED or answer is None: - return None - if getattr(answer, "needs_clarification", None) or not answer.sql: - return None - return answer, submission, list(state.get("semantic_validations") or []) - - def _without_review(self, answer: Any, records: list[dict[str, Any]]) -> dict[str, Any] | None: - """A record that ends the loop without a review (dispute / round limit), else None.""" - sql = normalize_sql(answer.sql) - previous = records[-1] if records else None - if previous and previous["verdict"] == "fail" and previous["sql"] == sql: - return {"id": uuid.uuid4().hex, "mode": "always", "verdict": "disputed", "sql": sql, - "issues": previous["issues"], "response": getattr(answer, "validation_response", None)} - reviews = sum(1 for r in records if r["verdict"] in ("pass", "fail")) - if self.max_rounds is not None and reviews >= self.max_rounds: - return {"id": uuid.uuid4().hex, "mode": "always", "verdict": "skipped", "sql": sql, "issues": [], - "reason": f"review limit reached ({self.max_rounds})"} - return None - - def _update(self, answer, submission, verdict, error: str | None) -> dict[str, Any]: - record = _record("always", verdict, sql=normalize_sql(answer.sql), - reason=None if verdict is not None else error) - if verdict is None: - logger.warning("Semantic validation produced no verdict: %s", error) - if verdict is None or verdict.verdict == "pass": - return {"semantic_validations": [record]} - feedback = ToolMessage(content=feedback_text(record["issues"]), tool_call_id=submission.tool_call_id, - name=submission.name, id=submission.id) # same id: replaces "Answer received." - return {"messages": [feedback], "semantic_validations": [record], "jump_to": "model"} - - def _review_input(self, state, answer) -> dict[str, Any]: - executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] - return {"messages": [HumanMessage(review_request(state.get("messages") or [], answer, executed))]} - - @hook_config(can_jump_to=["model"]) - def after_model(self, state, runtime) -> dict[str, Any] | None: - pending = self._pending(state) - if pending is None: - return None - answer, submission, records = pending - if (record := self._without_review(answer, records)) is not None: - return {"semantic_validations": [record]} - try: - out = self.validator.invoke(self._review_input(state, answer), context=runtime.context) - verdict, error = out.get("structured_response"), "the reviewer ended without a verdict" - except Exception as exc: # a broken review must not lose the answer - verdict, error = None, f"{type(exc).__name__}: {exc}" - return self._update(answer, submission, verdict, error) - - @hook_config(can_jump_to=["model"]) - async def aafter_model(self, state, runtime) -> dict[str, Any] | None: - pending = self._pending(state) - if pending is None: - return None - answer, submission, records = pending - if (record := self._without_review(answer, records)) is not None: - return {"semantic_validations": [record]} - try: - out = await self.validator.ainvoke(self._review_input(state, answer), context=runtime.context) - verdict, error = out.get("structured_response"), "the reviewer ended without a verdict" - except Exception as exc: # a broken review must not lose the answer - verdict, error = None, f"{type(exc).__name__}: {exc}" - return self._update(answer, submission, verdict, error) diff --git a/agent/src/deep_agent/validator/__init__.py b/agent/src/deep_agent/validator/__init__.py new file mode 100644 index 0000000..d25720f --- /dev/null +++ b/agent/src/deep_agent/validator/__init__.py @@ -0,0 +1,32 @@ +""" +Independent semantic review of the Deep Agent's answers. + +The reviewer is a separate agent with a fresh context and read-only diagnostic tools. It gets +the user's request, the SQL, and (usually) the result rows and stated assumptions — never the +main agent's reasoning, so it can't simply agree with it — and returns `submit_verdict` +(pass / fail + issues with evidence). DEEP_AGENT_SEMANTIC_VALIDATION picks how it is used: + +on_demand + A `semantic-validator` subagent the agent calls through `task` when it judges a review + worthwhile (its description says when, and what to send). The verdict comes back to the + agent as JSON; acting on it is up to the agent. Each review is recorded. + +always (default) + Every accepted `submit_answer` call is reviewed before the run can end: + - pass -> the run ends normally; + - fail -> the "Answer received." tool message is replaced by the review's feedback and the + model is sent back. It either fixes the SQL and submits again (reviewed again), or submits + the same SQL with `validation_response` — a dispute, which ends the loop. If it stops + without resubmitting, its last (failed) answer stands, marked "failed". + DEEP_AGENT_VALIDATOR_MAX_ROUNDS optionally limits reviews per turn (default: no limit). + +off + No reviewer. + +Both modes record reviews in `semantic_validations`; the outcome for the final answer goes to +final_result["semantic_validation"] (deep_agent.answer.verification.validation_summary). Semantic checks also +stay mandatory in the main agent's own prompt; the reviewer is an extra, independent check. + +- reviewer.py the reviewer agent: verdict format, read-only tools, its input, review records +- modes.py how it is used: the `always` gate, the `on_demand` subagent, per-turn reset +""" diff --git a/agent/src/deep_agent/validator/modes.py b/agent/src/deep_agent/validator/modes.py new file mode 100644 index 0000000..5fc1f16 --- /dev/null +++ b/agent/src/deep_agent/validator/modes.py @@ -0,0 +1,149 @@ +""" +How the reviewer (deep_agent.validator.reviewer) is used — DEEP_AGENT_SEMANTIC_VALIDATION: + +- always SemanticValidationMiddleware reviews every accepted submit_answer call; on fail the model + gets the feedback and fixes the SQL or disputes it (see the package docstring) +- on_demand validator_subagent(): the reviewer as a `task` subagent the model may call +- (both) ReviewTurnMiddleware starts every turn with no review records +""" + +import logging +import uuid +from typing import Any + +from langchain.agents.middleware import AgentMiddleware, hook_config +from langchain_core.language_models import BaseChatModel +from langchain_core.messages import HumanMessage, ToolMessage + +from deep_agent.answer.schema import ANSWER_RECEIVED, TOOL_NAME, last_submission +from deep_agent.answer.verification import normalize_sql +from deep_agent.context import DeepAgentRuntimeState +from deep_agent.validator.reviewer import VALIDATOR_NAME, build_validator, review_record, review_request + +logger = logging.getLogger(__name__) + +# What the main agent sees about the on-demand subagent (in the `task` tool's list of subagents). +ON_DEMAND_DESCRIPTION = ( + "Independent reviewer: checks whether a SQL answer really answers the user's request, using read-only " + "diagnostic queries, and returns JSON {verdict: pass|fail, issues: [{problem, evidence}]}. It has not seen " + "your work, which is the point. Worth it before submit_answer when the answer involves joins, aggregation " + "or grouping, date ranges, several conditions, an interpretation you had to choose, 0 rows or a surprising " + "number. Skip it for simple lookups you have already verified. In the task description send only: the " + "user's messages verbatim (all of them, for a follow-up), the SQL to review in a ```sql block, its result " + "rows, and your stated assumptions — not your reasoning or your conclusion. On fail, fix the SQL (and " + "review again if the change is substantial), or keep it only if you can show why the issue is wrong." +) + + +class ReviewTurnMiddleware(AgentMiddleware): + """Start every turn with no reviews (both modes).""" + + state_schema = DeepAgentRuntimeState + + def before_agent(self, state, runtime) -> dict[str, Any] | None: + return {"semantic_validations": None} # None resets (context.merge_reviews) + + async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: + return self.before_agent(state, runtime) + + +def validator_subagent(model: BaseChatModel) -> dict[str, Any]: + """The on-demand reviewer as a deepagents CompiledSubAgent (called through `task`).""" + return {"name": VALIDATOR_NAME, "description": ON_DEMAND_DESCRIPTION, "runnable": build_validator(model, on_demand=True)} + + + +def feedback_text(issues: list[dict[str, str]]) -> str: + listed = "\n".join(f"{n}. {i['problem']}\n Evidence: {i['evidence']}" for n, i in enumerate(issues, 1)) + return ( + "An independent reviewer checked this answer against the user's request and found problems:\n" + f"{listed}\n\n" + f"Fix the SQL, execute it, and call {TOOL_NAME} again. If you are sure the answer is correct as it is, " + f"call {TOOL_NAME} again with the same SQL and explain why in `validation_response`." + ) + + +class SemanticValidationMiddleware(AgentMiddleware): + """`always` mode: reviews every accepted submit_answer call (see module docstring).""" + + state_schema = DeepAgentRuntimeState + + def __init__(self, model: BaseChatModel, max_rounds: int | None = None) -> None: + super().__init__() + self.model = model + self.max_rounds = max_rounds + self._validator = None + + @property + def validator(self): + if self._validator is None: + self._validator = build_validator(self.model) + return self._validator + + def _pending(self, state) -> tuple[Any, ToolMessage, list[dict[str, Any]]] | None: + """(answer, its tool message, records) when the model just made an accepted SQL submission.""" + submission = last_submission(state.get("messages") or []) + answer = state.get("structured_response") + if submission is None or submission.text != ANSWER_RECEIVED or answer is None: + return None + if getattr(answer, "needs_clarification", None) or not answer.sql: + return None + return answer, submission, list(state.get("semantic_validations") or []) + + def _without_review(self, answer: Any, records: list[dict[str, Any]]) -> dict[str, Any] | None: + """A record that ends the loop without a review (dispute / round limit), else None.""" + sql = normalize_sql(answer.sql) + previous = records[-1] if records else None + if previous and previous["verdict"] == "fail" and previous["sql"] == sql: + return {"id": uuid.uuid4().hex, "mode": "always", "verdict": "disputed", "sql": sql, + "issues": previous["issues"], "response": getattr(answer, "validation_response", None)} + reviews = sum(1 for r in records if r["verdict"] in ("pass", "fail")) + if self.max_rounds is not None and reviews >= self.max_rounds: + return {"id": uuid.uuid4().hex, "mode": "always", "verdict": "skipped", "sql": sql, "issues": [], + "reason": f"review limit reached ({self.max_rounds})"} + return None + + def _update(self, answer, submission, verdict, error: str | None) -> dict[str, Any]: + record = review_record("always", verdict, sql=normalize_sql(answer.sql), + reason=None if verdict is not None else error) + if verdict is None: + logger.warning("Semantic validation produced no verdict: %s", error) + if verdict is None or verdict.verdict == "pass": + return {"semantic_validations": [record]} + feedback = ToolMessage(content=feedback_text(record["issues"]), tool_call_id=submission.tool_call_id, + name=submission.name, id=submission.id) # same id: replaces "Answer received." + return {"messages": [feedback], "semantic_validations": [record], "jump_to": "model"} + + def _review_input(self, state, answer) -> dict[str, Any]: + executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + return {"messages": [HumanMessage(review_request(state.get("messages") or [], answer, executed))]} + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + pending = self._pending(state) + if pending is None: + return None + answer, submission, records = pending + if (record := self._without_review(answer, records)) is not None: + return {"semantic_validations": [record]} + try: + out = self.validator.invoke(self._review_input(state, answer), context=runtime.context) + verdict, error = out.get("structured_response"), "the reviewer ended without a verdict" + except Exception as exc: # a broken review must not lose the answer + verdict, error = None, f"{type(exc).__name__}: {exc}" + return self._update(answer, submission, verdict, error) + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + pending = self._pending(state) + if pending is None: + return None + answer, submission, records = pending + if (record := self._without_review(answer, records)) is not None: + return {"semantic_validations": [record]} + try: + out = await self.validator.ainvoke(self._review_input(state, answer), context=runtime.context) + verdict, error = out.get("structured_response"), "the reviewer ended without a verdict" + except Exception as exc: # a broken review must not lose the answer + verdict, error = None, f"{type(exc).__name__}: {exc}" + return self._update(answer, submission, verdict, error) diff --git a/agent/src/deep_agent/validator/reviewer.py b/agent/src/deep_agent/validator/reviewer.py new file mode 100644 index 0000000..e73601c --- /dev/null +++ b/agent/src/deep_agent/validator/reviewer.py @@ -0,0 +1,140 @@ +""" +The reviewer agent: a separate agent with a fresh context (the user's messages, the SQL, its rows, +the stated assumptions and the catalog — never the main agent's reasoning), read-only diagnostic +tools, and a `submit_verdict` (pass / fail + issues with evidence). Its prompt is prompts/validator.md. +""" + +import logging +import re +import uuid +from typing import Any, Literal + +from langchain.agents import create_agent +from langchain.agents.middleware import AgentMiddleware +from langchain_core.language_models import BaseChatModel +from pydantic import BaseModel, Field, create_model, model_validator + +from deep_agent.answer.middleware import AnswerRecoveryMiddleware, SubmitReminderMiddleware +from deep_agent.answer.schema import submission_strategy +from deep_agent.answer.verification import match_execution, normalize_sql +from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware, DeepAgentRuntimeState, is_user_message +from deep_agent.middleware.catalog import CatalogMiddleware +from deep_agent.prompts.registry import PromptRefreshMiddleware, load_prompt +from deep_agent.tools import ( + execute_trino_query, + get_column_distinct_values, + get_column_profile, + get_sample_rows, + search_column_values, +) + +logger = logging.getLogger(__name__) + +ValidationMode = Literal["on_demand", "always", "off"] + +VERDICT_TOOL = "submit_verdict" +VALIDATOR_NAME = "semantic-validator" +REVIEW_CONFIG = {"run_name": VALIDATOR_NAME, "tags": [VALIDATOR_NAME]} # the tag marks the reviewer's nested runs +VALIDATOR_TOOLS = [execute_trino_query, get_sample_rows, get_column_distinct_values, search_column_values, + get_column_profile] + +class Issue(BaseModel): + problem: str = Field(description="What is wrong and how to fix it (Hebrew).") + evidence: str = Field(description="The query you ran and what it returned, or the exact part of the SQL / " + "request that disagrees (Hebrew).") + + +class _VerdictFields(BaseModel): + verdict: Literal["pass", "fail"] = Field(description="pass = the answer answers the request; fail = it doesn't.") + issues: list[Issue] = Field(default_factory=list, description="Every problem found (required for fail).") + + @model_validator(mode="after") + def _fail_needs_issues(self): + if self.verdict == "fail" and not self.issues: + raise ValueError("a fail verdict needs at least one issue with evidence") + return self + + +SubmitVerdict = create_model( + VERDICT_TOOL, __base__=_VerdictFields, + __doc__="Submit your review verdict. Call this exactly once, when you are done — it ends your review.", +) + +_SQL_BLOCK = re.compile(r"```sql\s*(.*?)```", re.DOTALL | re.IGNORECASE) + + +def review_record(mode: ValidationMode, verdict: Any, **fields: Any) -> dict[str, Any]: + if verdict is None: + return {"id": uuid.uuid4().hex, "mode": mode, "verdict": "error", "issues": [], **fields} + return {"id": uuid.uuid4().hex, "mode": mode, "verdict": verdict.verdict, + "issues": [issue.model_dump() for issue in verdict.issues], **fields} + + +class ReviewRecordMiddleware(AgentMiddleware): + """Inside the on-demand reviewer: record its verdict and which SQL it reviewed (```sql blocks of the brief).""" + + state_schema = DeepAgentRuntimeState + + def after_agent(self, state, runtime) -> dict[str, Any] | None: + messages = state.get("messages") or [] + brief = messages[0].text if messages else "" + sqls = [normalize_sql(block) for block in _SQL_BLOCK.findall(brief)] + reason = None if state.get("structured_response") else "the reviewer ended without a verdict" + return {"semantic_validations": [review_record("on_demand", state.get("structured_response"), + sqls=[s for s in sqls if s], reason=reason)]} + + async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: + return self.after_agent(state, runtime) + + +def build_validator(model: BaseChatModel, *, on_demand: bool = False): + """The reviewer agent: catalog + date in context, read-only tools, verdict as structured output.""" + prompt = load_prompt("validator").text + agent = create_agent( + model=model, + tools=VALIDATOR_TOOLS, + system_prompt=prompt, + middleware=[ + DeepAgentContextMiddleware(), + CatalogMiddleware(), + PromptRefreshMiddleware("validator", prompt), + AnswerRecoveryMiddleware(), + SubmitReminderMiddleware(VERDICT_TOOL), + *([ReviewRecordMiddleware()] if on_demand else []), + ], + response_format=submission_strategy(SubmitVerdict), + context_schema=DeepAgentContext, + checkpointer=False, # a fresh, unsaved state per review (never the main thread's checkpointer) + name=VALIDATOR_NAME, + ) + return agent.with_config(REVIEW_CONFIG) + + +def _human_messages(messages: list) -> list[str]: + return [m.text for m in messages if is_user_message(m) and m.text.strip()] + + +def _result_section(record: dict[str, Any] | None) -> str: + if record is None: + return "The analyst did not execute this exact SQL in this turn — run it yourself to see the result." + note = " (truncated by the row ceiling: more rows exist)" if record.get("truncated") else "" + lines = [f"Columns: {record['columns']}", f"Rows returned: {record['row_count']}{note}"] + lines += [str(row) for row in record["rows"]] + return "\n".join(lines) + + +def review_request(messages: list, answer: Any, executed: list[dict[str, Any]]) -> str: + """The reviewer's only input: the user's messages, the answer as the user will see it, and its rows.""" + humans = _human_messages(messages) + earlier = "\n".join(f"- {text}" for text in humans[:-1]) + parts = [] + if earlier: + parts.append(f"## Earlier user messages (context)\n{earlier}") + parts.append(f"## Current user request\n{humans[-1] if humans else ''}") + assumptions = "\n".join(f"- {a}" for a in answer.assumptions) or "(none)" + parts.append( + f"## Answer to review\n```sql\n{answer.sql}\n```\n\n" + f"Explanation shown to the user: {answer.explanation_he}\n\nStated assumptions:\n{assumptions}" + ) + parts.append(f"## Result of this SQL\n{_result_section(match_execution(answer.sql, executed))}") + return "\n\n".join(parts) diff --git a/agent/tests/deep_agent/conftest.py b/agent/tests/deep_agent/conftest.py index 89aab62..619c602 100644 --- a/agent/tests/deep_agent/conftest.py +++ b/agent/tests/deep_agent/conftest.py @@ -79,7 +79,7 @@ def fake_catalog(monkeypatch): """ from unittest.mock import AsyncMock, MagicMock - import deep_agent.catalog as catalog_module + import deep_agent.middleware.catalog as catalog_module client = MagicMock(get_catalog_prompt=AsyncMock(return_value=TEST_CATALOG)) monkeypatch.setattr(catalog_module, "get_jeen_metadata_client", lambda: client) diff --git a/agent/tests/deep_agent/test_answer.py b/agent/tests/deep_agent/test_answer.py index 9a70596..5366cbd 100644 --- a/agent/tests/deep_agent/test_answer.py +++ b/agent/tests/deep_agent/test_answer.py @@ -1,13 +1,15 @@ from unittest.mock import patch import pytest +from core.trino import TrinoExecutionResult from langchain_core.messages import AIMessage -from core.trino import TrinoExecutionResult -from deep_agent import answer as answer_module -from deep_agent import tools from deep_agent.agent import create_deep_agent -from deep_agent.answer import SubmitAnswer, answer_schema, normalize_sql, render_markdown, verify_answer +from deep_agent.answer import verification +from deep_agent.answer.render import render_markdown +from deep_agent.answer.schema import SubmitAnswer, answer_schema +from deep_agent.answer.verification import normalize_sql, verify_answer +from deep_agent.tools import sql as sql_tools from tests.deep_agent.conftest import system_text EXECUTED = "SELECT COUNT(DISTINCT flight_id) AS flights FROM \"postgres\".\"public\".\"flights_table\" WHERE launch_country = 'France'" @@ -34,8 +36,8 @@ def policy(messages): async def _run(policy_model, policy, tool_results, reexecution_results=(), clarifications=False): agent = create_deep_agent(model=policy_model(policy), clarifications_enabled=clarifications) - with patch.object(tools, "execute_query_sync", side_effect=list(tool_results)) as t1, \ - patch.object(answer_module, "execute_query_sync", side_effect=list(reexecution_results)) as t2: + with patch.object(sql_tools, "execute_query_sync", side_effect=list(tool_results)) as t1, \ + patch.object(verification, "execute_query_sync", side_effect=list(reexecution_results)) as t2: result = await agent.ainvoke({"messages": [("user", "כמה טיסות המריאו מצרפת")]}, {"configurable": {"thread_id": "a"}}) return result, t1, t2 @@ -145,7 +147,7 @@ def test_clarifications_are_off_by_default(): async def test_clarification_only_mentioned_in_prompt_when_enabled(scripted_model, enabled): model = scripted_model(AIMessage("", tool_calls=[{"name": "submit_answer", "args": {**ANSWER}, "id": "f"}])) agent = create_deep_agent(model=model, clarifications_enabled=enabled) - with patch.object(answer_module, "execute_query_sync", return_value=_trino([[1]])): + with patch.object(verification, "execute_query_sync", return_value=_trino([[1]])): await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": f"c{enabled}"}}) assert ("needs_clarification" in system_text(model.seen[0])) is enabled @@ -169,9 +171,9 @@ def policy(messages): def test_re_execution_without_a_row_ceiling(monkeypatch): - monkeypatch.setattr(answer_module.settings, "DEEP_AGENT_MAX_ROWS", None) + monkeypatch.setattr(verification.settings, "DEEP_AGENT_MAX_ROWS", None) answer = SubmitAnswer(sql="SELECT a FROM t", explanation_he="הסבר", confidence="high") - with patch.object(answer_module, "execute_query_sync", return_value=_trino([[i] for i in range(500)])) as run: + with patch.object(verification, "execute_query_sync", return_value=_trino([[i] for i in range(500)])) as run: final = verify_answer(answer, []) assert run.call_args.args[0] == "SELECT a FROM t" # no LIMIT added assert final["executed"] is True and final["result"]["row_count"] == 500 and final["result"]["truncated"] is False diff --git a/agent/tests/deep_agent/test_catalog_state.py b/agent/tests/deep_agent/test_catalog_state.py index efb47d6..046070d 100644 --- a/agent/tests/deep_agent/test_catalog_state.py +++ b/agent/tests/deep_agent/test_catalog_state.py @@ -7,6 +7,7 @@ from deep_agent import tools from deep_agent.agent import create_deep_agent +from deep_agent.tools import enrichment as enrichment_tools CATALOG = '# Jeen Catalog\n"postgres"."public"."flights_table"\n| launch_country | varchar | categorical |' QUESTION = "כמה טיסות המריאו מצרפת" @@ -37,7 +38,7 @@ def enrichment(fake_catalog): client = MagicMock(get_catalog_prompt=AsyncMock(return_value=CATALOG)) with patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", enrich), \ patch("agent.nodes.refiner.parse_jeen_catalog_tables", parse), \ - patch.object(tools, "get_jeen_metadata_client", return_value=client): + patch.object(enrichment_tools, "get_jeen_metadata_client", return_value=client): fake_catalog.get_catalog_prompt.return_value = CATALOG # what CatalogMiddleware loads for the run yield SimpleNamespace(enrich=enrich, parse=parse, client=client, run_catalog=fake_catalog) diff --git a/agent/tests/deep_agent/test_guidance_lint.py b/agent/tests/deep_agent/test_guidance_lint.py index d78c698..4541b1c 100644 --- a/agent/tests/deep_agent/test_guidance_lint.py +++ b/agent/tests/deep_agent/test_guidance_lint.py @@ -12,7 +12,7 @@ import sqlglot from deep_agent.agent import SYSTEM_PROMPT -from deep_agent.prompt_registry import local_prompt +from deep_agent.prompts.registry import local_prompt from deep_agent.resources import DEFAULT_SKILLS_DIR, EXPECTED_SKILLS from deep_agent.tools import DEEP_AGENT_TOOLS diff --git a/agent/tests/deep_agent/test_latency.py b/agent/tests/deep_agent/test_latency.py index 534bae2..8a38a53 100644 --- a/agent/tests/deep_agent/test_latency.py +++ b/agent/tests/deep_agent/test_latency.py @@ -2,17 +2,20 @@ from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch +import core.trino as core_trino import pytest +from core.trino import TrinoExecutionResult from langchain_core.messages import AIMessage import agent.utils.jeen_metadata_client as jmc -import core.trino as core_trino from agent.config import settings -from agent.utils.jeen_metadata_client import JeenMetadataClient, JeenMetadataError, close_mcp_sessions -from core.trino import TrinoExecutionResult -from deep_agent import tools +from agent.utils.jeen_metadata_client import ( + JeenMetadataClient, + JeenMetadataError, + close_mcp_sessions, +) from deep_agent.agent import create_deep_agent -from deep_agent.tool_filter import EXCLUDED_BUILTIN_TOOLS +from deep_agent.middleware.tool_filter import EXCLUDED_BUILTIN_TOOLS OK = TrinoExecutionResult(success=True, rows=[[7]], columns=["n"], row_count=1, query_id="q") diff --git a/agent/tests/deep_agent/test_observability.py b/agent/tests/deep_agent/test_observability.py index 5c76b8c..2297a9f 100644 --- a/agent/tests/deep_agent/test_observability.py +++ b/agent/tests/deep_agent/test_observability.py @@ -3,14 +3,16 @@ from uuid import UUID import pytest +from core.trino import TrinoExecutionResult from langchain_core.callbacks import BaseCallbackHandler from langchain_core.language_models.fake_chat_models import GenericFakeChatModel from langchain_core.messages import AIMessage, HumanMessage, ToolMessage -from core.trino import TrinoExecutionResult from deep_agent import observability, tools from deep_agent.agent import create_deep_agent from deep_agent.observability import RunMetrics, build_run_config, run_metrics +from deep_agent.tools import metadata as metadata_tools +from deep_agent.tools import sql as sql_tools class RunTreeRecorder(BaseCallbackHandler): @@ -74,8 +76,8 @@ async def fake_enrich(**kwargs): agent = create_deep_agent(model=policy_model(_policy)) config = build_run_config("thread-obs", user_id="u-1", callbacks=[recorder], tracing=False) - with patch.object(tools, "get_jeen_metadata_client", return_value=client), \ - patch.object(tools, "execute_query_sync", return_value=trino), \ + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client), \ + patch.object(sql_tools, "execute_query_sync", return_value=trino), \ patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=({"t": {}}, ["t"])), \ patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", side_effect=fake_enrich): await agent.ainvoke({"messages": [("user", "כמה טיסות")]}, config) @@ -122,16 +124,16 @@ def test_agent_version_prefers_explicit_env(monkeypatch): def test_trino_tools_annotate_the_tool_span(): ok_res = TrinoExecutionResult(success=True, rows=[[1], [2]], columns=["a"], row_count=2, query_id="q-9", execution_time_ms=34) - with patch.object(tools, "execute_query_sync", return_value=ok_res), \ - patch.object(tools, "annotate_current_span") as annotate: + with patch.object(sql_tools, "execute_query_sync", return_value=ok_res), \ + patch.object(sql_tools, "annotate_current_span") as annotate: out = tools.execute_trino_query.invoke({"sql": "SELECT a FROM t", "limit": 1}) annotate.assert_called_once_with({"trino_query_id": "q-9", "execution_time_ms": 34, "row_count": 1, "truncated": True}) assert '"execution_time_ms":34' in out and '"query_id":"q-9"' in out err = TrinoExecutionResult(success=False, error_message="line 1:8: Column 'x' cannot be resolved", error_name="COLUMN_NOT_FOUND", query_id="q-10", execution_time_ms=5) - with patch.object(tools, "execute_query_sync", return_value=err), \ - patch.object(tools, "annotate_current_span") as annotate: + with patch.object(sql_tools, "execute_query_sync", return_value=err), \ + patch.object(sql_tools, "annotate_current_span") as annotate: tools.execute_trino_query.invoke({"sql": "SELECT x FROM t"}) metadata, = annotate.call_args.args assert metadata["error_name"] == "COLUMN_NOT_FOUND" and metadata["trino_query_id"] == "q-10" @@ -181,7 +183,9 @@ async def test_real_langfuse_handler_produces_a_single_trace(policy_model): """End-to-end through the real Langfuse v4 CallbackHandler, exported to memory (no network).""" from langfuse import Langfuse from langfuse.langchain import CallbackHandler - from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter + from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, + ) exporter = InMemorySpanExporter() langfuse = Langfuse(public_key="pk-lf-unit-test", secret_key="sk-lf-unit-test", host="http://127.0.0.1:9", @@ -194,8 +198,8 @@ async def fake_enrich(**kwargs): execution_time_ms=9) agent = create_deep_agent(model=policy_model(_policy)) with patch.object(observability, "_langfuse_handler", return_value=CallbackHandler(public_key="pk-lf-unit-test")), \ - patch.object(tools, "get_jeen_metadata_client", return_value=MagicMock(get_catalog_prompt=AsyncMock(return_value="# c"))), \ - patch.object(tools, "execute_query_sync", return_value=trino), \ + patch.object(metadata_tools, "get_jeen_metadata_client", return_value=MagicMock(get_catalog_prompt=AsyncMock(return_value="# c"))), \ + patch.object(sql_tools, "execute_query_sync", return_value=trino), \ patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=({"t": {}}, ["t"])), \ patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", side_effect=fake_enrich): config = build_run_config("thread-lf", user_id="user-lf", tracing=True) diff --git a/agent/tests/deep_agent/test_prompts_and_catalog.py b/agent/tests/deep_agent/test_prompts_and_catalog.py index ecd05d0..386d37d 100644 --- a/agent/tests/deep_agent/test_prompts_and_catalog.py +++ b/agent/tests/deep_agent/test_prompts_and_catalog.py @@ -2,20 +2,20 @@ import json from types import SimpleNamespace -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import MagicMock, patch import pytest from langchain_core.messages import AIMessage from agent.config import settings -from deep_agent import observability, prompt_registry +from deep_agent import observability from deep_agent.agent import CLARIFICATION_PROMPT, create_deep_agent -from deep_agent.catalog import CatalogLoadError from deep_agent.context import merge_executions -from deep_agent.prompt_registry import PROMPT_KEYS, load_prompt, local_prompt +from deep_agent.middleware.catalog import CatalogLoadError +from deep_agent.prompts import registry as prompt_registry +from deep_agent.prompts.registry import PROMPT_KEYS, load_prompt, local_prompt from tests.deep_agent.conftest import TEST_CATALOG, system_text - # ── deterministic catalog ──────────────────────────────────────────────────── @pytest.mark.asyncio diff --git a/agent/tests/deep_agent/test_runtime_context.py b/agent/tests/deep_agent/test_runtime_context.py index 9f1e0df..d228d2d 100644 --- a/agent/tests/deep_agent/test_runtime_context.py +++ b/agent/tests/deep_agent/test_runtime_context.py @@ -7,9 +7,9 @@ from langchain_core.messages import AIMessage import deep_agent.context as context_module -from deep_agent import tools from deep_agent.agent import create_deep_agent from deep_agent.context import DeepAgentContext, date_line +from deep_agent.tools import metadata as metadata_tools from tests.deep_agent.conftest import system_text CATALOGS = {1: "# catalog for connection 1", 2: "# catalog for connection 2"} @@ -43,7 +43,7 @@ async def test_concurrent_requests_for_different_connections_are_isolated(policy fake_catalog.get_catalog_prompt = _catalog_by_connection() client = _value_client() - with patch.object(tools, "get_jeen_metadata_client", return_value=client): + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): r1, r2 = await asyncio.gather( agent.ainvoke({"messages": [("user", "q1")]}, {"configurable": {"thread_id": "conn-1"}}, context=DeepAgentContext(connection_id=1)), diff --git a/agent/tests/deep_agent/test_service.py b/agent/tests/deep_agent/test_service.py index f8b5978..2ba773c 100644 --- a/agent/tests/deep_agent/test_service.py +++ b/agent/tests/deep_agent/test_service.py @@ -5,12 +5,14 @@ from unittest.mock import AsyncMock, patch import pytest +from core.trino import TrinoExecutionResult from langchain_core.messages import AIMessage -from core.trino import TrinoExecutionResult -from deep_agent import answer, service, tools +from deep_agent import service from deep_agent.agent import create_deep_agent +from deep_agent.answer import verification from deep_agent.service import run_deep_chat, to_response +from deep_agent.tools import sql as sql_tools SQL = "SELECT COUNT(*) AS orders FROM orders WHERE status = 'shipped'" OK = TrinoExecutionResult(success=True, rows=[[466]], columns=["orders"], row_count=1, query_id="q-1") @@ -78,7 +80,7 @@ def test_clarification_maps_to_free_text_hitl(): @pytest.mark.asyncio async def test_clarify_then_resume_on_the_same_thread(policy_model, published): agent = create_deep_agent(model=policy_model(_policy), clarifications_enabled=True) - with patch.object(tools, "execute_query_sync", return_value=OK): + with patch.object(sql_tools, "execute_query_sync", return_value=OK): first = await run_deep_chat(connection_id=89, query="כמה הזמנות נשלחו", thread_id="deep-t1", agent=agent) second = await run_deep_chat(connection_id=89, thread_id="deep-t1", agent=agent, resume_value={"approved": False, "feedback": "שנשלחו"}) @@ -103,7 +105,7 @@ async def test_turn_without_new_answer_does_not_repeat_the_previous_one(scripted AIMessage("still no answer"), # reply to the submit reminder ) agent = create_deep_agent(model=model) - with patch.object(tools, "execute_query_sync", return_value=OK): + with patch.object(sql_tools, "execute_query_sync", return_value=OK): first = await run_deep_chat(connection_id=89, query="q1", thread_id="deep-t2", agent=agent) second = await run_deep_chat(connection_id=89, query="ותודה", thread_id="deep-t2", agent=agent) assert first["verification"] == "matched" @@ -119,8 +121,8 @@ async def test_answer_only_matches_sql_executed_in_its_own_turn(scripted_model, _answer(), ) agent = create_deep_agent(model=model) - with patch.object(tools, "execute_query_sync", return_value=OK), \ - patch.object(answer, "execute_query_sync", return_value=OK) as rerun: + with patch.object(sql_tools, "execute_query_sync", return_value=OK), \ + patch.object(verification, "execute_query_sync", return_value=OK) as rerun: first = await run_deep_chat(connection_id=89, query="q1", thread_id="deep-t3", agent=agent) second = await run_deep_chat(connection_id=89, query="ושוב", thread_id="deep-t3", agent=agent) assert first["verification"] == "matched" @@ -133,7 +135,7 @@ async def test_checkpoints_hold_only_plain_data(scripted_model, published, caplo """The answer object isn't kept in thread state (checkpoints can't restore its class); final_result is.""" agent = create_deep_agent(model=scripted_model( AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), _answer())) - with patch.object(tools, "execute_query_sync", return_value=OK): + with patch.object(sql_tools, "execute_query_sync", return_value=OK): await run_deep_chat(connection_id=89, query="q", thread_id="deep-t5", agent=agent) state = (await agent.aget_state({"configurable": {"thread_id": "deep-t5"}})).values assert state.get("structured_response") is None @@ -154,7 +156,7 @@ def slow_query(*args, **kwargs): return OK # A query already running in a worker thread can't be interrupted; the run stops there. - with patch.object(tools, "execute_query_sync", side_effect=slow_query): + with patch.object(sql_tools, "execute_query_sync", side_effect=slow_query): r = await run_deep_chat(connection_id=89, query="q", thread_id="deep-t4", agent=agent, timeout_s=0.3) assert r["verification"] == "no_answer" and r["executed"] is False and r["is_unanswerable"] is True assert "stopped after 0.3s" in r["summary"] @@ -234,7 +236,7 @@ async def test_reviewer_tools_are_labelled_in_the_stream(scripted_model, publish AIMessage("", tool_calls=[{"name": "submit_verdict", "args": {"verdict": "pass"}, "id": "v1"}]), ) agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) - with patch.object(tools, "execute_query_sync", return_value=OK): + with patch.object(sql_tools, "execute_query_sync", return_value=OK): r = await run_deep_chat(connection_id=89, query="q", thread_id="deep-t6", agent=agent) assert r["execution_path"] == ["deep:execute_trino_query", "deep:review:get_sample_rows"] assert r["semantic_validation"]["verdict"] == "passed" diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py index e7da654..ff5a30f 100644 --- a/agent/tests/deep_agent/test_tool_contracts.py +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -4,25 +4,22 @@ import pytest import tiktoken +from core.trino import TrinoExecutionResult import agent.utils.jeen_metadata_client as jmc from agent.utils.jeen_metadata_client import JeenMetadataClient, JeenMetadataError -from core.trino import TrinoExecutionResult from deep_agent import tools -from deep_agent.tools import DEEP_AGENT_TOOLS, UNREGISTERED_TOOLS +from deep_agent.tools import DEEP_AGENT_TOOLS +from deep_agent.tools import enrichment as enrichment_tools +from deep_agent.tools import location as location_tools +from deep_agent.tools import metadata as metadata_tools +from deep_agent.tools import sql as sql_tools -ALL_TOOLS = [*DEEP_AGENT_TOOLS, *UNREGISTERED_TOOLS] +ALL_TOOLS = DEEP_AGENT_TOOLS -# Minimal valid arguments for every tool (registered and unregistered — both must honour the envelope). +# Minimal valid arguments for every tool (each must honour the envelope). TOOL_ARGS = { - "get_database_tables": {}, - "get_table_columns": {"table_name": "t"}, - "get_table_relationships": {}, - "get_table_profile": {"table_name": "t"}, "get_column_profile": {"table_name": "t", "column_name": "c"}, - "search_metadata": {"query": "q"}, - "search_business_terms": {"query": "q"}, - "search_knowledge_pairs": {"query": "q"}, "search_column_values": {"search_term": "תל אביב"}, "resolve_location_to_wkt": {"location_name": "חיפה"}, "execute_trino_query": {"sql": "SELECT 1"}, @@ -54,10 +51,11 @@ def patched(request): if fail else TrinoExecutionResult(success=True, rows=[[1]], columns=["a"], row_count=1)) enrich = (AsyncMock(side_effect=RuntimeError("llm down")) if fail else AsyncMock(return_value=("SELECT 1 FROM t WHERE a = 'X'", SimpleNamespace(enrichment_details=[]), True))) - with patch.object(tools, "get_jeen_metadata_client", return_value=_client(fail)), \ - patch.object(tools, "execute_query_sync", return_value=trino_res), \ - patch.object(tools, "get_geojson_polygon", return_value=None if fail else {"type": "Polygon"}), \ - patch.object(tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"), \ + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=_client(fail)), \ + patch.object(enrichment_tools, "get_jeen_metadata_client", return_value=_client(fail)), \ + patch.object(sql_tools, "execute_query_sync", return_value=trino_res), \ + patch.object(location_tools, "get_geojson_polygon", return_value=None if fail else {"type": "Polygon"}), \ + patch.object(location_tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"), \ patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=("s", ["t"])), \ patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", enrich): yield fail @@ -95,10 +93,11 @@ async def test_tool_returns_envelope(tool, patched): @pytest.mark.asyncio async def test_metadata_failure_says_data_is_not_empty(): - client = MagicMock(get_tables=AsyncMock(side_effect=JeenMetadataError("auth expired"))) - with patch.object(tools, "get_jeen_metadata_client", return_value=client): - out = json.loads(await tools.get_database_tables.ainvoke({})) + client = MagicMock(get_column_profile=AsyncMock(side_effect=JeenMetadataError("auth expired"))) + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): + out = json.loads(await tools.get_column_profile.ainvoke({"table_name": "t", "column_name": "c"})) assert out["error"]["name"] == "METADATA_ERROR" + assert "auth expired" in out["error"]["message"] assert "does not mean the data is empty" in out["error"]["message"] @@ -125,19 +124,9 @@ async def test_unexpected_payload_is_an_error_not_empty(method): await getattr(client, method)() -@pytest.mark.asyncio -async def test_relationships_tool_surfaces_mcp_error(): - client = MagicMock(get_relationships=AsyncMock(side_effect=JeenMetadataError("auth expired"))) - with patch.object(tools, "get_jeen_metadata_client", return_value=client): - out = json.loads(await tools.get_table_relationships.ainvoke({})) - assert out["ok"] is False - assert out["error"]["name"] == "METADATA_ERROR" - assert "auth expired" in out["error"]["message"] - - async def _search(values): client = MagicMock(search_column_values=AsyncMock(return_value={"values": values})) - with patch.object(tools, "get_jeen_metadata_client", return_value=client): + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): return json.loads(await tools.search_column_values.ainvoke({"search_term": "x"})) @@ -174,15 +163,15 @@ async def test_search_values_says_when_the_limit_was_hit(): @pytest.mark.asyncio async def test_search_values_passes_limit_through_unclamped(): client = MagicMock(search_column_values=AsyncMock(return_value={"values": []})) - with patch.object(tools, "get_jeen_metadata_client", return_value=client): + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): await tools.search_column_values.ainvoke({"search_term": "x", "limit": 500}) assert client.search_column_values.call_args.kwargs["limit"] == 500 @pytest.mark.asyncio async def test_location_returns_the_polygon_once(): - with patch.object(tools, "get_geojson_polygon", return_value={"type": "Polygon"}), \ - patch.object(tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"): + with patch.object(location_tools, "get_geojson_polygon", return_value={"type": "Polygon"}), \ + patch.object(location_tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"): out = json.loads(tools.resolve_location_to_wkt.invoke({"location_name": "חיפה"})) assert out["data"] == {"location": "חיפה", "wkt": "POLYGON((0 0, 1 0, 1 1, 0 0))"} @@ -205,7 +194,7 @@ async def test_search_values_output_is_at_least_40_percent_smaller(): for i in range(10) ]} client = MagicMock(search_column_values=AsyncMock(return_value=res)) - with patch.object(tools, "get_jeen_metadata_client", return_value=client): + with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): new = await tools.search_column_values.ainvoke({"search_term": "תל אביב"}) enc = tiktoken.get_encoding("o200k_base") old_tokens = len(enc.encode(_old_search_column_values_output("תל אביב", res))) diff --git a/agent/tests/deep_agent/test_trino_errors.py b/agent/tests/deep_agent/test_trino_errors.py index e813687..21a7a62 100644 --- a/agent/tests/deep_agent/test_trino_errors.py +++ b/agent/tests/deep_agent/test_trino_errors.py @@ -2,12 +2,14 @@ from pathlib import Path from unittest.mock import MagicMock, patch +import core.trino as core_trino import pytest import trino.exceptions - -import core.trino as core_trino from core.trino import TrinoExecutionResult -from deep_agent import tools, trino_errors + +from deep_agent import tools +from deep_agent.tools import sql as sql_tools +from deep_agent.tools import trino_errors FIXTURES = json.loads((Path(__file__).parent.parent / "fixtures" / "trino_errors.json").read_text(encoding="utf-8")) @@ -59,7 +61,7 @@ def test_execute_tool_returns_trinos_error(): success=False, error_message="line 1:8: Function 'st_geomfromtext' not registered", error_name="FUNCTION_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 8), query_id="q1", ) - with patch.object(tools, "execute_query_sync", return_value=res): + with patch.object(sql_tools, "execute_query_sync", return_value=res): out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT ST_GeomFromText('POINT(1 1)')"})) assert out == { "ok": False, @@ -76,7 +78,7 @@ def test_execute_tool_returns_trinos_error(): def test_execute_tool_reports_exceptions_as_connection_error(): - with patch.object(tools, "execute_query_sync", side_effect=OSError("connection refused")): + with patch.object(sql_tools, "execute_query_sync", side_effect=OSError("connection refused")): out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT 1"})) assert out["error"]["name"] == "CONNECTION_ERROR" assert out["error"]["message"] == "connection refused" @@ -87,7 +89,7 @@ def test_validate_returns_trinos_error(): success=False, error_message="line 1:32: Column 'x' cannot be resolved", error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 32), ) - with patch.object(tools, "execute_query_sync", return_value=res): + with patch.object(sql_tools, "execute_query_sync", return_value=res): out = json.loads(tools.validate_sql.invoke({"sql": "SELECT x FROM t"})) assert out["ok"] is False assert out["error"]["name"] == "COLUMN_NOT_FOUND" @@ -100,7 +102,7 @@ def test_validate_reports_location_against_the_callers_sql(): success=False, error_message="line 1:32: Column 'x' cannot be resolved", error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(1, 32), ) - with patch.object(tools, "execute_query_sync", return_value=res): + with patch.object(sql_tools, "execute_query_sync", return_value=res): out = json.loads(tools.validate_sql.invoke({"sql": "SELECT x FROM t"})) assert out["error"]["location"] == {"line": 1, "column": 8} assert out["error"]["message"] == "line 1:32: Column 'x' cannot be resolved" # Trino's message stays raw @@ -111,6 +113,6 @@ def test_validate_leaves_later_lines_alone(): success=False, error_message="line 3:7: Column 'x' cannot be resolved", error_name="COLUMN_NOT_FOUND", error_type="USER_ERROR", error_location=(3, 7), ) - with patch.object(tools, "execute_query_sync", return_value=res): + with patch.object(sql_tools, "execute_query_sync", return_value=res): out = json.loads(tools.validate_sql.invoke({"sql": "SELECT a\nFROM t\nWHERE x = 1"})) assert out["error"]["location"] == {"line": 3, "column": 7} diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py index a275ee7..aa112d7 100644 --- a/agent/tests/deep_agent/test_trino_tools.py +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -2,9 +2,10 @@ from unittest.mock import patch import pytest - from core.trino import TrinoExecutionResult + from deep_agent import tools +from deep_agent.tools import sql as sql_tools def _ok(n_rows: int) -> TrinoExecutionResult: @@ -15,7 +16,7 @@ def _ok(n_rows: int) -> TrinoExecutionResult: @pytest.fixture def trino(): - with patch.object(tools, "execute_query_sync") as mock: + with patch.object(sql_tools, "execute_query_sync") as mock: yield mock @@ -37,14 +38,14 @@ def test_limit_argument_is_clamped_and_truncation_reported(trino): def test_omitted_limit_uses_the_configured_ceiling(trino, monkeypatch): - monkeypatch.setattr(tools.settings, "DEEP_AGENT_MAX_ROWS", 100) + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_ROWS", 100) trino.return_value = _ok(5) tools.execute_trino_query.invoke({"sql": "SELECT id FROM t"}) assert trino.call_args.args[0] == "SELECT id FROM t LIMIT 101" def test_no_ceiling_runs_sql_as_written_and_returns_every_row(trino, monkeypatch): - monkeypatch.setattr(tools.settings, "DEEP_AGENT_MAX_ROWS", None) + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_ROWS", None) trino.return_value = _ok(5000) out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t;"})) assert trino.call_args.args[0] == "SELECT id FROM t" @@ -53,7 +54,7 @@ def test_no_ceiling_runs_sql_as_written_and_returns_every_row(trino, monkeypatch def test_no_ceiling_still_honours_an_explicit_limit(trino, monkeypatch): - monkeypatch.setattr(tools.settings, "DEEP_AGENT_MAX_ROWS", None) + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_ROWS", None) trino.return_value = _ok(11) out = json.loads(tools.execute_trino_query.invoke({"sql": "SELECT id FROM t", "limit": 10})) assert trino.call_args.args[0] == "SELECT id FROM t LIMIT 11" diff --git a/agent/tests/deep_agent/test_validator.py b/agent/tests/deep_agent/test_validator.py index bf3690b..00381ac 100644 --- a/agent/tests/deep_agent/test_validator.py +++ b/agent/tests/deep_agent/test_validator.py @@ -1,20 +1,23 @@ """Independent semantic review of answers (deep_agent.validator): "always" gate and "on_demand" subagent.""" -from unittest.mock import patch - import itertools -from types import SimpleNamespace from contextlib import contextmanager +from types import SimpleNamespace +from unittest.mock import patch import pytest +from core.trino import TrinoExecutionResult from langchain_core.messages import AIMessage -from core.trino import TrinoExecutionResult -from deep_agent import answer, tools from deep_agent.agent import create_deep_agent -from deep_agent.answer import ANSWER_RECEIVED, answer_schema, render_markdown, validation_summary +from deep_agent.answer import verification +from deep_agent.answer.render import render_markdown +from deep_agent.answer.schema import ANSWER_RECEIVED, answer_schema +from deep_agent.answer.verification import validation_summary from deep_agent.observability import run_metrics -from deep_agent.validator import VALIDATOR_TOOLS, SubmitVerdict, feedback_text +from deep_agent.tools import sql as sql_tools +from deep_agent.validator.modes import feedback_text +from deep_agent.validator.reviewer import VALIDATOR_TOOLS, SubmitVerdict SQL = "SELECT COUNT(*) AS n FROM orders WHERE status = 'shipped'" FIXED = "SELECT COUNT(DISTINCT order_id) AS n FROM orders WHERE status = 'shipped'" @@ -29,8 +32,8 @@ def _trino(*args, **kwargs): @contextmanager def _fake_trino(): """Every execution in the run (agent, reviewer, re-execution) — never the real Trino.""" - with patch.object(tools, "execute_query_sync", side_effect=_trino), \ - patch.object(answer, "execute_query_sync", side_effect=_trino): + with patch.object(sql_tools, "execute_query_sync", side_effect=_trino), \ + patch.object(verification, "execute_query_sync", side_effect=_trino): yield ISSUE = {"problem": "סופרים שורות ולא הזמנות", "evidence": "COUNT(*)=42 אבל COUNT(DISTINCT order_id)=40"} @@ -374,8 +377,7 @@ async def test_no_reminder_after_a_failed_review(scripted_model): def test_reminder_is_not_the_users_words(): from langchain_core.messages import HumanMessage - from deep_agent.answer import current_turn - from deep_agent.context import REMINDER_NAME, user_request + from deep_agent.context import REMINDER_NAME, current_turn, user_request messages = [HumanMessage("the question"), AIMessage("text"), HumanMessage("submit!", name=REMINDER_NAME)] assert current_turn(messages) == messages[1:] From f07e922c366967ddadbe07ee22693166bb9afe3e Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 1 Nov 2026 13:28:29 +0200 Subject: [PATCH 24/37] fix(deep-agent): required SQL, reviewer can't pass a partial answer, simpler time guidance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - answer schema: `sql` must be non-empty (the model must commit to a SQL answer) - reviewer prompt: an assumption may choose between readings of the request but may not drop or replace part of it (Q3 dropped "per 10,000 residents" as an "assumption" and passed) - time guidance: one line — times are Israel time, plain literals, no zones, no hand conversion to UTC (a hand conversion caused a wrong month boundary); the temporal skill's long time-zone section is reduced to the same - Trino rule: decimal literals keep their scale (avg(IF(c, 1.0, 0.0)) returns 0.3, not 0.3008) - hide the built-in `ls` tool: skill paths are already in the prompt Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/answer/schema.py | 1 + .../src/deep_agent/middleware/tool_filter.py | 4 +- agent/src/deep_agent/prompts/system.md | 4 +- agent/src/deep_agent/prompts/validator.md | 2 +- .../skills/temporal-analyst/SKILL.md | 45 ++----------------- agent/tests/deep_agent/test_answer.py | 5 +++ 6 files changed, 14 insertions(+), 47 deletions(-) diff --git a/agent/src/deep_agent/answer/schema.py b/agent/src/deep_agent/answer/schema.py index 0c26faa..9ea18fa 100644 --- a/agent/src/deep_agent/answer/schema.py +++ b/agent/src/deep_agent/answer/schema.py @@ -18,6 +18,7 @@ class _AnswerFields(BaseModel): sql: str = Field( + min_length=1, description="The exact final Trino SQL whose results answer the question — the same query you executed " "successfully with execute_trino_query.", ) diff --git a/agent/src/deep_agent/middleware/tool_filter.py b/agent/src/deep_agent/middleware/tool_filter.py index 7350784..68af107 100644 --- a/agent/src/deep_agent/middleware/tool_filter.py +++ b/agent/src/deep_agent/middleware/tool_filter.py @@ -5,14 +5,14 @@ tokens per call and removes off-task options: - execute: always errors without a sandbox backend - write_file / edit_file: skills and memory are read-only; planning goes through write_todos -- glob / grep: the skills are listed in the prompt with their paths and read with read_file +- glob / grep / ls: the skills are listed in the prompt with their paths and read with read_file """ from collections.abc import Awaitable, Callable from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse -EXCLUDED_BUILTIN_TOOLS = frozenset({"execute", "write_file", "edit_file", "glob", "grep"}) +EXCLUDED_BUILTIN_TOOLS = frozenset({"execute", "write_file", "edit_file", "glob", "grep", "ls"}) class BuiltinToolFilterMiddleware(AgentMiddleware): diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index b77985a..04d624e 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -74,7 +74,7 @@ The user's word is almost never the stored string — the value may be spelled d ### Trino dialect essentials - **Identifiers vs strings**: double quotes for identifiers (`"catalog"."schema"."table"`, `"column"`), single quotes for string literals. Never backticks. `'column_name' = 'val'` compares two strings, not the column. -- **Integer division truncates** (`5 / 2 = 2`): for ratios and percentages use `CAST(a AS double) / NULLIF(b, 0)` or `1.0 * a / NULLIF(b, 0)` — `NULLIF` also prevents division-by-zero errors. +- **Integer division truncates** (`5 / 2 = 2`): for ratios and percentages use `CAST(a AS double) / NULLIF(b, 0)` — `NULLIF` also prevents division-by-zero errors. Decimal literals keep their scale: `avg(IF(cond, 1.0, 0.0))` returns `0.3`, not `0.3008` — use `CAST(count_if(cond) AS double) / count(*)` for a rate. - **Counting**: `COUNT(*)` counts rows, `COUNT(col)` skips NULLs, `COUNT(DISTINCT col)` counts unique non-null values — count entities with `COUNT(DISTINCT id)`. `approx_distinct(x)` is a fast estimate on large tables. - **Idioms**: `count_if(cond)` instead of `SUM(CASE WHEN cond THEN 1 ELSE 0 END)`; `max_by(val, ts)` / `min_by(val, ts)` for the latest/earliest value per entity without a window or self-join. - **NULLs**: `IS NULL` / `IS NOT NULL`, never `= NULL`. `AVG()` ignores NULLs — if NULL means zero, `AVG(COALESCE(col, 0))`; `COALESCE(SUM(...), 0)` when an empty group should be 0. @@ -84,7 +84,7 @@ The user's word is almost never the stored string — the value may be spelled d - **Per-entity ratios**: mind the granularity of numerator vs denominator — "orders per resident" is `COUNT(orders) / SUM(population)`, not `AVG(count_per_row)`. When the denominator comes from another table, aggregate each side in its own CTE, then join and divide. - **Set operations**: prefer `UNION ALL`; `UNION` adds an expensive distributed de-duplication — use it only when de-duplication is required. - **Arrays**: membership `contains(arr, 'v')`; expand with `CROSS JOIN UNNEST(arr) AS t(element)`. -- **Time filters**: a half-open range on the raw column (`col >= start AND col < end`), never a function around the filtered column. Dates the user names are **Israel time** — write `TIMESTAMP '2024-07-01 00:00:00 Asia/Jerusalem'`, not `... UTC` (2–3 hours off at each end). Details in the `temporal-analyst` skill. +- **Time filters**: a half-open range on the raw column (`col >= start AND col < end`), never a function around the filtered column. Times are Israel time and so is the session: write plain literals (`TIMESTAMP '2024-07-01 00:00:00'`, `DATE '2024-07-01'`) — don't add a time zone and don't convert to UTC yourself. - **Coordinates**: `ST_Point(lon, lat)` and WKT are longitude first; `great_circle_distance(lat1, lon1, lat2, lon2)` is latitude first and returns km. Distances and areas on plain geometry are in degrees — wrap in `to_spherical_geography(...)` for metres. Details in the `spatial-analyst` skill. - **When several logic paths seem plausible** (INNER vs LEFT JOIN, different grouping), run 2–3 variants with `LIMIT 10` and compare before choosing — don't guess. diff --git a/agent/src/deep_agent/prompts/validator.md b/agent/src/deep_agent/prompts/validator.md index b0c179a..ff77ac4 100644 --- a/agent/src/deep_agent/prompts/validator.md +++ b/agent/src/deep_agent/prompts/validator.md @@ -35,7 +35,7 @@ The connection's complete catalog is included at the end of this prompt ("Databa ## Verdict Call `submit_verdict` exactly once, when you are done: -- `verdict: "pass"` — the answer correctly answers the request (a reasonable interpretation stated in the assumptions is fine). +- `verdict: "pass"` — the answer correctly answers the request. An assumption may choose between reasonable readings of the request; it may not drop or replace part of what was asked. An answer that leaves out or substitutes part of the request fails, even when its assumptions say so. - `verdict: "fail"` — at least one concrete problem would make the user's answer wrong or misleading. For each problem give `problem` (what is wrong and how to fix it) and `evidence` (the query you ran and what it returned, or the exact part of the SQL / request that disagrees). Write them in Hebrew. Fail only for problems you can show. Style, formatting, performance, or a different-but-equivalent way to write the SQL are not problems. If you are unsure whether something is wrong, check it with a query; if you still cannot show it, it is not a problem. diff --git a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md index 54e8064..92bd3d2 100644 --- a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md +++ b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md @@ -115,52 +115,13 @@ ORDER BY 1 `year(d)`, `month(d)`, `day_of_week(d)` and `extract(year FROM d)` are fine in `SELECT` and `GROUP BY` — just not in `WHERE` on a native column you are filtering. -Group by the **Israel** day / hour, not the UTC one — convert before truncating: - -```sql -SELECT date_trunc('day', event_at AT TIME ZONE 'Asia/Jerusalem') AS day_il, count(*) AS events -FROM "catalog"."schema"."events" -GROUP BY 1 -ORDER BY 1 -``` - --- ## Time zones -**Dates and periods the user names are Israel time.** "On July 1st", "the first two weeks of July", "yesterday" start -and end at midnight in Israel, not in UTC. Write the boundaries as Israel-time literals and let Trino convert them: - -```sql -SELECT count(*) AS events -FROM "catalog"."schema"."events" -WHERE event_at >= TIMESTAMP '2024-07-01 00:00:00 Asia/Jerusalem' - AND event_at < TIMESTAMP '2024-07-15 00:00:00 Asia/Jerusalem' -``` - -`TIMESTAMP '... UTC'` boundaries are off by 2–3 hours at each end and change the counts. The session time zone is -Israel, so `current_date`, `current_timestamp` and `date_trunc('day', current_timestamp)` are already Israel time. - -If a table is partitioned by a UTC date string (e.g. `dt`), an Israel day spans two UTC partitions — widen the -partition filter by a day and keep the exact Israel-time filter on the timestamp column: - -```sql -SELECT count(*) AS events -FROM "catalog"."schema"."events" -WHERE dt >= '2024-04-30' AND dt <= '2024-05-01' - AND event_at >= TIMESTAMP '2024-05-01 00:00:00 Asia/Jerusalem' - AND event_at < TIMESTAMP '2024-05-02 00:00:00 Asia/Jerusalem' -``` - -A naive `timestamp` has no zone. To treat it as UTC and show Israel local time: - -```sql -SELECT with_timezone(event_at, 'UTC') AT TIME ZONE 'Asia/Jerusalem' AS event_at_israel -FROM "catalog"."schema"."events" -``` - -For a value that already carries a zone (`timestamp with time zone`, e.g. from `from_iso8601_timestamp('...Z')`), -`col AT TIME ZONE 'Asia/Jerusalem'` is enough. Israel is UTC+2 in winter and UTC+3 in summer (DST). +Times are Israel time, and so is the session time zone: plain literals (`TIMESTAMP '2024-07-01 00:00:00'`), +`current_date` and `current_timestamp` are already Israel time. Don't add zones to literals and don't convert to UTC +by hand. (Only if a column is a naive `timestamp` documented as UTC: `with_timezone(col, 'UTC')` before comparing.) --- diff --git a/agent/tests/deep_agent/test_answer.py b/agent/tests/deep_agent/test_answer.py index 5366cbd..25b4a2e 100644 --- a/agent/tests/deep_agent/test_answer.py +++ b/agent/tests/deep_agent/test_answer.py @@ -220,3 +220,8 @@ async def test_text_that_is_not_a_valid_answer_is_not_recovered(policy_model, te async def test_a_real_tool_call_is_not_marked_recovered(policy_model): result, _, _ = await _run(policy_model, _policy(ANSWER), [_trino([[466]])]) assert result["final_result"]["recovered_from_text"] is False + + +def test_sql_is_required(): + with pytest.raises(ValueError): + SubmitAnswer(sql="", explanation_he="x", confidence="low") From 0e4d129906da1e37aa8c74c5bae405ed31f3fad0 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 1 Nov 2026 16:12:31 +0200 Subject: [PATCH 25/37] =?UTF-8?q?feat(deep-agent):=20review=20before=20sub?= =?UTF-8?q?mit=20=E2=80=94=20submit=5Fanswer=20requires=20a=20run=20and=20?= =?UTF-8?q?a=20validator=20pass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - order: run the SQL (execute_trino_query) → have it reviewed (`semantic-validator` subagent, through `task`) → submit_answer. The reviewer no longer runs inside the submit step. - SubmitApprovalMiddleware: submit_answer only looks up two records for the exact SQL — it ran successfully this turn (a sample counts), and the validator passed it (or the agent disputes a fail with `validation_response`). Otherwise it is refused with the reason and the agent continues; a SQL changed after its review needs a new one. - reviewer independence: its input is built by our code from facts — the user's own messages (copied into state `user_messages` each turn; subagents don't get the conversation), the SQL, its recorded rows, the assumptions as claims to check, catalog and date. The rest of the brief is discarded; no reasoning, confidence or earlier verdicts. - final rows: the approved run's rows; a sample is re-run unchanged for all rows; SQL that never ran is never executed (status not_executed if the invariant ever breaks). - DEEP_AGENT_SEMANTIC_VALIDATION: always (default, validator pass required) | on_demand (offered, submit only needs a run) | off. DEEP_AGENT_STRICT_SUBMIT: no recovery / reminder — a model that doesn't call submit_answer ends without an answer. Optional DEEP_AGENT_VALIDATOR_MAX_ROUNDS. - review summary reports the review of the final SQL; README and docstrings updated. Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 40 +- agent/src/agent/config.py | 11 +- agent/src/deep_agent/agent.py | 31 +- agent/src/deep_agent/answer/middleware.py | 98 ++++- agent/src/deep_agent/answer/schema.py | 6 +- agent/src/deep_agent/answer/verification.py | 54 ++- agent/src/deep_agent/context.py | 3 + agent/src/deep_agent/prompts/system.md | 2 - agent/src/deep_agent/prompts/validator.md | 4 +- agent/src/deep_agent/service.py | 2 +- agent/src/deep_agent/validator/__init__.py | 39 +- agent/src/deep_agent/validator/modes.py | 178 +++----- agent/src/deep_agent/validator/reviewer.py | 157 ++++--- agent/tests/deep_agent/test_answer.py | 40 +- agent/tests/deep_agent/test_service.py | 26 +- agent/tests/deep_agent/test_validator.py | 427 +++++++++----------- 16 files changed, 568 insertions(+), 550 deletions(-) diff --git a/agent/README.md b/agent/README.md index 3ca63d1..6a73758 100644 --- a/agent/README.md +++ b/agent/README.md @@ -49,7 +49,7 @@ observability.py Langfuse run config and scores resources.py skills wiring (read-only /skills/) tools/ what the model can call: sql, metadata, enrichment, location (+ envelope, trino_errors) answer/ the final answer: schema, verification (did the SQL run), middleware, render -validator/ independent semantic review: reviewer (the agent), modes (always / on_demand) +validator/ independent semantic review before submit: reviewer (the agent), modes (wiring) middleware/ cross-cutting: catalog in every model call, built-in tool filter prompts/ system.md, validator.md + registry.py (Langfuse / packaged) skills/ temporal-analyst, spatial-analyst @@ -70,21 +70,29 @@ Run logs are opt-in and git-ignored (`agent/runs/`, `agent/*.jsonl`, `agent/*.cs ### Semantic validation (deep agent) -An independent reviewer (`src/deep_agent/validator/`) checks whether a SQL answer really answers the user's request: -a separate agent with a fresh context (the user's messages, the SQL, its rows, the stated assumptions and the catalog — -not the main agent's reasoning), read-only diagnostic tools, and a verdict of pass, or fail with issues and evidence. -Its prompt is `prompts/validator.md` (`deep-agent/validator` in Langfuse). `DEEP_AGENT_SEMANTIC_VALIDATION` picks how it is used: - -| Mode | | -|---|---| -| `on_demand` | a `semantic-validator` subagent the agent calls through `task` when it judges a review worthwhile; the verdict comes back to the agent, which decides what to do | -| `always` (default) | every submitted answer is reviewed before the run ends; on fail the agent fixes the SQL (reviewed again) or resubmits it with a justification (`validation_response`, recorded as disputed). `DEEP_AGENT_VALIDATOR_MAX_ROUNDS` optionally limits reviews per turn (default none) | -| `off` | no reviewer | - -The outcome for the final answer is the response's `semantic_validation`: `verdict` (`passed` / `failed` / `disputed` / -`not_validated`), `rounds`, `issues`, `reviewed_final_sql` (a review of an earlier SQL doesn't count for the final one). -Langfuse gets `validation_rounds` and, when the final SQL was reviewed, `semantic_validation_passed` — compare the modes -on accuracy and cost, then keep one. +A SQL answer needs two approvals **before** it is submitted: + +1. **It ran:** the SQL executed successfully with `execute_trino_query` in this turn (a limited sample counts; the + full rows are fetched once more for the user). +2. **It answers the question:** the `semantic-validator` subagent (`src/deep_agent/validator/`) passed it. The agent + calls it through `task` with the SQL and its assumptions; the reviewer's input is built by our code from facts — the + user's own messages, the SQL, its recorded rows, the assumptions as claims to check, the catalog and the date — + never from the agent's reasoning. It has read-only diagnostic tools and returns pass, or fail with issues and + evidence (prompt: `prompts/validator.md`, `deep-agent/validator` in Langfuse). + +`submit_answer` only checks those records. Without them it is refused with the reason and the agent continues; a SQL +changed after its review needs a new one. After a fail the agent fixes the SQL, or disputes: it submits the same SQL +with `validation_response` (recorded as disputed and shown to the user). + +| Setting | Default | | +|---|---|---| +| `DEEP_AGENT_SEMANTIC_VALIDATION` | `always` | `on_demand` = the reviewer is offered and the agent decides whether to call it; `off` = no reviewer. In both, only approval 1 is required | +| `DEEP_AGENT_VALIDATOR_MAX_ROUNDS` | none | optional: after this many reviews in a turn, an unreviewed SQL is accepted as `not_validated` | +| `DEEP_AGENT_STRICT_SUBMIT` | `false` | `true` = no recovery of answers written as text and no reminder: a model that doesn't call `submit_answer` ends without an answer | + +The response's `semantic_validation` reports the review of the **final** SQL: `verdict` (`passed` / `disputed` / +`not_validated`), `rounds`, `issues`, `reviewed_final_sql`. Langfuse gets `validation_rounds` and, when the final SQL +was reviewed, `semantic_validation_passed`. ### SQL safety (deep agent) diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 0ed390f..5819c11 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -52,11 +52,14 @@ class AgentSettings(BaseSettings): DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows DEEP_AGENT_TRACING_ENABLED: bool = True # Langfuse callbacks, span metadata and run scores DEEP_AGENT_CLARIFICATIONS_ENABLED: bool = False # let the model ask a clarifying question instead of answering - # Independent semantic review of answers (see deep_agent/validator/): - # always = every submitted answer is reviewed before the run ends; - # on_demand = a `semantic-validator` subagent the agent calls when it judges a review worthwhile; off = no reviewer. + # Independent semantic review (see deep_agent/validator/), by the `semantic-validator` subagent: + # always = submit_answer is accepted only for SQL it passed (or that the agent disputes); + # on_demand = the agent may call it, submit only requires that the SQL ran; off = no reviewer. DEEP_AGENT_SEMANTIC_VALIDATION: Literal["always", "on_demand", "off"] = "always" - DEEP_AGENT_VALIDATOR_MAX_ROUNDS: int | None = Field(default=None, gt=0) # "always" only: reviews per turn; "none" = no limit + DEEP_AGENT_VALIDATOR_MAX_ROUNDS: int | None = Field(default=None, gt=0) # reviews per turn before submit stops requiring one; "none" = no limit + # Strict submit: no recovery of answers written as text and no "submit now" reminder — a model that doesn't + # call submit_answer (or the reviewer submit_verdict) simply ends without an answer. + DEEP_AGENT_STRICT_SUBMIT: bool = False JEEN_METADATA_CACHE_TTL_S: float = Field(default=300.0, ge=0) # metadata read cache (0 disables) JEEN_METADATA_REUSE_SESSION: bool = True # keep one MCP session open per event loop # Prompts (see deep_agent/prompts/registry.py). Off until the prompts are finalised and synced to Langfuse. diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 71c6cc2..0529b01 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -14,7 +14,7 @@ from agent.config import settings from agent.llm import get_llm -from deep_agent.answer.middleware import AnswerRecoveryMiddleware, AnswerVerificationMiddleware, SubmitReminderMiddleware +from deep_agent.answer.middleware import AnswerVerificationMiddleware, SubmitApprovalMiddleware, submit_fallback from deep_agent.answer.schema import TOOL_NAME, answer_schema, submission_strategy from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware from deep_agent.middleware.catalog import CatalogMiddleware @@ -22,7 +22,7 @@ from deep_agent.prompts.registry import PromptRefreshMiddleware, load_prompt, local_prompt from deep_agent.resources import build_resources from deep_agent.tools import DEEP_AGENT_TOOLS -from deep_agent.validator.modes import ReviewTurnMiddleware, SemanticValidationMiddleware, validator_subagent +from deep_agent.validator.modes import ON_DEMAND_PROMPT, REVIEW_PROMPT, ReviewTurnMiddleware, validator_subagent from deep_agent.validator.reviewer import ValidationMode # Packaged system prompt (the Langfuse-managed version, when enabled, is loaded per agent build and refreshed per call). @@ -61,7 +61,7 @@ def create_deep_agent( model: Chat model override (tests); defaults to the configured LLM. clarifications_enabled: Override DEEP_AGENT_CLARIFICATIONS_ENABLED (tests). checkpointer: Thread persistence (e.g. AsyncPostgresSaver); defaults to an in-memory saver. - semantic_validation: Override DEEP_AGENT_SEMANTIC_VALIDATION: on_demand | always | off (tests). + semantic_validation: Override DEEP_AGENT_SEMANTIC_VALIDATION: always | on_demand | off (tests). validator_model: Model for the independent reviewer; defaults to the agent's model. """ if clarifications_enabled is None: @@ -70,17 +70,14 @@ def create_deep_agent( llm = model or get_llm() memory = checkpointer or MemorySaver() resources = build_resources() - suffix = CLARIFICATION_PROMPT if clarifications_enabled else "" + review_required = mode == "always" # submit needs a validator pass + has_reviewer = mode in ("always", "on_demand") # the semantic-validator subagent is available + review_prompt = {"always": REVIEW_PROMPT, "on_demand": ON_DEMAND_PROMPT}.get(mode, "") + suffix = (CLARIFICATION_PROMPT if clarifications_enabled else "") + review_prompt system_prompt = load_prompt("system").text + suffix - reviewer = validator_model or llm subagents = [_general_purpose_subagent()] - review_middleware = [] - if mode == "on_demand": - subagents.append(validator_subagent(reviewer)) - review_middleware = [ReviewTurnMiddleware()] - elif mode == "always": - review_middleware = [ReviewTurnMiddleware(), - SemanticValidationMiddleware(reviewer, settings.DEEP_AGENT_VALIDATOR_MAX_ROUNDS)] + if has_reviewer: + subagents.append(validator_subagent(validator_model or llm, mode)) agent = create_harness_agent( model=llm, @@ -91,13 +88,13 @@ def create_deep_agent( DeepAgentContextMiddleware(), CatalogMiddleware(), PromptRefreshMiddleware("system", system_prompt, suffix=suffix), - AnswerRecoveryMiddleware(), - SubmitReminderMiddleware(TOOL_NAME), - AnswerVerificationMiddleware(), - *review_middleware, + *submit_fallback(TOOL_NAME), + AnswerVerificationMiddleware(has_reviewer), + *([ReviewTurnMiddleware()] if has_reviewer else []), + SubmitApprovalMiddleware(review_required, settings.DEEP_AGENT_VALIDATOR_MAX_ROUNDS), BuiltinToolFilterMiddleware(), ], - response_format=submission_strategy(answer_schema(clarifications_enabled, mode == "always")), + response_format=submission_strategy(answer_schema(clarifications_enabled, review_required)), context_schema=DeepAgentContext, checkpointer=memory, backend=resources.backend, diff --git a/agent/src/deep_agent/answer/middleware.py b/agent/src/deep_agent/answer/middleware.py index 3c2d237..c80d089 100644 --- a/agent/src/deep_agent/answer/middleware.py +++ b/agent/src/deep_agent/answer/middleware.py @@ -3,6 +3,10 @@ - AnswerRecoveryMiddleware answer written as JSON text instead of a submit_answer call -> the real call - SubmitReminderMiddleware the model stopped without its submit call -> one reminder per turn + (these two are the submit fallback; off with DEEP_AGENT_STRICT_SUBMIT) +- SubmitApprovalMiddleware submit_answer is accepted only for SQL that ran this turn and that the + semantic-validator passed (or that the agent disputes); it checks records, it + doesn't judge - AnswerVerificationMiddleware each turn starts clean; invalid submissions are retried; at the end of the turn the answer is verified (deep_agent.answer.verification) -> final_result """ @@ -19,8 +23,9 @@ from langchain_core.messages import AIMessage, HumanMessage, ToolMessage from pydantic import BaseModel +from agent.config import settings from deep_agent.answer.schema import ANSWER_RECEIVED, last_submission -from deep_agent.answer.verification import validation_summary, verify_answer +from deep_agent.answer.verification import match_execution, normalize_sql, validation_summary, verify_answer from deep_agent.context import REMINDER_NAME, current_turn logger = logging.getLogger(__name__) @@ -122,6 +127,86 @@ async def aafter_model(self, state, runtime) -> dict[str, Any] | None: return self.after_model(state, runtime) +def submit_fallback(tool_name: str) -> list[AgentMiddleware]: + """Recovery + reminder for a model that doesn't call its submit tool — none with DEEP_AGENT_STRICT_SUBMIT.""" + if settings.DEEP_AGENT_STRICT_SUBMIT: + return [] + return [AnswerRecoveryMiddleware(), SubmitReminderMiddleware(tool_name)] + + +NOT_RUN = ("Not submitted: this SQL has not run successfully in this turn. Run it with execute_trino_query, check " + "its rows, have the semantic-validator review it, then submit it.") +NOT_REVIEWED = ("Not submitted: the semantic-validator has not reviewed this exact SQL (a SQL that passed review " + "and was then changed counts as not reviewed; formatting differences don't matter). Submit exactly the " + "SQL that passed, or send this one to the semantic-validator (task) — the SQL in a ```sql block and " + "your assumptions as '- ' lines — and submit after a pass.") + + +def _failed_text(issues: list[dict[str, str]]) -> str: + listed = "\n".join(f"{n}. {i['problem']}\n Evidence: {i['evidence']}" for n, i in enumerate(issues, 1)) + return ("Not submitted: the semantic-validator failed this SQL:\n" f"{listed}\n\n" + "Fix it (run it, have it reviewed, submit), or — if you are sure it is right — submit the same SQL " + "with `validation_response` explaining why.") + + +class SubmitApprovalMiddleware(AgentMiddleware): + """Accept submit_answer only when the SQL has both approvals — recorded before the submit. + + 1. ran: the SQL matches a successful execute_trino_query in this turn (a sample counts) + 2. reviewed (when review is required): the latest semantic-validator verdict for this SQL is a pass — + or a fail and the agent gives `validation_response` (a dispute, recorded and shown to the user). + If DEEP_AGENT_VALIDATOR_MAX_ROUNDS reviews already ran this turn, the SQL is accepted as not validated. + + It only looks the records up; the judging happened before (the execution, the reviewer). A refused + submission's tool message says why and the model is sent back. + """ + + def __init__(self, require_review: bool, max_rounds: int | None = None) -> None: + super().__init__() + self.require_review = require_review + self.max_rounds = max_rounds + + @staticmethod + def _refuse(submission: ToolMessage, reason: str) -> dict[str, Any]: + refusal = ToolMessage(content=reason, tool_call_id=submission.tool_call_id, name=submission.name, + id=submission.id) # same id: replaces "Answer received." + return {"messages": [refusal], "structured_response": None, "jump_to": "model"} + + @hook_config(can_jump_to=["model"]) + def after_model(self, state, runtime) -> dict[str, Any] | None: + submission = last_submission(state.get("messages") or []) + answer = state.get("structured_response") + if submission is None or submission.text != ANSWER_RECEIVED or answer is None: + return None + if getattr(answer, "needs_clarification", None) or not answer.sql: + return None + executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + if match_execution(answer.sql, executed) is None: + return self._refuse(submission, NOT_RUN) + if not self.require_review: + return None + sql = normalize_sql(answer.sql) + records = list(state.get("semantic_validations") or []) + reviews = [r for r in records if r.get("sql") == sql and r["verdict"] in ("pass", "fail")] + if reviews and reviews[-1]["verdict"] == "pass": + return None + if reviews: # failed + if getattr(answer, "validation_response", None): + return {"semantic_validations": [{"id": uuid.uuid4().hex, "verdict": "disputed", "sql": sql, + "issues": reviews[-1]["issues"], + "response": answer.validation_response}]} + return self._refuse(submission, _failed_text(reviews[-1]["issues"])) + done = sum(1 for r in records if r["verdict"] in ("pass", "fail")) + if self.max_rounds is not None and done >= self.max_rounds: + return {"semantic_validations": [{"id": uuid.uuid4().hex, "verdict": "skipped", "sql": sql, "issues": [], + "reason": f"review limit reached ({self.max_rounds})"}]} + return self._refuse(submission, NOT_REVIEWED) + + @hook_config(can_jump_to=["model"]) + async def aafter_model(self, state, runtime) -> dict[str, Any] | None: + return self.after_model(state, runtime) + + class AnswerVerificationMiddleware(AgentMiddleware): """Bind each turn's structured answer to SQL executed in that turn and its real rows. @@ -129,14 +214,20 @@ class AnswerVerificationMiddleware(AgentMiddleware): again on a turn that ends without a new one) and marks where this turn's executions start, so an answer can only match SQL that ran in its own turn. - after_model sends the model back after a rejected submit_answer call (arguments that fail the + after_model sends the model back after an invalid submit_answer call (arguments that fail the schema). LangChain would retry on its own only while `structured_response` has never been set in the thread; from the first reset on, it ends the run instead. after_agent keeps the answer only as plain data in final_result and drops the pydantic object: checkpoints can't restore the dynamically built `submit_answer` class. + + review_required: whether final_result gets a review summary (with review off it is None). """ + def __init__(self, review_required: bool = False) -> None: + super().__init__() + self.review_required = review_required + @hook_config(can_jump_to=["model"]) def after_model(self, state, runtime) -> dict[str, Any] | None: submission = last_submission(state.get("messages") or []) @@ -160,7 +251,8 @@ def after_agent(self, state, runtime) -> dict[str, Any] | None: final["recovered_from_text"] = any( (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in current_turn(state.get("messages") or []) ) - final["semantic_validation"] = validation_summary(state.get("semantic_validations"), final.get("sql")) + records = state.get("semantic_validations") or [] if self.review_required else None + final["semantic_validation"] = validation_summary(records, final.get("sql")) return {"final_result": final, "structured_response": None} async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: diff --git a/agent/src/deep_agent/answer/schema.py b/agent/src/deep_agent/answer/schema.py index 9ea18fa..a6542db 100644 --- a/agent/src/deep_agent/answer/schema.py +++ b/agent/src/deep_agent/answer/schema.py @@ -51,8 +51,8 @@ class _AnswerFields(BaseModel): _VALIDATION_RESPONSE = (str | None, Field( default=None, - description="Only when an independent review rejected your previous answer and you submit the same SQL again: " - "why that SQL is correct despite the review (Hebrew).", + description="Only when the semantic-validator failed this SQL and you submit it anyway: why it is correct " + "despite the review (Hebrew).", )) @@ -73,7 +73,7 @@ def answer_schema( ) -> type[SubmitAnswer]: """The final-answer schema; without clarifications the model must always commit to a SQL answer. - With semantic validation "always", it also has `validation_response` (to stand by a rejected answer). + With semantic validation "always", it also has `validation_response` (to dispute a failed review). """ if clarifications_enabled is None: clarifications_enabled = settings.DEEP_AGENT_CLARIFICATIONS_ENABLED diff --git a/agent/src/deep_agent/answer/verification.py b/agent/src/deep_agent/answer/verification.py index 67f27d1..300966e 100644 --- a/agent/src/deep_agent/answer/verification.py +++ b/agent/src/deep_agent/answer/verification.py @@ -7,10 +7,12 @@ to be semantically correct. - "matched": answer.sql equals (sqlglot-normalised) a query that executed successfully in - this run -> the result rows are that execution's rows -- "re_executed": no match, or the match was only a smaller sample than the configured row - ceiling -> answer.sql is run once through the read-only guard; rows come from that run -- "rejected" / "re_execution_failed": the answer's SQL is forbidden or fails -> not executed + this turn -> the result rows are that execution's rows +- "re_executed": it matched only a sample (a smaller limit than the configured row ceiling) -> the same, + already approved SQL is run once more to show all its rows +- "re_execution_failed": that full-rows run failed -> not executed +- "not_executed": the SQL never ran in this turn (SubmitApprovalMiddleware refuses such a submission, + so this only marks a broken invariant) - "clarification": the model asked a clarifying question instead of answering (only possible when DEEP_AGENT_CLARIFICATIONS_ENABLED is on) @@ -28,7 +30,8 @@ from core.trino import execute_query_sync from deep_agent.answer.schema import SubmitAnswer -VerificationStatus = Literal["matched", "re_executed", "rejected", "re_execution_failed", "clarification", "no_answer"] +VerificationStatus = Literal["matched", "re_executed", "rejected", "re_execution_failed", "not_executed", "clarification", + "no_answer"] def normalize_sql(sql: str | None) -> str | None: @@ -111,10 +114,13 @@ def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any] return {**base, "status": "clarification", "executed": False, "sql": None, "result": None} record = match_execution(answer.sql, executed) - if record is not None and not _is_sample(record): + if record is None: + return {**base, "status": "not_executed", "executed": False, "sql": clean_sql(answer.sql), "result": None, + "error": "the submitted SQL did not run in this turn"} + if not _is_sample(record): return {**base, "status": "matched", "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} - status, record, error = _re_execute(answer.sql) + status, record, error = _re_execute(answer.sql) # the approved SQL ran only as a sample: fetch all its rows if record is None: return {**base, "status": status, "executed": False, "sql": clean_sql(answer.sql), "result": None, "error": error} return {**base, "status": status, "executed": True, "sql": record["submitted_sql"], "result": _result_view(record)} @@ -123,32 +129,22 @@ def verify_answer(answer: Any, executed: list[dict[str, Any]]) -> dict[str, Any] _VERDICTS = {"pass": "passed", "fail": "failed", "disputed": "disputed"} -def _covers(record: dict[str, Any], final_sql: str | None) -> bool | None: - """Did this review look at the final SQL? None when it can't be told (an on-demand brief without a ```sql block).""" - target = normalize_sql(final_sql) - if "sql" in record: - return record["sql"] == target - return (target in record["sqls"]) if record.get("sqls") else None - - def validation_summary(records: list[dict[str, Any]] | None, final_sql: str | None = None) -> dict[str, Any] | None: - """The review outcome of the final answer, from this turn's review records (None = reviewer off). + """The review outcome of the final answer, from this turn's review records (None = review off). - verdict: passed | failed | disputed (the agent resubmitted a rejected SQL with a justification) | - not_validated (no review, a review of a different SQL than the final one, round limit, or the review failed). - reviewed_final_sql: whether the last review covered the final SQL (None = can't be told). + verdict: the latest record for the final SQL — passed | disputed (the agent submitted a failed SQL with a + justification) | failed | not_validated (no review of the final SQL, review limit, or the review errored). + rounds: reviews this turn (any SQL). """ if records is None: return None rounds = sum(1 for r in records if r["verdict"] in ("pass", "fail")) summary = {"verdict": "not_validated", "rounds": rounds, "issues": [], "response": None, "reason": None, - "reviewed_final_sql": None} - if not records: - return {**summary, "reason": "no review"} - last = records[-1] - covers = _covers(last, final_sql) - summary.update(issues=last.get("issues") or [], response=last.get("response"), reviewed_final_sql=covers, - reason=last.get("reason")) - if covers is False: - return {**summary, "issues": [], "reason": "the final SQL changed after the last review"} - return {**summary, "verdict": _VERDICTS.get(last["verdict"], "not_validated")} + "reviewed_final_sql": False} + target = normalize_sql(final_sql) + relevant = [r for r in records if target is not None and r.get("sql") == target] + if not relevant: + return {**summary, "reason": "no review of the final SQL"} + last = relevant[-1] + return {**summary, "verdict": _VERDICTS.get(last["verdict"], "not_validated"), "issues": last.get("issues") or [], + "response": last.get("response"), "reason": last.get("reason"), "reviewed_final_sql": True} diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index d910f9a..6c57367 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -80,6 +80,9 @@ class DeepAgentRuntimeState(AgentState): final_result: NotRequired[Annotated[dict[str, Any], latest]] # verified answer + rows (see deep_agent.answer.verification) turn_execution_start: NotRequired[Annotated[int, latest]] # index into executed_queries where the current turn began semantic_validations: NotRequired[Annotated[list[dict[str, Any]], merge_reviews]] # this turn's reviews (deep_agent.validator) + # The user's messages in this thread, oldest first, copied at the start of each turn. Subagents don't receive the + # conversation (deepagents leaves `messages` out of their state), so the reviewer reads the real request from here. + user_messages: NotRequired[Annotated[list[str], latest]] # Name of the one-time "submit now" message (deep_agent.answer.middleware.SubmitReminderMiddleware): not the user's words. diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index 04d624e..10a277d 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -165,8 +165,6 @@ After a successful execution, validate before answering: If any check fails or you're unsure, run a targeted diagnostic query. Do not guess. -**Independent review** — if a `semantic-validator` subagent is available, ask it to review the answer (`task`) before `submit_answer` whenever the answer involves a join, aggregation or grouping, several conditions, an interpretation you had to choose, 0 rows or a surprising number. It has not seen your work, so it catches mistakes you can't see in your own reasoning — confidence is not a reason to skip it. Skip it only for simple lookups whose values you have already verified. - --- ## Skills diff --git a/agent/src/deep_agent/prompts/validator.md b/agent/src/deep_agent/prompts/validator.md index ff77ac4..47a69f1 100644 --- a/agent/src/deep_agent/prompts/validator.md +++ b/agent/src/deep_agent/prompts/validator.md @@ -1,4 +1,4 @@ -You are an independent reviewer of Text-to-SQL answers. An analyst translated a user's request into Trino SQL and wants it checked before showing it to the user. You did not write this SQL and you do not see the analyst's reasoning — you get the user's request, the SQL, and usually its result rows, the explanation and the assumptions the analyst made. Your job: decide whether this SQL actually answers what the user asked, on this database. If the result rows are missing, run the SQL yourself. +You are an independent reviewer of Text-to-SQL answers. An analyst translated a user's request into Trino SQL and must have it approved before submitting it. You did not write this SQL and you do not see the analyst's reasoning. You get the user's own messages, the SQL, its result rows, and the analyst's interpretation choices — those are claims to check, not facts. Your job: decide whether this SQL actually answers what the user asked, on this database. If the result rows are missing, run the SQL yourself. The connection's complete catalog is included at the end of this prompt ("Database Catalog"). @@ -30,7 +30,7 @@ The connection's complete catalog is included at the end of this prompt ("Databa - **Joins that drop entities**: an `INNER JOIN` removes entities with no related rows, which is wrong for "per entity" results that should show zero. **Judge — don't solve.** Your job is to decide whether this SQL answers the request, not to write the correct SQL. Stop investigating as soon as you can show a concrete problem with evidence; point briefly at the direction of a fix, but don't search for the full solution. Keep your checks proportionate to the risk in the SQL: a simple lookup needs little, a multi-join aggregation more. -4. **Check the explanation** the user will see: it must describe what the SQL does and what the result means, without claiming anything the result does not show. +4. **Check the interpretation choices**: each must be a reasonable reading of the request and true of the data — check the ones the answer depends on. ## Verdict diff --git a/agent/src/deep_agent/service.py b/agent/src/deep_agent/service.py index 4dbcef3..9d44ed8 100644 --- a/agent/src/deep_agent/service.py +++ b/agent/src/deep_agent/service.py @@ -42,7 +42,7 @@ _agent_lock: asyncio.Lock | None = None _pg_pool = None -UNANSWERED = {"no_answer", "rejected", "re_execution_failed"} +UNANSWERED = {"no_answer", "rejected", "re_execution_failed", "not_executed"} async def build_checkpointer(): diff --git a/agent/src/deep_agent/validator/__init__.py b/agent/src/deep_agent/validator/__init__.py index d25720f..61f84b2 100644 --- a/agent/src/deep_agent/validator/__init__.py +++ b/agent/src/deep_agent/validator/__init__.py @@ -1,32 +1,17 @@ """ -Independent semantic review of the Deep Agent's answers. +Independent semantic review of the Deep Agent's SQL — before it is submitted. -The reviewer is a separate agent with a fresh context and read-only diagnostic tools. It gets -the user's request, the SQL, and (usually) the result rows and stated assumptions — never the -main agent's reasoning, so it can't simply agree with it — and returns `submit_verdict` -(pass / fail + issues with evidence). DEEP_AGENT_SEMANTIC_VALIDATION picks how it is used: +The order is: run the SQL (execute_trino_query) → have it reviewed (the `semantic-validator` subagent, +through `task`) → submit it (submit_answer). The reviewer is a separate agent with a fresh context and +read-only diagnostic tools; its input is built by our code from facts — the user's own messages, the +SQL, its recorded rows, the agent's assumptions (as claims to check), the catalog and the date — never +from the agent's reasoning. It returns pass, or fail with issues and evidence; on fail the agent goes +back to work, or disputes (submits the same SQL with `validation_response`, shown to the user). -on_demand - A `semantic-validator` subagent the agent calls through `task` when it judges a review - worthwhile (its description says when, and what to send). The verdict comes back to the - agent as JSON; acting on it is up to the agent. Each review is recorded. +DEEP_AGENT_SEMANTIC_VALIDATION: `always` (default) makes submit_answer accept only SQL the reviewer passed +(or that the agent disputes); `on_demand` offers the reviewer and lets the agent decide; `off` drops it. submit_answer itself only checks the records +(deep_agent.answer.middleware.SubmitApprovalMiddleware) — the judging happens before it. -always (default) - Every accepted `submit_answer` call is reviewed before the run can end: - - pass -> the run ends normally; - - fail -> the "Answer received." tool message is replaced by the review's feedback and the - model is sent back. It either fixes the SQL and submits again (reviewed again), or submits - the same SQL with `validation_response` — a dispute, which ends the loop. If it stops - without resubmitting, its last (failed) answer stands, marked "failed". - DEEP_AGENT_VALIDATOR_MAX_ROUNDS optionally limits reviews per turn (default: no limit). - -off - No reviewer. - -Both modes record reviews in `semantic_validations`; the outcome for the final answer goes to -final_result["semantic_validation"] (deep_agent.answer.verification.validation_summary). Semantic checks also -stay mandatory in the main agent's own prompt; the reviewer is an extra, independent check. - -- reviewer.py the reviewer agent: verdict format, read-only tools, its input, review records -- modes.py how it is used: the `always` gate, the `on_demand` subagent, per-turn reset +- reviewer.py the reviewer agent: verdict format, read-only tools, its facts-only input, verdict records +- modes.py the wiring: the subagent, the "before you submit" prompt, the per-turn reset """ diff --git a/agent/src/deep_agent/validator/modes.py b/agent/src/deep_agent/validator/modes.py index 5fc1f16..6038685 100644 --- a/agent/src/deep_agent/validator/modes.py +++ b/agent/src/deep_agent/validator/modes.py @@ -1,149 +1,69 @@ """ -How the reviewer (deep_agent.validator.reviewer) is used — DEEP_AGENT_SEMANTIC_VALIDATION: +How the reviewer (deep_agent.validator.reviewer) is wired into the agent — DEEP_AGENT_SEMANTIC_VALIDATION: -- always SemanticValidationMiddleware reviews every accepted submit_answer call; on fail the model - gets the feedback and fixes the SQL or disputes it (see the package docstring) -- on_demand validator_subagent(): the reviewer as a `task` subagent the model may call -- (both) ReviewTurnMiddleware starts every turn with no review records +- always the `semantic-validator` subagent is available through `task`, and submit_answer is accepted + only for SQL it passed (or that the agent disputes) — see SubmitApprovalMiddleware + (deep_agent.answer.middleware). REVIEW_PROMPT tells the agent the order of steps. +- on_demand the subagent is available and the agent decides whether to call it (ON_DEMAND_PROMPT); + submit_answer only requires that the SQL ran. +- off no reviewer; submit_answer still requires that the SQL ran. + +ReviewTurnMiddleware starts every turn with no review records and copies the user's messages into +state for the reviewer (subagents don't receive the conversation). """ -import logging -import uuid from typing import Any -from langchain.agents.middleware import AgentMiddleware, hook_config +from langchain.agents.middleware import AgentMiddleware from langchain_core.language_models import BaseChatModel -from langchain_core.messages import HumanMessage, ToolMessage - -from deep_agent.answer.schema import ANSWER_RECEIVED, TOOL_NAME, last_submission -from deep_agent.answer.verification import normalize_sql -from deep_agent.context import DeepAgentRuntimeState -from deep_agent.validator.reviewer import VALIDATOR_NAME, build_validator, review_record, review_request - -logger = logging.getLogger(__name__) - -# What the main agent sees about the on-demand subagent (in the `task` tool's list of subagents). -ON_DEMAND_DESCRIPTION = ( - "Independent reviewer: checks whether a SQL answer really answers the user's request, using read-only " - "diagnostic queries, and returns JSON {verdict: pass|fail, issues: [{problem, evidence}]}. It has not seen " - "your work, which is the point. Worth it before submit_answer when the answer involves joins, aggregation " - "or grouping, date ranges, several conditions, an interpretation you had to choose, 0 rows or a surprising " - "number. Skip it for simple lookups you have already verified. In the task description send only: the " - "user's messages verbatim (all of them, for a follow-up), the SQL to review in a ```sql block, its result " - "rows, and your stated assumptions — not your reasoning or your conclusion. On fail, fix the SQL (and " - "review again if the change is substantial), or keep it only if you can show why the issue is wrong." + +from deep_agent.context import DeepAgentRuntimeState, is_user_message +from deep_agent.validator.reviewer import VALIDATOR_NAME, build_validator + +# What the main agent sees about the subagent (in the `task` tool's list of subagents). +_HOW_TO_SEND = ( + "It checks whether a SQL query really answers the user's request, with read-only diagnostic queries, and " + "returns JSON {verdict: pass|fail, issues: [{problem, evidence}]}. Send exactly two things in the description: " + "the SQL in a ```sql block, and your interpretation choices as a list of lines starting with '- '. Nothing else " + "is read: the reviewer gets the user's messages and this SQL's result rows itself." ) +VALIDATOR_DESCRIPTION = { + "always": "Independent reviewer — required before submit_answer. " + _HOW_TO_SEND, + "on_demand": ("Independent reviewer — worth it before submit_answer when the answer involves a join, aggregation " + "or grouping, several conditions, an interpretation you had to choose, 0 rows or a surprising " + "number. " + _HOW_TO_SEND), +} + +# Appended to the main system prompt when review is required. +REVIEW_PROMPT = """ +## Before you submit (required) + +1. The final SQL must have run successfully with `execute_trino_query` in this turn — check its rows. +2. Ask the `semantic-validator` to review it: `task` with subagent_type `semantic-validator`, the SQL in a ```sql block and your assumptions as `- ` lines. +3. Pass → call `submit_answer` with exactly that SQL (any change needs a new review). Fail → fix the SQL and repeat 1–2. If you are sure the reviewer is wrong, you may submit the same SQL with `validation_response` explaining why. + +`submit_answer` is refused for SQL that hasn't run, or that the reviewer hasn't passed. +""" + +# Appended to the main system prompt when review is on demand. +ON_DEMAND_PROMPT = """ +An independent reviewer is available: `task` with subagent_type `semantic-validator` (its description says when it is worth calling and what to send). `submit_answer` is refused for SQL that hasn't run successfully in this turn. +""" class ReviewTurnMiddleware(AgentMiddleware): - """Start every turn with no reviews (both modes).""" + """Start every turn with no review records, and give the reviewer the user's messages.""" state_schema = DeepAgentRuntimeState def before_agent(self, state, runtime) -> dict[str, Any] | None: - return {"semantic_validations": None} # None resets (context.merge_reviews) + user_messages = [m.text for m in state.get("messages") or [] if is_user_message(m) and m.text.strip()] + return {"semantic_validations": None, "user_messages": user_messages} # None resets (context.merge_reviews) async def abefore_agent(self, state, runtime) -> dict[str, Any] | None: return self.before_agent(state, runtime) -def validator_subagent(model: BaseChatModel) -> dict[str, Any]: - """The on-demand reviewer as a deepagents CompiledSubAgent (called through `task`).""" - return {"name": VALIDATOR_NAME, "description": ON_DEMAND_DESCRIPTION, "runnable": build_validator(model, on_demand=True)} - - - -def feedback_text(issues: list[dict[str, str]]) -> str: - listed = "\n".join(f"{n}. {i['problem']}\n Evidence: {i['evidence']}" for n, i in enumerate(issues, 1)) - return ( - "An independent reviewer checked this answer against the user's request and found problems:\n" - f"{listed}\n\n" - f"Fix the SQL, execute it, and call {TOOL_NAME} again. If you are sure the answer is correct as it is, " - f"call {TOOL_NAME} again with the same SQL and explain why in `validation_response`." - ) - - -class SemanticValidationMiddleware(AgentMiddleware): - """`always` mode: reviews every accepted submit_answer call (see module docstring).""" - - state_schema = DeepAgentRuntimeState - - def __init__(self, model: BaseChatModel, max_rounds: int | None = None) -> None: - super().__init__() - self.model = model - self.max_rounds = max_rounds - self._validator = None - - @property - def validator(self): - if self._validator is None: - self._validator = build_validator(self.model) - return self._validator - - def _pending(self, state) -> tuple[Any, ToolMessage, list[dict[str, Any]]] | None: - """(answer, its tool message, records) when the model just made an accepted SQL submission.""" - submission = last_submission(state.get("messages") or []) - answer = state.get("structured_response") - if submission is None or submission.text != ANSWER_RECEIVED or answer is None: - return None - if getattr(answer, "needs_clarification", None) or not answer.sql: - return None - return answer, submission, list(state.get("semantic_validations") or []) - - def _without_review(self, answer: Any, records: list[dict[str, Any]]) -> dict[str, Any] | None: - """A record that ends the loop without a review (dispute / round limit), else None.""" - sql = normalize_sql(answer.sql) - previous = records[-1] if records else None - if previous and previous["verdict"] == "fail" and previous["sql"] == sql: - return {"id": uuid.uuid4().hex, "mode": "always", "verdict": "disputed", "sql": sql, - "issues": previous["issues"], "response": getattr(answer, "validation_response", None)} - reviews = sum(1 for r in records if r["verdict"] in ("pass", "fail")) - if self.max_rounds is not None and reviews >= self.max_rounds: - return {"id": uuid.uuid4().hex, "mode": "always", "verdict": "skipped", "sql": sql, "issues": [], - "reason": f"review limit reached ({self.max_rounds})"} - return None - - def _update(self, answer, submission, verdict, error: str | None) -> dict[str, Any]: - record = review_record("always", verdict, sql=normalize_sql(answer.sql), - reason=None if verdict is not None else error) - if verdict is None: - logger.warning("Semantic validation produced no verdict: %s", error) - if verdict is None or verdict.verdict == "pass": - return {"semantic_validations": [record]} - feedback = ToolMessage(content=feedback_text(record["issues"]), tool_call_id=submission.tool_call_id, - name=submission.name, id=submission.id) # same id: replaces "Answer received." - return {"messages": [feedback], "semantic_validations": [record], "jump_to": "model"} - - def _review_input(self, state, answer) -> dict[str, Any]: - executed = (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] - return {"messages": [HumanMessage(review_request(state.get("messages") or [], answer, executed))]} - - @hook_config(can_jump_to=["model"]) - def after_model(self, state, runtime) -> dict[str, Any] | None: - pending = self._pending(state) - if pending is None: - return None - answer, submission, records = pending - if (record := self._without_review(answer, records)) is not None: - return {"semantic_validations": [record]} - try: - out = self.validator.invoke(self._review_input(state, answer), context=runtime.context) - verdict, error = out.get("structured_response"), "the reviewer ended without a verdict" - except Exception as exc: # a broken review must not lose the answer - verdict, error = None, f"{type(exc).__name__}: {exc}" - return self._update(answer, submission, verdict, error) - - @hook_config(can_jump_to=["model"]) - async def aafter_model(self, state, runtime) -> dict[str, Any] | None: - pending = self._pending(state) - if pending is None: - return None - answer, submission, records = pending - if (record := self._without_review(answer, records)) is not None: - return {"semantic_validations": [record]} - try: - out = await self.validator.ainvoke(self._review_input(state, answer), context=runtime.context) - verdict, error = out.get("structured_response"), "the reviewer ended without a verdict" - except Exception as exc: # a broken review must not lose the answer - verdict, error = None, f"{type(exc).__name__}: {exc}" - return self._update(answer, submission, verdict, error) +def validator_subagent(model: BaseChatModel, mode: str = "always") -> dict[str, Any]: + """The reviewer as a deepagents CompiledSubAgent (called through `task`).""" + return {"name": VALIDATOR_NAME, "description": VALIDATOR_DESCRIPTION[mode], "runnable": build_validator(model)} diff --git a/agent/src/deep_agent/validator/reviewer.py b/agent/src/deep_agent/validator/reviewer.py index e73601c..d93236e 100644 --- a/agent/src/deep_agent/validator/reviewer.py +++ b/agent/src/deep_agent/validator/reviewer.py @@ -1,23 +1,38 @@ """ -The reviewer agent: a separate agent with a fresh context (the user's messages, the SQL, its rows, -the stated assumptions and the catalog — never the main agent's reasoning), read-only diagnostic -tools, and a `submit_verdict` (pass / fail + issues with evidence). Its prompt is prompts/validator.md. +The reviewer agent (the `semantic-validator` subagent): a separate agent with a fresh context, read-only +diagnostic tools and a `submit_verdict` (pass / fail + issues with evidence). Its prompt is +prompts/validator.md. + +Independence: the agent that asks for the review writes a brief, but the reviewer never reads it as +such. ReviewInputMiddleware replaces the brief with an input our code builds from facts: + +- the user's messages, from the thread (state `user_messages`) — never from the brief +- the SQL to review and the agent's assumptions — the only two things taken from the brief + (a ```sql block and a "- " list); any other text in the brief is discarded +- that SQL's result rows, from the recorded execution (state `executed_queries`) — never from the brief +- plus, like every model call: today's date and the connection's catalog + +Not given: the agent's reasoning, notes, other attempts, confidence, the user-facing explanation, +or the reviewer's own earlier verdicts. ReviewRecordMiddleware records the verdict for the reviewed +SQL in `semantic_validations`, which submit_answer checks (deep_agent.answer.middleware). """ import logging import re import uuid +from collections.abc import Awaitable, Callable from typing import Any, Literal from langchain.agents import create_agent -from langchain.agents.middleware import AgentMiddleware +from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse from langchain_core.language_models import BaseChatModel +from langchain_core.messages import HumanMessage from pydantic import BaseModel, Field, create_model, model_validator -from deep_agent.answer.middleware import AnswerRecoveryMiddleware, SubmitReminderMiddleware +from deep_agent.answer.middleware import submit_fallback from deep_agent.answer.schema import submission_strategy from deep_agent.answer.verification import match_execution, normalize_sql -from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware, DeepAgentRuntimeState, is_user_message +from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware, DeepAgentRuntimeState from deep_agent.middleware.catalog import CatalogMiddleware from deep_agent.prompts.registry import PromptRefreshMiddleware, load_prompt from deep_agent.tools import ( @@ -30,7 +45,7 @@ logger = logging.getLogger(__name__) -ValidationMode = Literal["on_demand", "always", "off"] +ValidationMode = Literal["always", "on_demand", "off"] VERDICT_TOOL = "submit_verdict" VALIDATOR_NAME = "semantic-validator" @@ -38,6 +53,7 @@ VALIDATOR_TOOLS = [execute_trino_query, get_sample_rows, get_column_distinct_values, search_column_values, get_column_profile] + class Issue(BaseModel): problem: str = Field(description="What is wrong and how to fix it (Hebrew).") evidence: str = Field(description="The query you ran and what it returned, or the exact part of the SQL / " @@ -45,7 +61,7 @@ class Issue(BaseModel): class _VerdictFields(BaseModel): - verdict: Literal["pass", "fail"] = Field(description="pass = the answer answers the request; fail = it doesn't.") + verdict: Literal["pass", "fail"] = Field(description="pass = the SQL answers the request; fail = it doesn't.") issues: list[Issue] = Field(default_factory=list, description="Every problem found (required for fail).") @model_validator(mode="after") @@ -61,46 +77,113 @@ def _fail_needs_issues(self): ) _SQL_BLOCK = re.compile(r"```sql\s*(.*?)```", re.DOTALL | re.IGNORECASE) +_BULLET = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s+(.+?)\s*$") + + +def parse_brief(brief: str) -> tuple[str | None, list[str]]: + """The two things taken from the agent's brief: the SQL (first ```sql block) and its assumptions (bullets).""" + blocks = _SQL_BLOCK.findall(brief or "") + sql = blocks[0].strip() if blocks else None + outside = _SQL_BLOCK.sub("", brief or "") + assumptions = [m.group(1) for line in outside.splitlines() if (m := _BULLET.match(line))] + return sql or None, assumptions + + +def _result_section(record: dict[str, Any] | None) -> str: + if record is None: + return "This SQL has not run successfully in this turn — run it yourself to see the result." + if record.get("truncated"): + note = " (only part of the result: more rows exist)" + else: + note = "" + lines = [f"Columns: {record['columns']}", f"Rows returned: {record['row_count']}{note}"] + lines += [str(row) for row in record["rows"]] + return "\n".join(lines) -def review_record(mode: ValidationMode, verdict: Any, **fields: Any) -> dict[str, Any]: +def review_request(user_messages: list[str], sql: str | None, assumptions: list[str], + executed: list[dict[str, Any]]) -> str: + """The reviewer's input, built from facts: the user's own messages, the SQL, its assumptions, its real rows.""" + parts = [] + if user_messages[:-1]: + parts.append("## Earlier user messages (context)\n" + "\n".join(f"- {text}" for text in user_messages[:-1])) + parts.append(f"## Current user request\n{user_messages[-1] if user_messages else ''}") + if sql is None: + parts.append("## SQL to review\n(none was provided — fail the review with the issue " + "\"no SQL was sent for review\")") + return "\n\n".join(parts) + parts.append(f"## SQL to review\n```sql\n{sql}\n```") + listed = "\n".join(f"- {a}" for a in assumptions) or "(none stated)" + parts.append("## The analyst's interpretation choices — claims to check, not facts\n" + listed) + parts.append(f"## Result of this SQL\n{_result_section(match_execution(sql, executed))}") + return "\n\n".join(parts) + + +def _turn_executions(state: dict) -> list[dict[str, Any]]: + return (state.get("executed_queries") or [])[state.get("turn_execution_start") or 0:] + + +class ReviewInputMiddleware(AgentMiddleware): + """Inside the reviewer: replace the agent's brief with the input built from facts (module docstring).""" + + state_schema = DeepAgentRuntimeState + + def _with_review_input(self, request: ModelRequest) -> ModelRequest: + messages = list(request.messages) + if not messages or not isinstance(messages[0], HumanMessage): + return request + state = request.state or {} + sql, assumptions = parse_brief(messages[0].text) + text = review_request(list(state.get("user_messages") or []), sql, assumptions, _turn_executions(state)) + messages[0] = HumanMessage(text, id=messages[0].id) + return request.override(messages=messages) + + def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: + return handler(self._with_review_input(request)) + + async def awrap_model_call( + self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] + ) -> ModelResponse: + return await handler(self._with_review_input(request)) + + +def review_record(verdict: Any, **fields: Any) -> dict[str, Any]: if verdict is None: - return {"id": uuid.uuid4().hex, "mode": mode, "verdict": "error", "issues": [], **fields} - return {"id": uuid.uuid4().hex, "mode": mode, "verdict": verdict.verdict, + return {"id": uuid.uuid4().hex, "verdict": "error", "issues": [], **fields} + return {"id": uuid.uuid4().hex, "verdict": verdict.verdict, "issues": [issue.model_dump() for issue in verdict.issues], **fields} class ReviewRecordMiddleware(AgentMiddleware): - """Inside the on-demand reviewer: record its verdict and which SQL it reviewed (```sql blocks of the brief).""" + """Inside the reviewer: record its verdict for the SQL it reviewed (state `semantic_validations`).""" state_schema = DeepAgentRuntimeState def after_agent(self, state, runtime) -> dict[str, Any] | None: messages = state.get("messages") or [] - brief = messages[0].text if messages else "" - sqls = [normalize_sql(block) for block in _SQL_BLOCK.findall(brief)] - reason = None if state.get("structured_response") else "the reviewer ended without a verdict" - return {"semantic_validations": [review_record("on_demand", state.get("structured_response"), - sqls=[s for s in sqls if s], reason=reason)]} + sql, _ = parse_brief(messages[0].text if messages else "") + verdict = state.get("structured_response") + reason = None if verdict else "the reviewer ended without a verdict" + return {"semantic_validations": [review_record(verdict, sql=normalize_sql(sql), reason=reason)]} async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: return self.after_agent(state, runtime) -def build_validator(model: BaseChatModel, *, on_demand: bool = False): - """The reviewer agent: catalog + date in context, read-only tools, verdict as structured output.""" +def build_validator(model: BaseChatModel): + """The reviewer agent: facts-only input, catalog + date in context, read-only tools, verdict via submit_verdict.""" prompt = load_prompt("validator").text agent = create_agent( model=model, tools=VALIDATOR_TOOLS, system_prompt=prompt, middleware=[ + ReviewInputMiddleware(), # first: the date is then added to the built input, not to the brief DeepAgentContextMiddleware(), CatalogMiddleware(), PromptRefreshMiddleware("validator", prompt), - AnswerRecoveryMiddleware(), - SubmitReminderMiddleware(VERDICT_TOOL), - *([ReviewRecordMiddleware()] if on_demand else []), + *submit_fallback(VERDICT_TOOL), + ReviewRecordMiddleware(), ], response_format=submission_strategy(SubmitVerdict), context_schema=DeepAgentContext, @@ -108,33 +191,3 @@ def build_validator(model: BaseChatModel, *, on_demand: bool = False): name=VALIDATOR_NAME, ) return agent.with_config(REVIEW_CONFIG) - - -def _human_messages(messages: list) -> list[str]: - return [m.text for m in messages if is_user_message(m) and m.text.strip()] - - -def _result_section(record: dict[str, Any] | None) -> str: - if record is None: - return "The analyst did not execute this exact SQL in this turn — run it yourself to see the result." - note = " (truncated by the row ceiling: more rows exist)" if record.get("truncated") else "" - lines = [f"Columns: {record['columns']}", f"Rows returned: {record['row_count']}{note}"] - lines += [str(row) for row in record["rows"]] - return "\n".join(lines) - - -def review_request(messages: list, answer: Any, executed: list[dict[str, Any]]) -> str: - """The reviewer's only input: the user's messages, the answer as the user will see it, and its rows.""" - humans = _human_messages(messages) - earlier = "\n".join(f"- {text}" for text in humans[:-1]) - parts = [] - if earlier: - parts.append(f"## Earlier user messages (context)\n{earlier}") - parts.append(f"## Current user request\n{humans[-1] if humans else ''}") - assumptions = "\n".join(f"- {a}" for a in answer.assumptions) or "(none)" - parts.append( - f"## Answer to review\n```sql\n{answer.sql}\n```\n\n" - f"Explanation shown to the user: {answer.explanation_he}\n\nStated assumptions:\n{assumptions}" - ) - parts.append(f"## Result of this SQL\n{_result_section(match_execution(answer.sql, executed))}") - return "\n\n".join(parts) diff --git a/agent/tests/deep_agent/test_answer.py b/agent/tests/deep_agent/test_answer.py index 25b4a2e..20ccf56 100644 --- a/agent/tests/deep_agent/test_answer.py +++ b/agent/tests/deep_agent/test_answer.py @@ -56,27 +56,15 @@ async def test_answer_is_bound_to_the_executed_query(policy_model): assert len(result["executed_queries"]) == 1 -@pytest.mark.asyncio -async def test_unexecuted_answer_sql_is_re_executed(policy_model): - other = {**ANSWER, "sql": "SELECT COUNT(*) AS flights FROM \"postgres\".\"public\".\"flights_table\""} - result, _, reexec = await _run(policy_model, _policy(other), [_trino([[466]])], [_trino([[1000]])]) - - final = result["final_result"] - assert final["status"] == "re_executed" and final["executed"] is True - assert final["result"]["rows"] == [[1000]] - reexec.assert_called_once() - assert reexec.call_args.args[0].endswith("LIMIT 101") # re-execution goes through the guard - - -@pytest.mark.asyncio -async def test_forbidden_answer_sql_is_rejected(policy_model): - bad = {**ANSWER, "sql": "DELETE FROM \"postgres\".\"public\".\"flights_table\""} - result, _, reexec = await _run(policy_model, _policy(bad), [_trino([[466]])]) - - final = result["final_result"] - assert final["status"] == "rejected" and final["executed"] is False - assert final["result"] is None - reexec.assert_not_called() +@pytest.mark.parametrize("sql", ["SELECT COUNT(*) AS flights FROM \"postgres\".\"public\".\"flights_table\"", + "DELETE FROM \"postgres\".\"public\".\"flights_table\""], ids=["select", "delete"]) +def test_sql_that_never_ran_is_never_executed_or_shown(sql): + """submit_answer refuses such SQL (SubmitApprovalMiddleware); if it ever reached verification, nothing runs.""" + answer = SubmitAnswer(sql=sql, explanation_he="הסבר", confidence="high") + with patch.object(verification, "execute_query_sync") as run: + final = verify_answer(answer, []) + run.assert_not_called() + assert final["status"] == "not_executed" and final["executed"] is False and final["result"] is None @pytest.mark.asyncio @@ -145,9 +133,10 @@ def test_clarifications_are_off_by_default(): @pytest.mark.asyncio @pytest.mark.parametrize("enabled", [False, True]) async def test_clarification_only_mentioned_in_prompt_when_enabled(scripted_model, enabled): - model = scripted_model(AIMessage("", tool_calls=[{"name": "submit_answer", "args": {**ANSWER}, "id": "f"}])) + model = scripted_model(AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": EXECUTED}, "id": "e"}]), + AIMessage("", tool_calls=[{"name": "submit_answer", "args": {**ANSWER}, "id": "f"}])) agent = create_deep_agent(model=model, clarifications_enabled=enabled) - with patch.object(verification, "execute_query_sync", return_value=_trino([[1]])): + with patch.object(sql_tools, "execute_query_sync", return_value=_trino([[1]])): await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": f"c{enabled}"}}) assert ("needs_clarification" in system_text(model.seen[0])) is enabled @@ -173,8 +162,11 @@ def policy(messages): def test_re_execution_without_a_row_ceiling(monkeypatch): monkeypatch.setattr(verification.settings, "DEEP_AGENT_MAX_ROWS", None) answer = SubmitAnswer(sql="SELECT a FROM t", explanation_he="הסבר", confidence="high") + sample = verification.executed_query_record( # the approved SQL ran with limit=5 + "SELECT a FROM t", "SELECT a FROM t LIMIT 6", + {"columns": ["a"], "rows": [[i] for i in range(5)], "row_count": 5, "truncated": True}, 5) with patch.object(verification, "execute_query_sync", return_value=_trino([[i] for i in range(500)])) as run: - final = verify_answer(answer, []) + final = verify_answer(answer, [sample]) assert run.call_args.args[0] == "SELECT a FROM t" # no LIMIT added assert final["executed"] is True and final["result"]["row_count"] == 500 and final["result"]["truncated"] is False diff --git a/agent/tests/deep_agent/test_service.py b/agent/tests/deep_agent/test_service.py index 2ba773c..df6e220 100644 --- a/agent/tests/deep_agent/test_service.py +++ b/agent/tests/deep_agent/test_service.py @@ -113,21 +113,23 @@ async def test_turn_without_new_answer_does_not_repeat_the_previous_one(scripted @pytest.mark.asyncio -async def test_answer_only_matches_sql_executed_in_its_own_turn(scripted_model, published): - """Turn 2 submits turn 1's SQL without running it: not 'matched' — it is re-executed to get real rows.""" +async def test_answer_must_run_in_its_own_turn(scripted_model, published): + """Turn 2 submits turn 1's SQL without running it: refused; the agent runs it and submits again.""" model = scripted_model( AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), _answer(), + _answer(), # turn 2: not run yet + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e2"}]), _answer(), ) agent = create_deep_agent(model=model) - with patch.object(sql_tools, "execute_query_sync", return_value=OK), \ - patch.object(verification, "execute_query_sync", return_value=OK) as rerun: + with patch.object(sql_tools, "execute_query_sync", side_effect=lambda *a, **k: TrinoExecutionResult( + success=True, rows=[[466]], columns=["orders"], row_count=1, query_id=str(uuid.uuid4()))), \ + patch.object(verification, "execute_query_sync") as rerun: first = await run_deep_chat(connection_id=89, query="q1", thread_id="deep-t3", agent=agent) second = await run_deep_chat(connection_id=89, query="ושוב", thread_id="deep-t3", agent=agent) - assert first["verification"] == "matched" - assert second["verification"] == "re_executed" and second["executed"] is True - rerun.assert_called_once() + assert first["verification"] == second["verification"] == "matched" + rerun.assert_not_called() @pytest.mark.asyncio @@ -229,14 +231,18 @@ async def test_threads_survive_a_restart_with_postgres(scripted_model, monkeypat @pytest.mark.asyncio async def test_reviewer_tools_are_labelled_in_the_stream(scripted_model, published): + brief = f"```sql\n{SQL}\n```" main = scripted_model( - AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), _answer()) + AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), + AIMessage("", tool_calls=[{"name": "task", "args": {"description": brief, "subagent_type": "semantic-validator"}, + "id": "r1"}]), + _answer()) reviewer = scripted_model( - AIMessage("", tool_calls=[{"name": "get_sample_rows", "args": {"table_name": "orders"}, "id": "r1"}]), + AIMessage("", tool_calls=[{"name": "get_sample_rows", "args": {"table_name": "orders"}, "id": "x1"}]), AIMessage("", tool_calls=[{"name": "submit_verdict", "args": {"verdict": "pass"}, "id": "v1"}]), ) agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) with patch.object(sql_tools, "execute_query_sync", return_value=OK): r = await run_deep_chat(connection_id=89, query="q", thread_id="deep-t6", agent=agent) - assert r["execution_path"] == ["deep:execute_trino_query", "deep:review:get_sample_rows"] + assert r["execution_path"] == ["deep:execute_trino_query", "deep:task", "deep:review:get_sample_rows"] assert r["semantic_validation"]["verdict"] == "passed" diff --git a/agent/tests/deep_agent/test_validator.py b/agent/tests/deep_agent/test_validator.py index 00381ac..7d93c29 100644 --- a/agent/tests/deep_agent/test_validator.py +++ b/agent/tests/deep_agent/test_validator.py @@ -1,6 +1,11 @@ -"""Independent semantic review of answers (deep_agent.validator): "always" gate and "on_demand" subagent.""" +"""Independent semantic review (deep_agent.validator) and the two approvals submit_answer needs. + +The agent runs the SQL, has the `semantic-validator` subagent review it, then submits. submit_answer +only checks the records: the SQL ran this turn, and the reviewer passed it (or the agent disputes). +""" import itertools +import json from contextlib import contextmanager from types import SimpleNamespace from unittest.mock import patch @@ -11,16 +16,18 @@ from deep_agent.agent import create_deep_agent from deep_agent.answer import verification +from deep_agent.answer.middleware import NOT_REVIEWED, NOT_RUN from deep_agent.answer.render import render_markdown from deep_agent.answer.schema import ANSWER_RECEIVED, answer_schema -from deep_agent.answer.verification import validation_summary +from deep_agent.answer.verification import normalize_sql, validation_summary from deep_agent.observability import run_metrics from deep_agent.tools import sql as sql_tools -from deep_agent.validator.modes import feedback_text -from deep_agent.validator.reviewer import VALIDATOR_TOOLS, SubmitVerdict +from deep_agent.validator.reviewer import VALIDATOR_TOOLS, SubmitVerdict, parse_brief, review_request SQL = "SELECT COUNT(*) AS n FROM orders WHERE status = 'shipped'" FIXED = "SELECT COUNT(DISTINCT order_id) AS n FROM orders WHERE status = 'shipped'" +QUESTION = "כמה הזמנות נשלחו?" +ISSUE = {"problem": "סופרים שורות ולא הזמנות", "evidence": "COUNT(*)=42 אבל COUNT(DISTINCT order_id)=40"} _ids = itertools.count() @@ -31,29 +38,36 @@ def _trino(*args, **kwargs): @contextmanager def _fake_trino(): - """Every execution in the run (agent, reviewer, re-execution) — never the real Trino.""" + """Every execution in the run (agent, reviewer, full-rows run) — never the real Trino.""" with patch.object(sql_tools, "execute_query_sync", side_effect=_trino), \ patch.object(verification, "execute_query_sync", side_effect=_trino): yield -ISSUE = {"problem": "סופרים שורות ולא הזמנות", "evidence": "COUNT(*)=42 אבל COUNT(DISTINCT order_id)=40"} -def _execute(sql, call_id="e1"): - return AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": sql}, "id": call_id}]) +def _call(name, args, call_id): + return AIMessage("", tool_calls=[{"name": name, "args": args, "id": call_id}]) + + +def _execute(sql=SQL, call_id="e1", **extra): + return _call("execute_trino_query", {"sql": sql, **extra}, call_id) + + +def _review(sql=SQL, call_id="r1", prose=""): + brief = f"{prose}\n```sql\n{sql}\n```\nAssumptions:\n- הזמנה = שורה בטבלה" + return _call("task", {"description": brief, "subagent_type": "semantic-validator"}, call_id) def _submit(sql=SQL, call_id="s1", **extra): - return AIMessage("", tool_calls=[{"name": "submit_answer", "id": call_id, "args": { - "sql": sql, "explanation_he": "מספר ההזמנות שנשלחו", "confidence": "high", **extra}}]) + return _call("submit_answer", {"sql": sql, "explanation_he": "מספר ההזמנות שנשלחו", "confidence": "high", **extra}, + call_id) def _verdict(verdict, issues=(), call_id="v1"): - return AIMessage("", tool_calls=[{"name": "submit_verdict", "id": call_id, - "args": {"verdict": verdict, "issues": list(issues)}}]) + return _call("submit_verdict", {"verdict": verdict, "issues": list(issues)}, call_id) -async def _run(main, reviewer, question="כמה הזמנות נשלחו?", thread="t"): - agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) +async def _run(main, reviewer=None, mode="always", question=QUESTION, thread="t"): + agent = create_deep_agent(model=main, semantic_validation=mode, validator_model=reviewer) with _fake_trino(): return await agent.ainvoke({"messages": [("user", question)]}, {"configurable": {"thread_id": thread}}) @@ -62,202 +76,187 @@ def _texts(messages): return "\n".join(m.text for m in messages) -# ── always: every submitted answer is reviewed ─────────────────────────────── +def _submit_results(state): + return [m.text for m in state["messages"] if m.type == "tool" and m.name == "submit_answer"] + + +# ── the happy path: run → review → submit ──────────────────────────────────── + +@pytest.mark.asyncio +async def test_run_review_submit_is_accepted(scripted_model): + main = scripted_model(_execute(), _review(), _submit()) + state = await _run(main, scripted_model(_verdict("pass"))) + assert _submit_results(state) == [ANSWER_RECEIVED] + final = state["final_result"] + assert final["status"] == "matched" and final["executed"] is True + assert final["semantic_validation"]["verdict"] == "passed" and final["semantic_validation"]["reviewed_final_sql"] + @pytest.mark.asyncio -async def test_pass_ends_the_run(scripted_model): - main = scripted_model(AIMessage("my private reasoning", tool_calls=_execute(SQL).tool_calls), _submit()) +async def test_reviewer_input_is_built_from_facts_not_the_brief(scripted_model): + main = scripted_model(_execute(), _review(prose="my private reasoning: I already checked it, it is fine"), _submit()) reviewer = scripted_model(_verdict("pass")) - state = await _run(main, reviewer) + await _run(main, reviewer) - final = state["final_result"] - assert final["status"] == "matched" - assert final["semantic_validation"] == {"verdict": "passed", "rounds": 1, "issues": [], "response": None, - "reason": None, "reviewed_final_sql": True} - # Fresh context: the reviewer sees the request, the SQL, the explanation and the rows — not the reasoning. - review = _texts(reviewer.seen[0]) - assert "כמה הזמנות נשלחו?" in review and SQL in review and "מספר ההזמנות שנשלחו" in review and "[42]" in review - assert "my private reasoning" not in review - assert '"catalog"."schema"."orders"' in review # the catalog is in the reviewer's system prompt - assert state["messages"][-1].text == ANSWER_RECEIVED + seen = reviewer.seen[0] + review = _texts(seen) + assert QUESTION in review # the user's own words, from the thread + assert SQL in review and "[42]" in review # the SQL and its recorded rows + assert "claims to check, not facts" in review and "הזמנה = שורה בטבלה" in review + assert "my private reasoning" not in review and "already checked" not in review # the brief's prose is dropped + assert '"catalog"."schema"."orders"' in review # the catalog, as for every call + user = [m for m in seen if m.type == "human"][0] + assert user.text.startswith("[Today") # the date, on the built input +# ── submit_answer checks the two approvals ─────────────────────────────────── + @pytest.mark.asyncio -async def test_fail_sends_feedback_and_the_revision_is_reviewed_again(scripted_model): - main = scripted_model(_execute(SQL), _submit(), _execute(FIXED, "e2"), _submit(FIXED, "s2")) - reviewer = scripted_model(_verdict("fail", [ISSUE]), _verdict("pass", call_id="v2")) +async def test_submit_without_running_is_refused(scripted_model): + main = scripted_model(_review(), _submit(), _execute(), _review(call_id="r2"), _submit(call_id="s2")) + reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) state = await _run(main, reviewer) + assert _submit_results(state) == [NOT_RUN, ANSWER_RECEIVED] + assert state["final_result"]["status"] == "matched" - # The model saw the review instead of "Answer received." for its first submission. - after_fail = _texts(main.seen[2]) - assert ISSUE["problem"] in after_fail and ISSUE["evidence"] in after_fail - first_submission = next(m for m in state["messages"] if m.type == "tool" and m.tool_call_id == "s1") - assert first_submission.text == feedback_text([ISSUE]) - final = state["final_result"] - assert final["sql"] == FIXED and final["status"] == "matched" - assert final["semantic_validation"]["verdict"] == "passed" and final["semantic_validation"]["rounds"] == 2 - assert FIXED in _texts(reviewer.seen[1]) +@pytest.mark.asyncio +async def test_submit_without_review_is_refused(scripted_model): + main = scripted_model(_execute(), _submit(), _review(), _submit(call_id="s2")) + state = await _run(main, scripted_model(_verdict("pass"))) + assert _submit_results(state) == [NOT_REVIEWED, ANSWER_RECEIVED] + assert state["final_result"]["semantic_validation"]["verdict"] == "passed" @pytest.mark.asyncio -async def test_resubmitting_the_same_sql_with_a_justification_is_a_dispute(scripted_model): - main = scripted_model(_execute(SQL), _submit(), - _submit(SQL, "s2", validation_response="כל שורה היא הזמנה אחת, אין כפילויות")) - reviewer = scripted_model(_verdict("fail", [ISSUE])) +async def test_sql_changed_after_review_is_refused(scripted_model): + main = scripted_model(_execute(), _execute(FIXED, "e2"), _review(), _submit(FIXED), _review(FIXED, "r2"), + _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) state = await _run(main, reviewer) - - review = state["final_result"]["semantic_validation"] - assert review["verdict"] == "disputed" and review["rounds"] == 1 - assert review["issues"] == [ISSUE] and review["response"] == "כל שורה היא הזמנה אחת, אין כפילויות" - assert len(reviewer.seen) == 1 # the dispute ends the loop without another review - shown = render_markdown(state["final_result"]) - assert "בדיקה עצמאית העלתה הסתייגות" in shown and ISSUE["problem"] in shown and "תגובת הסוכן" in shown + assert _submit_results(state) == [NOT_REVIEWED, ANSWER_RECEIVED] + assert state["final_result"]["sql"] == FIXED and state["final_result"]["semantic_validation"]["verdict"] == "passed" @pytest.mark.asyncio -async def test_stopping_after_a_fail_keeps_the_answer_marked_failed(scripted_model): - main = scripted_model(_execute(SQL), _submit(), AIMessage("I think it is fine.")) - reviewer = scripted_model(_verdict("fail", [ISSUE])) +async def test_failed_review_refuses_submit_and_the_fix_is_reviewed(scripted_model): + main = scripted_model(_execute(), _review(), _submit(), _execute(FIXED, "e2"), _review(FIXED, "r2"), + _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("fail", [ISSUE]), _verdict("pass", call_id="v2")) state = await _run(main, reviewer) + refusal = _submit_results(state)[0] + assert refusal.startswith("Not submitted: the semantic-validator failed") and ISSUE["problem"] in refusal final = state["final_result"] - assert final["sql"] == SQL and final["executed"] is True - assert final["semantic_validation"]["verdict"] == "failed" - assert "בדיקה עצמאית מצאה בעיות בתשובה" in render_markdown(final) + assert final["sql"] == FIXED and final["semantic_validation"]["verdict"] == "passed" + assert final["semantic_validation"]["rounds"] == 2 @pytest.mark.asyncio -async def test_review_limit_is_optional(scripted_model, monkeypatch): +async def test_submitting_a_failed_sql_with_a_justification_is_a_dispute(scripted_model): + main = scripted_model(_execute(), _review(), _submit(validation_response="כל שורה היא הזמנה אחת")) + state = await _run(main, scripted_model(_verdict("fail", [ISSUE]))) + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "disputed" and review["issues"] == [ISSUE] + assert review["response"] == "כל שורה היא הזמנה אחת" + shown = render_markdown(state["final_result"]) + assert "בדיקה עצמאית העלתה הסתייגות" in shown and "תגובת הסוכן" in shown + + +@pytest.mark.asyncio +async def test_review_limit_accepts_an_unreviewed_sql_as_not_validated(scripted_model, monkeypatch): from agent.config import settings monkeypatch.setattr(settings, "DEEP_AGENT_VALIDATOR_MAX_ROUNDS", 1) - main = scripted_model(_execute(SQL), _submit(), _execute(FIXED, "e2"), _submit(FIXED, "s2")) - reviewer = scripted_model(_verdict("fail", [ISSUE])) - state = await _run(main, reviewer) - + main = scripted_model(_execute(), _review(), _execute(FIXED, "e2"), _submit(FIXED)) + state = await _run(main, scripted_model(_verdict("fail", [ISSUE]))) review = state["final_result"]["semantic_validation"] + assert state["final_result"]["sql"] == FIXED assert review["verdict"] == "not_validated" and review["reason"] == "review limit reached (1)" - assert len(reviewer.seen) == 1 @pytest.mark.asyncio -async def test_a_broken_review_does_not_lose_the_answer(scripted_model): - main = scripted_model(_execute(SQL), _submit()) - reviewer = scripted_model() # no scripted reply: the reviewer's model call raises +async def test_brief_without_a_sql_block_cannot_approve_anything(scripted_model): + no_sql = _call("task", {"description": "please check my count query", "subagent_type": "semantic-validator"}, "r1") + main = scripted_model(_execute(), no_sql, _submit(), _review(call_id="r2"), _submit(call_id="s2")) + reviewer = scripted_model(_verdict("fail", [{"problem": "no SQL", "evidence": "-"}]), _verdict("pass", call_id="v2")) state = await _run(main, reviewer) - - final = state["final_result"] - assert final["status"] == "matched" - assert final["semantic_validation"]["verdict"] == "not_validated" - assert final["semantic_validation"]["reason"] + assert "none was provided" in _texts(reviewer.seen[0]) + assert _submit_results(state) == [NOT_REVIEWED, ANSWER_RECEIVED] + assert state["final_result"]["semantic_validation"]["verdict"] == "passed" @pytest.mark.asyncio -async def test_follow_up_turn_is_reviewed_with_its_context(scripted_model): - main = scripted_model(_execute(SQL), _submit(), _execute(FIXED, "e2"), _submit(FIXED, "s2")) - reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) - agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) - config = {"configurable": {"thread_id": "follow-up"}} - with _fake_trino(): - await agent.ainvoke({"messages": [("user", "כמה הזמנות נשלחו?")]}, config) - state = await agent.ainvoke({"messages": [("user", "ובלי כפילויות?")]}, config) - - second = _texts(reviewer.seen[1]) - assert "Earlier user messages" in second and "כמה הזמנות נשלחו?" in second - assert "Current user request\nובלי כפילויות?" in second - assert state["final_result"]["semantic_validation"]["rounds"] == 1 # counted per turn +async def test_off_mode_still_requires_that_the_sql_ran(scripted_model): + main = scripted_model(_submit(), _execute(), _submit(call_id="s2")) + state = await _run(main, mode="off") + assert _submit_results(state) == [NOT_RUN, ANSWER_RECEIVED] + assert state["final_result"]["status"] == "matched" + assert state["final_result"]["semantic_validation"] is None # review off -# ── on_demand: the agent calls the reviewer through `task` ─────────────────── +@pytest.mark.asyncio +async def test_truncated_sample_is_re_run_unchanged_for_all_rows(scripted_model): + sample = TrinoExecutionResult(success=True, rows=[[i] for i in range(6)], columns=["n"], row_count=6, query_id="s") + full = TrinoExecutionResult(success=True, rows=[[i] for i in range(40)], columns=["n"], row_count=40, query_id="f") + main = scripted_model(_execute(limit=5), _review(), _submit()) + agent = create_deep_agent(model=main, semantic_validation="always", validator_model=scripted_model(_verdict("pass"))) + with patch.object(sql_tools, "execute_query_sync", return_value=sample), \ + patch.object(verification, "execute_query_sync", return_value=full) as rerun: + state = await agent.ainvoke({"messages": [("user", QUESTION)]}, {"configurable": {"thread_id": "s"}}) + assert state["final_result"]["status"] == "re_executed" and state["final_result"]["result"]["row_count"] == 40 + assert rerun.call_args.args[0].startswith(SQL) -def _review(sql=SQL, call_id="r1", extra=""): - brief = f"User request: כמה הזמנות נשלחו?\n```sql\n{sql}\n```\nResult: [[42]]{extra}" - return {"name": "task", "id": call_id, "args": {"description": brief, "subagent_type": "semantic-validator"}} +# ── strict submit: no fallback ──────────────────────────────────────────────── -async def _run_on_demand(main, reviewer, thread="od"): - agent = create_deep_agent(model=main, semantic_validation="on_demand", validator_model=reviewer) - with _fake_trino(): - return await agent.ainvoke({"messages": [("user", "כמה הזמנות נשלחו?")]}, {"configurable": {"thread_id": thread}}) +ANSWER_AS_TEXT = json.dumps({"sql": SQL, "explanation_he": "x", "confidence": "high"}) @pytest.mark.asyncio -async def test_on_demand_review_returns_the_verdict_to_the_agent(scripted_model): - main = scripted_model(_execute(SQL), AIMessage("my private reasoning", tool_calls=[_review()]), _submit()) - reviewer = scripted_model(_verdict("pass")) - state = await _run_on_demand(main, reviewer) +async def test_strict_submit_has_no_recovery_or_reminder(scripted_model, monkeypatch): + from agent.config import settings - assert '"verdict":"pass"' in _texts(main.seen[2]) # the verdict came back as the task result (JSON) - review = state["final_result"]["semantic_validation"] - assert review["verdict"] == "passed" and review["rounds"] == 1 and review["reviewed_final_sql"] is True - seen = _texts(reviewer.seen[0]) - assert SQL in seen and "my private reasoning" not in seen # fresh context: only the brief - assert '"catalog"."schema"."orders"' in seen - assert "`semantic-validator` subagent is available" in _texts(main.seen[0]) # the Phase 6 nudge + monkeypatch.setattr(settings, "DEEP_AGENT_STRICT_SUBMIT", True) + state = await _run(scripted_model(_execute(), AIMessage(ANSWER_AS_TEXT)), mode="off") + assert state["final_result"]["status"] == "no_answer" + assert not [m for m in state["messages"] if getattr(m, "name", None) == "submit_reminder"] @pytest.mark.asyncio -async def test_on_demand_review_of_a_different_sql_does_not_count(scripted_model): - main = scripted_model(_execute(SQL), AIMessage("", tool_calls=[_review()]), - _execute(FIXED, "e2"), _submit(FIXED)) - reviewer = scripted_model(_verdict("fail", [ISSUE])) - state = await _run_on_demand(main, reviewer) +async def test_default_submit_fallback_recovers_an_answer_written_as_text(scripted_model): + state = await _run(scripted_model(_execute(), AIMessage(ANSWER_AS_TEXT)), mode="off") + assert state["final_result"]["status"] == "matched" and state["final_result"]["recovered_from_text"] is True - review = state["final_result"]["semantic_validation"] - assert review["verdict"] == "not_validated" and review["reviewed_final_sql"] is False - assert review["reason"] == "the final SQL changed after the last review" and review["rounds"] == 1 - assert "בדיקה עצמאית" not in render_markdown(state["final_result"]) # no warning about issues that were fixed - assert run_metrics([], 1.0, state["final_result"]).semantic_validation_passed is None +# ── the reviewer and its records ───────────────────────────────────────────── -@pytest.mark.asyncio -async def test_on_demand_without_a_review(scripted_model): - state = await _run_on_demand(scripted_model(_execute(SQL), _submit()), scripted_model()) - review = state["final_result"]["semantic_validation"] - assert review["verdict"] == "not_validated" and review["rounds"] == 0 and review["reason"] == "no review" +def test_parse_brief_takes_only_the_sql_and_the_bullets(): + sql, assumptions = parse_brief("I'm confident.\n```sql\nSELECT 1\n```\nAssumptions:\n- a\n* b\n1. c\nMore prose.") + assert sql == "SELECT 1" and assumptions == ["a", "b", "c"] + assert parse_brief("no sql here") == (None, []) -@pytest.mark.asyncio -async def test_on_demand_failed_review_of_the_final_sql_is_shown(scripted_model): - main = scripted_model(_execute(SQL), AIMessage("", tool_calls=[_review()]), _submit()) - state = await _run_on_demand(main, scripted_model(_verdict("fail", [ISSUE]))) - review = state["final_result"]["semantic_validation"] - assert review["verdict"] == "failed" and review["issues"] == [ISSUE] - assert "בדיקה עצמאית מצאה בעיות בתשובה" in render_markdown(state["final_result"]) +def test_review_request_marks_earlier_messages_and_missing_runs(): + text = review_request(["כמה טיסות יצאו מצרפת?", "ומאיטליה?"], SQL, [], []) + assert "Earlier user messages" in text and "כמה טיסות יצאו מצרפת?" in text + assert "Current user request\nומאיטליה?" in text + assert "has not run successfully in this turn" in text and "(none stated)" in text @pytest.mark.asyncio -async def test_parallel_on_demand_reviews_are_both_recorded(policy_model): - def main_policy(messages): - tool_names = [m.name for m in messages if m.type == "tool"] - if not tool_names: - return _execute(SQL) - if "task" not in tool_names: - return AIMessage("", tool_calls=[_review(call_id="r1"), _review(FIXED, "r2")]) - return _submit() - - def reviewer_policy(messages): - return _verdict("pass") - - state = await _run_on_demand(policy_model(main_policy), policy_model(reviewer_policy)) - records = state["semantic_validations"] - assert len(records) == 2 and len({r["id"] for r in records}) == 2 - assert state["final_result"]["semantic_validation"]["rounds"] == 2 - - -def test_modes_wire_the_reviewer(scripted_model): - for mode, subagent in [("on_demand", True), ("always", False), ("off", False)]: - agent = create_deep_agent(model=scripted_model(), semantic_validation=mode) - tools_desc = str(agent.get_graph().nodes) # built without errors in every mode - assert tools_desc - assert ("semantic-validator" in _task_description(agent)) is subagent, mode - - -def _task_description(agent) -> str: - node = agent.nodes["tools"].bound - task = node.tools_by_name.get("task") - return task.description if task else "" +async def test_follow_up_turn_gives_the_reviewer_the_earlier_question(scripted_model): + main = scripted_model(_execute(), _review(), _submit(), _execute(FIXED, "e2"), _review(FIXED, "r2"), + _submit(FIXED, "s2")) + reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) + agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) + config = {"configurable": {"thread_id": "follow-up"}} + with _fake_trino(): + await agent.ainvoke({"messages": [("user", QUESTION)]}, config) + state = await agent.ainvoke({"messages": [("user", "ובלי כפילויות?")]}, config) + second = _texts(reviewer.seen[1]) + assert "Earlier user messages" in second and QUESTION in second and "ובלי כפילויות?" in second + assert state["final_result"]["semantic_validation"]["rounds"] == 1 # counted per turn def test_reviewer_tools_are_read_only_diagnostics(): @@ -272,39 +271,31 @@ def test_fail_verdict_needs_evidence(): assert SubmitVerdict(verdict="pass").issues == [] -def test_validation_response_only_exists_with_validation(): - assert "validation_response" in answer_schema(False, True).model_fields # "always" mode only +def test_validation_response_only_exists_when_review_is_required(): + assert "validation_response" in answer_schema(False, True).model_fields assert "validation_response" not in answer_schema(False, False).model_fields -def test_summary_and_scores(): - assert validation_summary(None) is None # reviewer off - assert validation_summary([])["verdict"] == "not_validated" - unreviewed = run_metrics([], 1.0, {"semantic_validation": validation_summary([])}) - assert unreviewed.semantic_validation_passed is None and unreviewed.validation_rounds == 0 - metrics = run_metrics([], 1.0, {"semantic_validation": {"verdict": "passed", "rounds": 2}}) - assert metrics.semantic_validation_passed is True and metrics.validation_rounds == 2 - off = run_metrics([], 1.0, {"semantic_validation": None}) - assert off.semantic_validation_passed is None and off.validation_rounds is None # no score when off +def test_defaults(): + from agent.config import AgentSettings + assert AgentSettings.model_fields["DEEP_AGENT_SEMANTIC_VALIDATION"].default == "always" + assert AgentSettings.model_fields["DEEP_AGENT_STRICT_SUBMIT"].default is False -# ── rejected submit_answer arguments are retried (every turn) ──────────────── -@pytest.mark.asyncio -@pytest.mark.parametrize("validation", ["off", "always", "on_demand"]) -async def test_invalid_submission_is_retried_on_every_turn(scripted_model, validation): - bad = AIMessage("", tool_calls=[{"name": "submit_answer", "id": "bad", "args": {"sql": SQL}}]) # missing fields - main = scripted_model(_execute(SQL), bad, _submit(), _execute(SQL, "e2"), bad, _submit(call_id="s2")) - reviewer = scripted_model(_verdict("pass"), _verdict("pass", call_id="v2")) - agent = create_deep_agent(model=main, semantic_validation=validation, validator_model=reviewer) - config = {"configurable": {"thread_id": f"retry-{validation}"}} - with _fake_trino(): - first = await agent.ainvoke({"messages": [("user", "q1")]}, config) - second = await agent.ainvoke({"messages": [("user", "q2")]}, config) - assert first["final_result"]["status"] == "matched" - assert second["final_result"]["status"] == "matched" +def test_summary_looks_at_the_review_of_the_final_sql(): + records = [{"id": "1", "verdict": "pass", "sql": normalize_sql(SQL), "issues": []}, + {"id": "2", "verdict": "fail", "sql": normalize_sql(FIXED), "issues": [ISSUE]}] + assert validation_summary(records, SQL)["verdict"] == "passed" # not the later review of another SQL + assert validation_summary(records, FIXED)["verdict"] == "failed" + assert validation_summary([], SQL)["reason"] == "no review of the final SQL" + assert validation_summary(None, SQL) is None # review off + passed = run_metrics([], 1.0, {"semantic_validation": validation_summary(records, SQL)}) + assert passed.semantic_validation_passed is True and passed.validation_rounds == 2 +# ── unchanged harness behaviour ────────────────────────────────────────────── + @pytest.mark.asyncio async def test_parallel_general_purpose_tasks_do_not_collide(policy_model): """Every subagent returns the parent's state keys; two in one step must not be rejected.""" @@ -317,68 +308,42 @@ def main_policy(messages): agent = create_deep_agent(model=policy_model(main_policy), semantic_validation="off") state = await agent.ainvoke({"messages": [("user", "q")]}, {"configurable": {"thread_id": "gp"}}) - assert [m.name for m in state["messages"] if m.type == "tool"] == ["task", "task"] + assert [m.name for m in state["messages"] if m.type == "tool"][:2] == ["task", "task"] -# ── submit reminder (model ends with text instead of the submit call) ──────── +def test_reminder_is_not_the_users_words(): + from langchain_core.messages import HumanMessage -def test_default_mode_is_always(): - from agent.config import AgentSettings + from deep_agent.context import REMINDER_NAME, current_turn, user_request - assert AgentSettings.model_fields["DEEP_AGENT_SEMANTIC_VALIDATION"].default == "always" + messages = [HumanMessage("the question"), AIMessage("text"), HumanMessage("submit!", name=REMINDER_NAME)] + assert current_turn(messages) == messages[1:] + assert user_request(SimpleNamespace(state={"messages": messages})) == "the question" @pytest.mark.asyncio -async def test_reviewer_that_forgets_its_verdict_is_reminded_once(scripted_model): - reviewer = scripted_model(AIMessage("I found the join is broken."), _verdict("fail", [ISSUE])) - main = scripted_model(_execute(SQL), _submit(), _submit(SQL, "s2", validation_response="בטוח")) - state = await _run(main, reviewer) - - assert "submit_verdict" in _texts(reviewer.seen[1]) # the reminder +async def test_on_demand_offers_the_reviewer_but_submit_only_needs_a_run(scripted_model): + main = scripted_model(_execute(), _submit()) + state = await _run(main, scripted_model(), mode="on_demand") + assert _submit_results(state) == [ANSWER_RECEIVED] review = state["final_result"]["semantic_validation"] - assert review["verdict"] == "disputed" and review["issues"] == [ISSUE] # the verdict was not lost - - -@pytest.mark.asyncio -async def test_main_agent_that_answers_in_text_is_reminded_once(scripted_model): - main = scripted_model(_execute(SQL), AIMessage("There are 42 shipped orders."), _submit()) - agent = create_deep_agent(model=main, semantic_validation="off") - with _fake_trino(): - state = await agent.ainvoke({"messages": [("user", "כמה הזמנות נשלחו?")]}, {"configurable": {"thread_id": "rm"}}) - assert state["final_result"]["status"] == "matched" - reminder = main.seen[2][-1] - assert reminder.type == "human" and reminder.name == "submit_reminder" and "submit_answer" in reminder.text - assert not reminder.text.startswith("[Today") # the date stays on the user's message - assert main.seen[2][[m.type for m in main.seen[2]].index("human")].text.startswith("[Today") + assert review["verdict"] == "not_validated" and review["reason"] == "no review of the final SQL" + assert "worth it before submit_answer" in _texts(main.seen[0]) or "semantic-validator" in _texts(main.seen[0]) @pytest.mark.asyncio -async def test_reminder_is_sent_only_once_per_turn(scripted_model): - main = scripted_model(AIMessage("no"), AIMessage("still no"), AIMessage("next turn"), AIMessage("still not")) - agent = create_deep_agent(model=main, semantic_validation="off") - config = {"configurable": {"thread_id": "once"}} - first = await agent.ainvoke({"messages": [("user", "q1")]}, config) - second = await agent.ainvoke({"messages": [("user", "q2")]}, config) - reminders = [m for m in second["messages"] if getattr(m, "name", None) == "submit_reminder"] - assert len(reminders) == 2 # one per turn, not more - assert first["final_result"]["status"] == second["final_result"]["status"] == "no_answer" - assert len(main.seen) == 4 +async def test_on_demand_review_is_reported_when_the_agent_asks_for_it(scripted_model): + main = scripted_model(_execute(), _review(), _submit()) + state = await _run(main, scripted_model(_verdict("pass")), mode="on_demand") + assert state["final_result"]["semantic_validation"]["verdict"] == "passed" @pytest.mark.asyncio -async def test_no_reminder_after_a_failed_review(scripted_model): - """The agent may stop after a fail: its (failed) answer stands — that is not a missing answer.""" - main = scripted_model(_execute(SQL), _submit(), AIMessage("I think it is fine.")) - state = await _run(main, scripted_model(_verdict("fail", [ISSUE]))) - assert not [m for m in state["messages"] if getattr(m, "name", None) == "submit_reminder"] - assert state["final_result"]["semantic_validation"]["verdict"] == "failed" - - -def test_reminder_is_not_the_users_words(): - from langchain_core.messages import HumanMessage - - from deep_agent.context import REMINDER_NAME, current_turn, user_request - - messages = [HumanMessage("the question"), AIMessage("text"), HumanMessage("submit!", name=REMINDER_NAME)] - assert current_turn(messages) == messages[1:] - assert user_request(SimpleNamespace(state={"messages": messages})) == "the question" +@pytest.mark.parametrize("mode, offered", [("always", True), ("on_demand", True), ("off", False)]) +async def test_modes_offer_the_reviewer(scripted_model, mode, offered): + main = scripted_model(_execute(), _submit(), _review(), _submit(call_id="s2")) + reviewer = scripted_model(_verdict("pass")) + await _run(main, reviewer, mode=mode) + task_tool = next((t for t in main.bound_tool_names[0] if t == "task"), None) + assert task_tool == "task" # general-purpose is always there + assert ("semantic-validator" in _texts(main.seen[0])) is offered From 92bd48babad759815ee6a58e76fcada77c83ef15 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 1 Nov 2026 17:49:03 +0200 Subject: [PATCH 26/37] fix(deep-agent): bind the Langfuse tracer to our keys (CLI runs were untraced) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The keys live in agent settings (.env), not in the process environment, so a bare CallbackHandler() started a disabled client ("Langfuse client initialized without public_key") unless the legacy graph had already created a keyed one — true behind the agent service, not in the CLI. The deep agent now creates our keyed client and binds the handler to its public key; if tracing can't start, the run continues with a warning. Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/observability.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/agent/src/deep_agent/observability.py b/agent/src/deep_agent/observability.py index 6405ea4..8302227 100644 --- a/agent/src/deep_agent/observability.py +++ b/agent/src/deep_agent/observability.py @@ -39,9 +39,20 @@ def agent_version() -> str: def _langfuse_handler() -> BaseCallbackHandler | None: - from core.langfuse import get_langfuse_handler + """A Langfuse callback bound to our project's keys. - return get_langfuse_handler() + The keys live in agent settings (.env), not in the process environment, so a bare + CallbackHandler() would start a disabled client unless something else had already created a + keyed one (the legacy graph does; the CLI doesn't). Create our client, then bind to its key. + """ + try: + import agent.langfuse_client # noqa: F401 — creates the Langfuse client with settings' keys + from langfuse.langchain import CallbackHandler + + return CallbackHandler(public_key=settings.LANGFUSE_PUBLIC_KEY) + except Exception as exc: # tracing must never break a run + logger.warning("Langfuse tracing disabled: %s", exc) + return None def build_run_config( From 8649e11e32945c3a6d405351f64a6e613bb8adc5 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 2 Nov 2026 10:49:24 +0200 Subject: [PATCH 27/37] =?UTF-8?q?refactor(deep-agent):=20the=20reviewer=20?= =?UTF-8?q?judges=20by=20reading=20=E2=80=94=20no=20SQL=20tools,=20rare=20?= =?UTF-8?q?needs=5Fcheck=20run=20by=20the=20agent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - semantic-validator: no SQL tools; it reads the request, the SQL, its result rows, the assumptions and the catalog (types, descriptions, example values). Verdicts: pass | fail (issues with evidence) | needs_check (rare: a concrete, visible doubt only data can settle, with specific checks) - needs_check: submit_answer refuses with the checks; the agent runs them and asks again; the next review sees the checks it asked for and the real results of the queries run since (recorded executions, never the agent's description) - reviewer prompt rewritten for reading: when (and when not) to ask for a check, ties, cut-off results, join keys judged from the catalog's example values - brief parser: only a real ```sql code block counts (an inline mention in prose did) - main agent: SELECT aliases can't be used in GROUP BY / WHERE (verified on Trino); sample and distinct-value tools say when the requested limit was reduced to the ceiling Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 6 +- agent/src/deep_agent/answer/middleware.py | 17 +++- agent/src/deep_agent/answer/verification.py | 7 +- agent/src/deep_agent/prompts/system.md | 4 +- agent/src/deep_agent/prompts/validator.md | 44 ++++++---- agent/src/deep_agent/tools/sql.py | 19 ++-- agent/src/deep_agent/validator/__init__.py | 4 +- agent/src/deep_agent/validator/modes.py | 6 +- agent/src/deep_agent/validator/reviewer.py | 96 +++++++++++++-------- agent/tests/deep_agent/test_service.py | 5 +- agent/tests/deep_agent/test_trino_tools.py | 10 +++ agent/tests/deep_agent/test_validator.py | 63 ++++++++++++-- 12 files changed, 196 insertions(+), 85 deletions(-) diff --git a/agent/README.md b/agent/README.md index 6a73758..e805091 100644 --- a/agent/README.md +++ b/agent/README.md @@ -77,8 +77,10 @@ A SQL answer needs two approvals **before** it is submitted: 2. **It answers the question:** the `semantic-validator` subagent (`src/deep_agent/validator/`) passed it. The agent calls it through `task` with the SQL and its assumptions; the reviewer's input is built by our code from facts — the user's own messages, the SQL, its recorded rows, the assumptions as claims to check, the catalog and the date — - never from the agent's reasoning. It has read-only diagnostic tools and returns pass, or fail with issues and - evidence (prompt: `prompts/validator.md`, `deep-agent/validator` in Langfuse). + never from the agent's reasoning. It judges by reading (no SQL tools) and returns pass, fail with issues and + evidence, or — rarely, when only data can settle a doubt it can see — needs_check with specific checks; the agent + runs them and asks for review again, and the reviewer then sees their real results (prompt: `prompts/validator.md`, + `deep-agent/validator` in Langfuse). `submit_answer` only checks those records. Without them it is refused with the reason and the agent continues; a SQL changed after its review needs a new one. After a fail the agent fixes the SQL, or disputes: it submits the same SQL diff --git a/agent/src/deep_agent/answer/middleware.py b/agent/src/deep_agent/answer/middleware.py index c80d089..0a9e793 100644 --- a/agent/src/deep_agent/answer/middleware.py +++ b/agent/src/deep_agent/answer/middleware.py @@ -142,6 +142,13 @@ def submit_fallback(tool_name: str) -> list[AgentMiddleware]: "your assumptions as '- ' lines — and submit after a pass.") +def _checks_text(checks: list[str]) -> str: + listed = "\n".join(f"- {c}" for c in checks) + return ("Not submitted: the semantic-validator asks for these checks before it can decide:\n" f"{listed}\n\n" + "Run them with execute_trino_query, then ask the semantic-validator to review the SQL again " + "(it will see the checks' results).") + + def _failed_text(issues: list[dict[str, str]]) -> str: listed = "\n".join(f"{n}. {i['problem']}\n Evidence: {i['evidence']}" for n, i in enumerate(issues, 1)) return ("Not submitted: the semantic-validator failed this SQL:\n" f"{listed}\n\n" @@ -149,12 +156,16 @@ def _failed_text(issues: list[dict[str, str]]) -> str: "with `validation_response` explaining why.") +_REVIEWED = ("pass", "fail", "needs_check") # verdicts of a completed review + + class SubmitApprovalMiddleware(AgentMiddleware): """Accept submit_answer only when the SQL has both approvals — recorded before the submit. 1. ran: the SQL matches a successful execute_trino_query in this turn (a sample counts) 2. reviewed (when review is required): the latest semantic-validator verdict for this SQL is a pass — or a fail and the agent gives `validation_response` (a dispute, recorded and shown to the user). + A needs_check verdict is not a pass: the agent runs the checks and asks for review again. If DEEP_AGENT_VALIDATOR_MAX_ROUNDS reviews already ran this turn, the SQL is accepted as not validated. It only looks the records up; the judging happened before (the execution, the reviewer). A refused @@ -187,16 +198,18 @@ def after_model(self, state, runtime) -> dict[str, Any] | None: return None sql = normalize_sql(answer.sql) records = list(state.get("semantic_validations") or []) - reviews = [r for r in records if r.get("sql") == sql and r["verdict"] in ("pass", "fail")] + reviews = [r for r in records if r.get("sql") == sql and r["verdict"] in _REVIEWED] if reviews and reviews[-1]["verdict"] == "pass": return None + if reviews and reviews[-1]["verdict"] == "needs_check": + return self._refuse(submission, _checks_text(reviews[-1].get("checks") or [])) if reviews: # failed if getattr(answer, "validation_response", None): return {"semantic_validations": [{"id": uuid.uuid4().hex, "verdict": "disputed", "sql": sql, "issues": reviews[-1]["issues"], "response": answer.validation_response}]} return self._refuse(submission, _failed_text(reviews[-1]["issues"])) - done = sum(1 for r in records if r["verdict"] in ("pass", "fail")) + done = sum(1 for r in records if r["verdict"] in _REVIEWED) if self.max_rounds is not None and done >= self.max_rounds: return {"semantic_validations": [{"id": uuid.uuid4().hex, "verdict": "skipped", "sql": sql, "issues": [], "reason": f"review limit reached ({self.max_rounds})"}]} diff --git a/agent/src/deep_agent/answer/verification.py b/agent/src/deep_agent/answer/verification.py index 300966e..bebdf4b 100644 --- a/agent/src/deep_agent/answer/verification.py +++ b/agent/src/deep_agent/answer/verification.py @@ -133,12 +133,13 @@ def validation_summary(records: list[dict[str, Any]] | None, final_sql: str | No """The review outcome of the final answer, from this turn's review records (None = review off). verdict: the latest record for the final SQL — passed | disputed (the agent submitted a failed SQL with a - justification) | failed | not_validated (no review of the final SQL, review limit, or the review errored). + justification) | failed | not_validated (no review of the final SQL, checks still pending, review limit, + or the review errored). rounds: reviews this turn (any SQL). """ if records is None: return None - rounds = sum(1 for r in records if r["verdict"] in ("pass", "fail")) + rounds = sum(1 for r in records if r["verdict"] in ("pass", "fail", "needs_check")) summary = {"verdict": "not_validated", "rounds": rounds, "issues": [], "response": None, "reason": None, "reviewed_final_sql": False} target = normalize_sql(final_sql) @@ -146,5 +147,7 @@ def validation_summary(records: list[dict[str, Any]] | None, final_sql: str | No if not relevant: return {**summary, "reason": "no review of the final SQL"} last = relevant[-1] + if last["verdict"] == "needs_check": + return {**summary, "reviewed_final_sql": True, "reason": "checks were requested and not reviewed again"} return {**summary, "verdict": _VERDICTS.get(last["verdict"], "not_validated"), "issues": last.get("issues") or [], "response": last.get("response"), "reason": last.get("reason"), "reviewed_final_sql": True} diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index 10a277d..007c05f 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -78,7 +78,7 @@ The user's word is almost never the stored string — the value may be spelled d - **Counting**: `COUNT(*)` counts rows, `COUNT(col)` skips NULLs, `COUNT(DISTINCT col)` counts unique non-null values — count entities with `COUNT(DISTINCT id)`. `approx_distinct(x)` is a fast estimate on large tables. - **Idioms**: `count_if(cond)` instead of `SUM(CASE WHEN cond THEN 1 ELSE 0 END)`; `max_by(val, ts)` / `min_by(val, ts)` for the latest/earliest value per entity without a window or self-join. - **NULLs**: `IS NULL` / `IS NOT NULL`, never `= NULL`. `AVG()` ignores NULLs — if NULL means zero, `AVG(COALESCE(col, 0))`; `COALESCE(SUM(...), 0)` when an empty group should be 0. -- **GROUP BY**: every non-aggregated `SELECT` column must be grouped. For distinct ordered values use `SELECT DISTINCT col ... ORDER BY col`. +- **GROUP BY**: every non-aggregated `SELECT` column must be grouped. For distinct ordered values use `SELECT DISTINCT col ... ORDER BY col`. A `SELECT` alias can't be used in `GROUP BY` or `WHERE` (`COLUMN_NOT_FOUND`) — repeat the expression or use `GROUP BY 1`; `ORDER BY` may use the alias. - **Top-N and ties**: for "the highest / the top", return ALL rows sharing the top value unless the user asks for exactly one — `RANK()` keeps ties; `ROW_NUMBER()` breaks them arbitrarily; `ORDER BY ... LIMIT n` for a plain top-N. - **Joins**: every JOIN needs an explicit `ON` with keys (no cross joins). `INNER JOIN` when the relationship is guaranteed; `LEFT JOIN` for "per entity" metrics where some entities may have zero related rows; anti-join (`NOT EXISTS`, or `LEFT JOIN ... WHERE right.key IS NULL`) for entities with NO related rows — not `NOT IN (subquery)` when the key can be NULL. Trino's optimizer reorders joins when statistics exist; without them, put the large fact table on the left and the small lookup table on the right. - **Per-entity ratios**: mind the granularity of numerator vs denominator — "orders per resident" is `COUNT(orders) / SUM(population)`, not `AVG(count_per_row)`. When the denominator comes from another table, aggregate each side in its own CTE, then join and divide. @@ -124,7 +124,7 @@ The user's word is almost never the stored string — the value may be spelled d |---|---| | `SYNTAX_ERROR` (`mismatched input`, `extraneous input`) | Fix the specific line only — do not redesign. Typical causes: backticks (use `"`), `INTERVAL 1 DAY` (use `INTERVAL '1' DAY`), `::` casts | | `TABLE_NOT_FOUND` / `SCHEMA_NOT_FOUND` / `CATALOG_NOT_FOUND` | Use the exact 3-part identifier from the catalog | -| `COLUMN_NOT_FOUND` | Re-check the column name and the table alias prefix against the catalog | +| `COLUMN_NOT_FOUND` | Re-check the column name and the table alias prefix against the catalog — or a `SELECT` alias used in `GROUP BY` / `WHERE` (repeat the expression, or `GROUP BY 1`) | | `AMBIGUOUS_NAME` | Qualify the column with its table alias | | `TYPE_MISMATCH` (`Cannot apply operator: timestamp = varchar`, `varchar = integer`) | `CAST` one side, use a typed literal (`TIMESTAMP '...'`), or quote the literal | | `FUNCTION_NOT_FOUND` (`not registered`) | A non-Trino function — see the table above | diff --git a/agent/src/deep_agent/prompts/validator.md b/agent/src/deep_agent/prompts/validator.md index 47a69f1..b6e79c8 100644 --- a/agent/src/deep_agent/prompts/validator.md +++ b/agent/src/deep_agent/prompts/validator.md @@ -1,14 +1,14 @@ -You are an independent reviewer of Text-to-SQL answers. An analyst translated a user's request into Trino SQL and must have it approved before submitting it. You did not write this SQL and you do not see the analyst's reasoning. You get the user's own messages, the SQL, its result rows, and the analyst's interpretation choices — those are claims to check, not facts. Your job: decide whether this SQL actually answers what the user asked, on this database. If the result rows are missing, run the SQL yourself. +You are an independent reviewer of Text-to-SQL answers. An analyst translated a user's request into Trino SQL and must have it approved before submitting it. You did not write this SQL and you do not see the analyst's reasoning. You get the user's own messages, the SQL, its result rows, and the analyst's interpretation choices — those are claims to check, not facts. Your job: decide whether this SQL actually answers what the user asked, on this database. -The connection's complete catalog is included at the end of this prompt ("Database Catalog"). +You judge by reading. You don't run queries and you don't write SQL. The connection's complete catalog — every table and column with its type, description and example values — is included at the end of this prompt ("Database Catalog"). ## How to review 1. **Restate the request.** In one sentence, what exactly is the user asking for? What should one output row represent (the grain)? Which conditions did the user state (entities, values, places, time ranges)? If there are several user messages, the last one is the current question and the earlier ones are its context (a follow-up such as "and from Italy?" keeps the earlier conditions and changes one). -2. **Translate the SQL back into plain language** and compare it with the request, condition by condition: - - every condition the user stated is in the SQL, on the right column; +2. **Read the SQL back in plain language** and compare it with the request, condition by condition: + - every condition the user stated is in the SQL, on the right column (check the catalog's column descriptions); - the SQL adds no condition the user did not ask for (unless it is stated in the assumptions and reasonable); - - the output grain and the aggregation match the question ("how many X" counts X, not rows of a joined table; "per X" groups by X; "top N" orders by the right measure in the right direction, and ties are handled sensibly); + - the output grain and the aggregation match the question ("how many X" counts X, not rows of a joined table; "per X" groups by X; "top N" orders by the right measure in the right direction); - the selected columns are what the user asked for. How request wording usually maps to SQL, and what goes wrong: @@ -21,23 +21,29 @@ The connection's complete catalog is included at the end of this prompt ("Databa | "הכי" / "הגבוה ביותר" (most / highest) | `ORDER BY … LIMIT` or `MAX` | ties: other rows with the same top value are silently dropped | | "לכל" / "ל-" (per X, per capita) | a ratio at X's grain | numerator and denominator at different grains; integer division (`5 / 2 = 2`); division by zero | | "לפי X" (by X) | `GROUP BY X` | grouped at a different level than X | -3. **Check the risky parts with evidence**, using your tools. Run small diagnostic queries rather than guessing: - - **Filter values**: a text filter must use the value as it is stored. Check it exists (`get_column_distinct_values` for `categorical` columns, `search_column_values` for `large_categorical` / `large_unit_id` columns, or the values listed in the catalog). Check that no other stored spelling of the same entity was missed. - - **Joins**: on a one-to-many join, compare counts before and after the join; `COUNT(*)` after a fan-out counts duplicated rows, not entities. - - **Time ranges**: correct column, correct boundaries (inclusive/exclusive, whole periods), correct relative dates against today's date given above, DATE vs TIMESTAMP comparison. - - **NULLs and empty results**: 0 rows, or a suspiciously round or table-sized number, means a condition is wrong or ineffective — find which one (a count equal to the whole table's count means the filter does nothing; a count far above the table's size means a join without a proper key). - - **Anti-joins** ("X with no Y"): `NOT IN (subquery)` returns nothing when the subquery has a NULL — `NOT EXISTS` or `LEFT JOIN … IS NULL` is safe. Also check the anti-join actually matches anything: if the join keys of the two sides never match, "no Y" is true for everyone. - - **Joins that drop entities**: an `INNER JOIN` removes entities with no related rows, which is wrong for "per entity" results that should show zero. -**Judge — don't solve.** Your job is to decide whether this SQL answers the request, not to write the correct SQL. Stop investigating as soon as you can show a concrete problem with evidence; point briefly at the direction of a fix, but don't search for the full solution. Keep your checks proportionate to the risk in the SQL: a simple lookup needs little, a multi-join aggregation more. -4. **Check the interpretation choices**: each must be a reasonable reading of the request and true of the data — check the ones the answer depends on. +3. **Look at the result rows.** Do they fit the question? 0 rows, a count equal to a whole table, an anti-join ("X with no Y") that removed nothing, or a long list cut off ("only part of the result") for a "top 2" question all mean something in the SQL is wrong or ineffective. +4. **Check the risky parts by reading:** + - **Filter values**: a text filter must use the value as it is stored — compare it with the values the catalog lists for that column. + - **Joins**: the join keys should hold the same kind of values. Compare the catalog's example values of both columns: if they look different (`ORD-000123` vs `123`, `Site-7` vs `Springfield`, codes vs names), the join can't match as written. An `INNER JOIN` also drops entities with no related rows, wrong for "per entity" results that should show zero. + - **Anti-joins**: `NOT IN (subquery)` returns nothing when the subquery has a NULL — `NOT EXISTS` or `LEFT JOIN … IS NULL` is safe. + - **Ties**: for "the most / the longest / the highest", if the SQL keeps only one row (`LIMIT 1`, `ROW_NUMBER() … = 1`, `max_by`), other rows may share the top value. Dropping tied rows the user didn't ask to drop is a fail. + - **Time ranges**: correct column, whole periods, relative dates against today's date given above. +5. **Check the interpretation choices**: each must be a reasonable reading of the request and consistent with the catalog. + +**Judge — don't solve.** Decide whether this SQL answers the request; don't design the correct SQL. Point briefly at the direction of a fix. + +## When to ask for a check (rarely) + +Most reviews are decided by reading. Ask for a check only when something you can see gives a concrete reason to doubt, and only data can settle it — for example: the catalog's examples suggest the two join keys hold different kinds of values but you can't be sure, the rows look implausible and you can't tell why, a filter value doesn't appear among the catalog's listed values, or ties are plausible and the rows don't show whether they exist. + +Don't ask for a check when a join's keys look consistent in the catalog (same name and kind of values), when an assumption is a reasonable reading, or when you can decide from what you have — a mismatch you can already see is a fail, not a check. Name each check specifically ("check whether the values of `table_a.col` match `table_b.col`"), never "verify the joins". After a check, you'll see the checks you asked for and the real results of the queries the analyst ran since — decide from them. ## Verdict Call `submit_verdict` exactly once, when you are done: -- `verdict: "pass"` — the answer correctly answers the request. An assumption may choose between reasonable readings of the request; it may not drop or replace part of what was asked. An answer that leaves out or substitutes part of the request fails, even when its assumptions say so. -- `verdict: "fail"` — at least one concrete problem would make the user's answer wrong or misleading. For each problem give `problem` (what is wrong and how to fix it) and `evidence` (the query you ran and what it returned, or the exact part of the SQL / request that disagrees). Write them in Hebrew. - -Fail only for problems you can show. Style, formatting, performance, or a different-but-equivalent way to write the SQL are not problems. If you are unsure whether something is wrong, check it with a query; if you still cannot show it, it is not a problem. +- `verdict: "pass"` — the SQL correctly answers the request. An assumption may choose between reasonable readings of the request; it may not drop or replace part of what was asked. An answer that leaves out or substitutes part of the request fails, even when its assumptions say so. +- `verdict: "fail"` — at least one concrete problem would make the user's answer wrong or misleading. For each problem give `problem` (what is wrong and how to fix it) and `evidence` (the exact part of the SQL, the rows, the catalog or the request that shows it). Write them in Hebrew. +- `verdict: "needs_check"` — only as described above, with `checks`: each specific check. -Your tools are read-only. Never modify data. +Fail only for problems you can show. Style, formatting, performance, or a different-but-equivalent way to write the SQL are not problems. diff --git a/agent/src/deep_agent/tools/sql.py b/agent/src/deep_agent/tools/sql.py index 087f71d..54dc3e7 100644 --- a/agent/src/deep_agent/tools/sql.py +++ b/agent/src/deep_agent/tools/sql.py @@ -28,8 +28,13 @@ logger = logging.getLogger(__name__) -def _run_sql(sql: str, row_cap: int | None) -> str: - return _execute(sql, row_cap)[0] +def _run_sql(sql: str, row_cap: int | None, requested: int | None = None) -> str: + """Run guarded SQL; when the requested row count was reduced to the configured ceiling, say so.""" + content, payload = _execute(sql, row_cap) + if payload is None or requested is None or row_cap is None or requested <= row_cap: + return content + return ok({**payload, "notice": f"limit reduced from {requested} to {row_cap} (the configured ceiling) — " + "asking for more returns the same rows"}) def _execute(sql: str, row_cap: int | None) -> tuple[str, dict | None]: @@ -134,12 +139,13 @@ def get_sample_rows(table_name: str, limit: int = 5) -> str: table_name (str): The fully qualified exact name of the table, e.g. '"catalog"."schema"."table"'. limit (int): The number of rows to sample. Defaults to 5 (bounded by the configured sample ceiling). """ - row_cap = effective_cap(limit if limit is not None else 5, settings.DEEP_AGENT_MAX_SAMPLE_ROWS) + requested = limit if limit is not None else 5 + row_cap = effective_cap(requested, settings.DEEP_AGENT_MAX_SAMPLE_ROWS) try: sql = sql_guard.sample_rows_sql(table_name, row_cap) except sql_guard.GuardError as e: return fail(trino_errors.forbidden(str(e))) - return _run_sql(sql, row_cap) + return _run_sql(sql, row_cap, requested) @tool @@ -164,12 +170,13 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 column_name (str): The exact name of the column (plain or double-quoted; spaces and Hebrew are fine). limit (int): Maximum distinct values to return. Defaults to 50 (bounded by the configured row ceiling). """ - row_cap = effective_cap(limit if limit is not None else 50, settings.DEEP_AGENT_MAX_ROWS) + requested = limit if limit is not None else 50 + row_cap = effective_cap(requested, settings.DEEP_AGENT_MAX_ROWS) try: sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) except sql_guard.GuardError as e: return fail(trino_errors.forbidden(str(e))) - return _run_sql(sql, row_cap) + return _run_sql(sql, row_cap, requested) _VALIDATE_PREFIX = "EXPLAIN (TYPE VALIDATE) " diff --git a/agent/src/deep_agent/validator/__init__.py b/agent/src/deep_agent/validator/__init__.py index 61f84b2..a43f5ac 100644 --- a/agent/src/deep_agent/validator/__init__.py +++ b/agent/src/deep_agent/validator/__init__.py @@ -3,7 +3,7 @@ The order is: run the SQL (execute_trino_query) → have it reviewed (the `semantic-validator` subagent, through `task`) → submit it (submit_answer). The reviewer is a separate agent with a fresh context and -read-only diagnostic tools; its input is built by our code from facts — the user's own messages, the +no SQL tools — it judges by reading; its input is built by our code from facts — the user's own messages, the SQL, its recorded rows, the agent's assumptions (as claims to check), the catalog and the date — never from the agent's reasoning. It returns pass, or fail with issues and evidence; on fail the agent goes back to work, or disputes (submits the same SQL with `validation_response`, shown to the user). @@ -12,6 +12,6 @@ (or that the agent disputes); `on_demand` offers the reviewer and lets the agent decide; `off` drops it. submit_answer itself only checks the records (deep_agent.answer.middleware.SubmitApprovalMiddleware) — the judging happens before it. -- reviewer.py the reviewer agent: verdict format, read-only tools, its facts-only input, verdict records +- reviewer.py the reviewer agent: verdicts (pass / fail / needs_check), its facts-only input, verdict records - modes.py the wiring: the subagent, the "before you submit" prompt, the per-turn reset """ diff --git a/agent/src/deep_agent/validator/modes.py b/agent/src/deep_agent/validator/modes.py index 6038685..7f73fc0 100644 --- a/agent/src/deep_agent/validator/modes.py +++ b/agent/src/deep_agent/validator/modes.py @@ -22,8 +22,8 @@ # What the main agent sees about the subagent (in the `task` tool's list of subagents). _HOW_TO_SEND = ( - "It checks whether a SQL query really answers the user's request, with read-only diagnostic queries, and " - "returns JSON {verdict: pass|fail, issues: [{problem, evidence}]}. Send exactly two things in the description: " + "It reads a SQL query against the user's request and the catalog (it doesn't run queries) and returns JSON " + "{verdict: pass|fail|needs_check, issues: [{problem, evidence}], checks: [...]}. Send exactly two things in the description: " "the SQL in a ```sql block, and your interpretation choices as a list of lines starting with '- '. Nothing else " "is read: the reviewer gets the user's messages and this SQL's result rows itself." ) @@ -40,7 +40,7 @@ 1. The final SQL must have run successfully with `execute_trino_query` in this turn — check its rows. 2. Ask the `semantic-validator` to review it: `task` with subagent_type `semantic-validator`, the SQL in a ```sql block and your assumptions as `- ` lines. -3. Pass → call `submit_answer` with exactly that SQL (any change needs a new review). Fail → fix the SQL and repeat 1–2. If you are sure the reviewer is wrong, you may submit the same SQL with `validation_response` explaining why. +3. Pass → call `submit_answer` with exactly that SQL (any change needs a new review). Fail → fix the SQL and repeat 1–2; if you are sure the reviewer is wrong, you may submit the same SQL with `validation_response` explaining why. Needs check → run exactly the checks it names with `execute_trino_query`, then ask for review again (it sees their results). `submit_answer` is refused for SQL that hasn't run, or that the reviewer hasn't passed. """ diff --git a/agent/src/deep_agent/validator/reviewer.py b/agent/src/deep_agent/validator/reviewer.py index d93236e..385e9c7 100644 --- a/agent/src/deep_agent/validator/reviewer.py +++ b/agent/src/deep_agent/validator/reviewer.py @@ -1,7 +1,12 @@ """ -The reviewer agent (the `semantic-validator` subagent): a separate agent with a fresh context, read-only -diagnostic tools and a `submit_verdict` (pass / fail + issues with evidence). Its prompt is -prompts/validator.md. +The reviewer agent (the `semantic-validator` subagent): a separate agent with a fresh context that +judges by reading — it has no SQL tools and doesn't write SQL. Its prompt is prompts/validator.md. + +Verdicts (`submit_verdict`): +- pass the SQL answers the request +- fail a problem it can show from what it read (issues with evidence) +- needs_check rarely: something it can see gives a concrete reason to doubt that only data can settle; + it names the specific checks, the main agent runs them and asks for review again Independence: the agent that asks for the review writes a brief, but the reviewer never reads it as such. ReviewInputMiddleware replaces the brief with an input our code builds from facts: @@ -9,12 +14,14 @@ - the user's messages, from the thread (state `user_messages`) — never from the brief - the SQL to review and the agent's assumptions — the only two things taken from the brief (a ```sql block and a "- " list); any other text in the brief is discarded -- that SQL's result rows, from the recorded execution (state `executed_queries`) — never from the brief +- that SQL's result rows, from the recorded execution (state `executed_queries`) +- after a needs_check: the checks it asked for, and the real results of the queries the agent ran since + (from the recorded executions — never the agent's description of them) - plus, like every model call: today's date and the connection's catalog -Not given: the agent's reasoning, notes, other attempts, confidence, the user-facing explanation, -or the reviewer's own earlier verdicts. ReviewRecordMiddleware records the verdict for the reviewed -SQL in `semantic_validations`, which submit_answer checks (deep_agent.answer.middleware). +Not given: the agent's reasoning, notes, confidence, or the user-facing explanation. +ReviewRecordMiddleware records each verdict for the reviewed SQL in `semantic_validations`, which +submit_answer checks (deep_agent.answer.middleware). """ import logging @@ -35,13 +42,6 @@ from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware, DeepAgentRuntimeState from deep_agent.middleware.catalog import CatalogMiddleware from deep_agent.prompts.registry import PromptRefreshMiddleware, load_prompt -from deep_agent.tools import ( - execute_trino_query, - get_column_distinct_values, - get_column_profile, - get_sample_rows, - search_column_values, -) logger = logging.getLogger(__name__) @@ -50,24 +50,30 @@ VERDICT_TOOL = "submit_verdict" VALIDATOR_NAME = "semantic-validator" REVIEW_CONFIG = {"run_name": VALIDATOR_NAME, "tags": [VALIDATOR_NAME]} # the tag marks the reviewer's nested runs -VALIDATOR_TOOLS = [execute_trino_query, get_sample_rows, get_column_distinct_values, search_column_values, - get_column_profile] class Issue(BaseModel): problem: str = Field(description="What is wrong and how to fix it (Hebrew).") - evidence: str = Field(description="The query you ran and what it returned, or the exact part of the SQL / " - "request that disagrees (Hebrew).") + evidence: str = Field(description="The exact part of the SQL, the result rows, the catalog or the request that " + "shows it (Hebrew).") class _VerdictFields(BaseModel): - verdict: Literal["pass", "fail"] = Field(description="pass = the SQL answers the request; fail = it doesn't.") + verdict: Literal["pass", "fail", "needs_check"] = Field( + description="pass = the SQL answers the request; fail = it doesn't; needs_check = something you can see " + "gives a concrete reason to doubt that only data can settle (rare).") issues: list[Issue] = Field(default_factory=list, description="Every problem found (required for fail).") + checks: list[str] = Field( + default_factory=list, + description="For needs_check: each specific check for the analyst to run, e.g. 'check whether the values of " + "table_a.col match table_b.col'.") @model_validator(mode="after") - def _fail_needs_issues(self): + def _verdict_needs_its_details(self): if self.verdict == "fail" and not self.issues: raise ValueError("a fail verdict needs at least one issue with evidence") + if self.verdict == "needs_check" and not self.checks: + raise ValueError("a needs_check verdict needs at least one specific check") return self @@ -76,7 +82,9 @@ def _fail_needs_issues(self): __doc__="Submit your review verdict. Call this exactly once, when you are done — it ends your review.", ) -_SQL_BLOCK = re.compile(r"```sql\s*(.*?)```", re.DOTALL | re.IGNORECASE) +# A real code block: the ```sql fence starts a line and the SQL is on the lines below (an inline mention of +# "```sql block" in prose is not one). +_SQL_BLOCK = re.compile(r"^[ \t]*```sql[ \t]*\n(.*?)^[ \t]*```", re.DOTALL | re.IGNORECASE | re.MULTILINE) _BULLET = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s+(.+?)\s*$") @@ -89,21 +97,26 @@ def parse_brief(brief: str) -> tuple[str | None, list[str]]: return sql or None, assumptions -def _result_section(record: dict[str, Any] | None) -> str: - if record is None: - return "This SQL has not run successfully in this turn — run it yourself to see the result." - if record.get("truncated"): - note = " (only part of the result: more rows exist)" - else: - note = "" +def _rows_section(record: dict[str, Any]) -> str: + note = " (only part of the result: more rows exist)" if record.get("truncated") else "" lines = [f"Columns: {record['columns']}", f"Rows returned: {record['row_count']}{note}"] lines += [str(row) for row in record["rows"]] return "\n".join(lines) +def _pending_checks(records: list[dict[str, Any]], executions: list[dict[str, Any]]) -> tuple[list[str], list[dict]]: + """The checks asked for in the latest needs_check review this turn, and the executions recorded since it.""" + asked = [r for r in records if r.get("verdict") == "needs_check"] + if not asked: + return [], [] + latest = asked[-1] + return latest.get("checks") or [], executions[latest.get("after_execution", len(executions)):] + + def review_request(user_messages: list[str], sql: str | None, assumptions: list[str], - executed: list[dict[str, Any]]) -> str: - """The reviewer's input, built from facts: the user's own messages, the SQL, its assumptions, its real rows.""" + executed: list[dict[str, Any]], records: list[dict[str, Any]] | None = None) -> str: + """The reviewer's input, built from facts: the user's own messages, the SQL, its assumptions, its real rows, + and — after a needs_check — the checks asked for and the real results of the queries run since.""" parts = [] if user_messages[:-1]: parts.append("## Earlier user messages (context)\n" + "\n".join(f"- {text}" for text in user_messages[:-1])) @@ -115,7 +128,16 @@ def review_request(user_messages: list[str], sql: str | None, assumptions: list[ parts.append(f"## SQL to review\n```sql\n{sql}\n```") listed = "\n".join(f"- {a}" for a in assumptions) or "(none stated)" parts.append("## The analyst's interpretation choices — claims to check, not facts\n" + listed) - parts.append(f"## Result of this SQL\n{_result_section(match_execution(sql, executed))}") + record = match_execution(sql, executed) + parts.append("## Result of this SQL\n" + (_rows_section(record) if record else "This SQL has not run in this turn.")) + checks, since = _pending_checks(records or [], executed) + if checks: + parts.append("## Checks you asked for in your previous review\n" + "\n".join(f"- {c}" for c in checks)) + if since: + ran = [f"```sql\n{r['submitted_sql']}\n```\n{_rows_section(r)}" for r in since] + parts.append("## Queries the analyst ran since, with their real results\n" + "\n\n".join(ran)) + else: + parts.append("## Queries the analyst ran since\n(none)") return "\n\n".join(parts) @@ -134,7 +156,8 @@ def _with_review_input(self, request: ModelRequest) -> ModelRequest: return request state = request.state or {} sql, assumptions = parse_brief(messages[0].text) - text = review_request(list(state.get("user_messages") or []), sql, assumptions, _turn_executions(state)) + text = review_request(list(state.get("user_messages") or []), sql, assumptions, _turn_executions(state), + list(state.get("semantic_validations") or [])) messages[0] = HumanMessage(text, id=messages[0].id) return request.override(messages=messages) @@ -150,7 +173,7 @@ async def awrap_model_call( def review_record(verdict: Any, **fields: Any) -> dict[str, Any]: if verdict is None: return {"id": uuid.uuid4().hex, "verdict": "error", "issues": [], **fields} - return {"id": uuid.uuid4().hex, "verdict": verdict.verdict, + return {"id": uuid.uuid4().hex, "verdict": verdict.verdict, "checks": list(verdict.checks), "issues": [issue.model_dump() for issue in verdict.issues], **fields} @@ -164,18 +187,19 @@ def after_agent(self, state, runtime) -> dict[str, Any] | None: sql, _ = parse_brief(messages[0].text if messages else "") verdict = state.get("structured_response") reason = None if verdict else "the reviewer ended without a verdict" - return {"semantic_validations": [review_record(verdict, sql=normalize_sql(sql), reason=reason)]} + return {"semantic_validations": [review_record(verdict, sql=normalize_sql(sql), reason=reason, + after_execution=len(_turn_executions(state)))]} async def aafter_agent(self, state, runtime) -> dict[str, Any] | None: return self.after_agent(state, runtime) def build_validator(model: BaseChatModel): - """The reviewer agent: facts-only input, catalog + date in context, read-only tools, verdict via submit_verdict.""" + """The reviewer agent: facts-only input, catalog + date in context, no SQL tools, verdict via submit_verdict.""" prompt = load_prompt("validator").text agent = create_agent( model=model, - tools=VALIDATOR_TOOLS, + tools=[], # it judges by reading; checks that need data are run by the main agent (needs_check) system_prompt=prompt, middleware=[ ReviewInputMiddleware(), # first: the date is then added to the built input, not to the brief diff --git a/agent/tests/deep_agent/test_service.py b/agent/tests/deep_agent/test_service.py index df6e220..1c11e5d 100644 --- a/agent/tests/deep_agent/test_service.py +++ b/agent/tests/deep_agent/test_service.py @@ -230,7 +230,7 @@ async def test_threads_survive_a_restart_with_postgres(scripted_model, monkeypat @pytest.mark.asyncio -async def test_reviewer_tools_are_labelled_in_the_stream(scripted_model, published): +async def test_review_appears_in_the_stream(scripted_model, published): brief = f"```sql\n{SQL}\n```" main = scripted_model( AIMessage("", tool_calls=[{"name": "execute_trino_query", "args": {"sql": SQL}, "id": "e1"}]), @@ -238,11 +238,10 @@ async def test_reviewer_tools_are_labelled_in_the_stream(scripted_model, publish "id": "r1"}]), _answer()) reviewer = scripted_model( - AIMessage("", tool_calls=[{"name": "get_sample_rows", "args": {"table_name": "orders"}, "id": "x1"}]), AIMessage("", tool_calls=[{"name": "submit_verdict", "args": {"verdict": "pass"}, "id": "v1"}]), ) agent = create_deep_agent(model=main, semantic_validation="always", validator_model=reviewer) with patch.object(sql_tools, "execute_query_sync", return_value=OK): r = await run_deep_chat(connection_id=89, query="q", thread_id="deep-t6", agent=agent) - assert r["execution_path"] == ["deep:execute_trino_query", "deep:task", "deep:review:get_sample_rows"] + assert r["execution_path"] == ["deep:execute_trino_query", "deep:task"] # the reviewer runs no tools assert r["semantic_validation"]["verdict"] == "passed" diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py index aa112d7..e909929 100644 --- a/agent/tests/deep_agent/test_trino_tools.py +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -128,3 +128,13 @@ def test_validate_runs_explain_for_reads(trino): trino.return_value = _ok(0) assert json.loads(tools.validate_sql.invoke({"sql": "SELECT 1"}))["data"] == {"valid": True} assert trino.call_args.args[0] == "EXPLAIN (TYPE VALIDATE) SELECT 1" + + +def test_sample_rows_says_when_the_limit_was_reduced(monkeypatch): + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_SAMPLE_ROWS", 10) + res = TrinoExecutionResult(success=True, rows=[[i] for i in range(11)], columns=["a"], row_count=11, query_id="q") + with patch.object(sql_tools, "execute_query_sync", return_value=res): + reduced = json.loads(tools.get_sample_rows.invoke({"table_name": "t", "limit": 200})) + normal = json.loads(tools.get_sample_rows.invoke({"table_name": "t", "limit": 5})) + assert "limit reduced from 200 to 10" in reduced["data"]["notice"] and reduced["data"]["row_count"] == 10 + assert "notice" not in normal["data"] diff --git a/agent/tests/deep_agent/test_validator.py b/agent/tests/deep_agent/test_validator.py index 7d93c29..c73a507 100644 --- a/agent/tests/deep_agent/test_validator.py +++ b/agent/tests/deep_agent/test_validator.py @@ -22,7 +22,7 @@ from deep_agent.answer.verification import normalize_sql, validation_summary from deep_agent.observability import run_metrics from deep_agent.tools import sql as sql_tools -from deep_agent.validator.reviewer import VALIDATOR_TOOLS, SubmitVerdict, parse_brief, review_request +from deep_agent.validator.reviewer import SubmitVerdict, parse_brief, review_request SQL = "SELECT COUNT(*) AS n FROM orders WHERE status = 'shipped'" FIXED = "SELECT COUNT(DISTINCT order_id) AS n FROM orders WHERE status = 'shipped'" @@ -241,7 +241,7 @@ def test_review_request_marks_earlier_messages_and_missing_runs(): text = review_request(["כמה טיסות יצאו מצרפת?", "ומאיטליה?"], SQL, [], []) assert "Earlier user messages" in text and "כמה טיסות יצאו מצרפת?" in text assert "Current user request\nומאיטליה?" in text - assert "has not run successfully in this turn" in text and "(none stated)" in text + assert "has not run in this turn" in text and "(none stated)" in text @pytest.mark.asyncio @@ -259,12 +259,6 @@ async def test_follow_up_turn_gives_the_reviewer_the_earlier_question(scripted_m assert state["final_result"]["semantic_validation"]["rounds"] == 1 # counted per turn -def test_reviewer_tools_are_read_only_diagnostics(): - assert {t.name for t in VALIDATOR_TOOLS} == { - "execute_trino_query", "get_sample_rows", "get_column_distinct_values", "search_column_values", - "get_column_profile"} - - def test_fail_verdict_needs_evidence(): with pytest.raises(ValueError): SubmitVerdict(verdict="fail", issues=[]) @@ -347,3 +341,56 @@ async def test_modes_offer_the_reviewer(scripted_model, mode, offered): task_tool = next((t for t in main.bound_tool_names[0] if t == "task"), None) assert task_tool == "task" # general-purpose is always there assert ("semantic-validator" in _texts(main.seen[0])) is offered + + +def _needs_check(checks, call_id="v1"): + return _call("submit_verdict", {"verdict": "needs_check", "checks": checks}, call_id) + + +CHECK = "SELECT COUNT(DISTINCT order_id) FROM orders" + + +@pytest.mark.asyncio +async def test_needs_check_sends_the_agent_to_run_it_and_the_reviewer_sees_the_result(scripted_model): + main = scripted_model(_execute(), _review(), _submit(), _execute(CHECK, "e2"), _review(call_id="r2"), + _submit(call_id="s2")) + reviewer = scripted_model(_needs_check(["check whether order_id repeats across rows"]), + _verdict("pass", call_id="v2")) + state = await _run(main, reviewer) + + refusal = _submit_results(state)[0] + assert refusal.startswith("Not submitted: the semantic-validator asks for these checks") + assert "order_id repeats" in refusal + second = _texts(reviewer.seen[1]) + assert "Checks you asked for in your previous review" in second and "order_id repeats" in second + assert CHECK in second and "[42]" in second # the check's real recorded result + final = state["final_result"] + assert final["semantic_validation"]["verdict"] == "passed" and final["semantic_validation"]["rounds"] == 2 + + +@pytest.mark.asyncio +async def test_the_reviewer_has_no_sql_tools(scripted_model): + reviewer = scripted_model(_verdict("pass")) + await _run(scripted_model(_execute(), _review(), _submit()), reviewer) + assert reviewer.bound_tool_names[0] == ["submit_verdict"] + + +def test_needs_check_requires_named_checks(): + with pytest.raises(ValueError): + SubmitVerdict(verdict="needs_check") + assert SubmitVerdict(verdict="needs_check", checks=["x"]).checks == ["x"] + + +def test_pending_checks_without_new_queries_are_shown_as_none(): + records = [{"verdict": "needs_check", "checks": ["c1"], "after_execution": 1}] + executed = [{"submitted_sql": SQL, "executed_sql": SQL, "columns": ["n"], "rows": [[42]], "row_count": 1, + "truncated": False}] + text = review_request([QUESTION], SQL, [], executed, records) + assert "- c1" in text and "Queries the analyst ran since\n(none)" in text + + + +def test_parse_brief_ignores_an_inline_mention_of_a_sql_block(): + brief = ("Provide the SQL in a ```sql block``` and list assumptions. Also ```sql``` here.\n" + "```sql\nSELECT 1\n```\n- a") + assert parse_brief(brief) == ("SELECT 1", ["a"]) From 4c32b87626641da42909b97860bec5c6fef707c2 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 2 Nov 2026 10:56:42 +0200 Subject: [PATCH 28/37] feat(deep-agent): the reviewer gets code-detected notes on the answer (single row, cut-off, empty) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit General rules buried in the reviewer's prompt (ties, cut-off lists) were sometimes not applied. Our code now detects the facts and puts them next to the SQL as specific cues: SQL that keeps one row (LIMIT 1 / row_number() / max_by → check ties), a cut-off result, an empty result. Two prompt lines: read the request's exact wording before failing; an extra harmless column is not a problem. On the 15-question set: a new real catch (DENSE_RANK over five levels), no wrong fails (was 2), 24–80s per question (was 33–117s). Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/prompts/validator.md | 4 +-- agent/src/deep_agent/validator/reviewer.py | 35 ++++++++++++++++++++++ agent/tests/deep_agent/test_validator.py | 28 +++++++++++++++++ 3 files changed, 65 insertions(+), 2 deletions(-) diff --git a/agent/src/deep_agent/prompts/validator.md b/agent/src/deep_agent/prompts/validator.md index b6e79c8..9571f06 100644 --- a/agent/src/deep_agent/prompts/validator.md +++ b/agent/src/deep_agent/prompts/validator.md @@ -4,7 +4,7 @@ You judge by reading. You don't run queries and you don't write SQL. The connect ## How to review -1. **Restate the request.** In one sentence, what exactly is the user asking for? What should one output row represent (the grain)? Which conditions did the user state (entities, values, places, time ranges)? If there are several user messages, the last one is the current question and the earlier ones are its context (a follow-up such as "and from Italy?" keeps the earlier conditions and changes one). +1. **Restate the request.** Read its exact wording before deciding the SQL got it wrong — e.g. "the last 30 days in the data" is relative to the data, not to today. In one sentence, what exactly is the user asking for? What should one output row represent (the grain)? Which conditions did the user state (entities, values, places, time ranges)? If there are several user messages, the last one is the current question and the earlier ones are its context (a follow-up such as "and from Italy?" keeps the earlier conditions and changes one). 2. **Read the SQL back in plain language** and compare it with the request, condition by condition: - every condition the user stated is in the SQL, on the right column (check the catalog's column descriptions); - the SQL adds no condition the user did not ask for (unless it is stated in the assumptions and reasonable); @@ -46,4 +46,4 @@ Call `submit_verdict` exactly once, when you are done: - `verdict: "fail"` — at least one concrete problem would make the user's answer wrong or misleading. For each problem give `problem` (what is wrong and how to fix it) and `evidence` (the exact part of the SQL, the rows, the catalog or the request that shows it). Write them in Hebrew. - `verdict: "needs_check"` — only as described above, with `checks`: each specific check. -Fail only for problems you can show. Style, formatting, performance, or a different-but-equivalent way to write the SQL are not problems. +Fail only for problems you can show. Style, formatting, performance, a different-but-equivalent way to write the SQL, or an extra column that doesn't change or mislead the answer are not problems. The "Notes on this answer" are facts our code detected — act on them. diff --git a/agent/src/deep_agent/validator/reviewer.py b/agent/src/deep_agent/validator/reviewer.py index 385e9c7..97ede6d 100644 --- a/agent/src/deep_agent/validator/reviewer.py +++ b/agent/src/deep_agent/validator/reviewer.py @@ -35,6 +35,9 @@ from langchain_core.language_models import BaseChatModel from langchain_core.messages import HumanMessage from pydantic import BaseModel, Field, create_model, model_validator +import sqlglot +from sqlglot import exp +from sqlglot.errors import SqlglotError from deep_agent.answer.middleware import submit_fallback from deep_agent.answer.schema import submission_strategy @@ -104,6 +107,35 @@ def _rows_section(record: dict[str, Any]) -> str: return "\n".join(lines) +def answer_notes(sql: str, record: dict[str, Any] | None) -> list[str]: + """Facts our code can see about this answer, put in front of the reviewer so a general rule becomes a + specific cue: SQL that keeps a single row (ties), a cut-off result, an empty result.""" + notes = [] + try: + tree = sqlglot.parse_one(sql, read="trino") + except SqlglotError: + tree = None + if tree is not None: + limit = tree.args.get("limit") + single = [] + if isinstance(limit, exp.Limit) and limit.expression.sql() == "1": + single.append("it ends with LIMIT 1") + if any(isinstance(w.this, exp.RowNumber) for w in tree.find_all(exp.Window)): + single.append("it picks rows with row_number(), which keeps one row per group even when values tie") + if any(True for _ in tree.find_all(exp.ArgMax, exp.ArgMin)): + single.append("it uses max_by / min_by, which return one value even when several tie") + if single: + notes.append("This SQL keeps a single row: " + "; ".join(single) + ". If the request asks for " + "'the most / the longest / the highest', check whether other rows share the top value — " + "dropping ties the user didn't ask to drop is a fail.") + if record is not None and record.get("truncated"): + notes.append(f"The result was cut off at {record['row_count']} rows — more rows exist. For a request that " + "expects a short list (a top N, a few items per group), the SQL returns more than was asked.") + if record is not None and record.get("row_count") == 0: + notes.append("The result is empty (0 rows) — check whether a condition or a join makes it impossible.") + return notes + + def _pending_checks(records: list[dict[str, Any]], executions: list[dict[str, Any]]) -> tuple[list[str], list[dict]]: """The checks asked for in the latest needs_check review this turn, and the executions recorded since it.""" asked = [r for r in records if r.get("verdict") == "needs_check"] @@ -129,6 +161,9 @@ def review_request(user_messages: list[str], sql: str | None, assumptions: list[ listed = "\n".join(f"- {a}" for a in assumptions) or "(none stated)" parts.append("## The analyst's interpretation choices — claims to check, not facts\n" + listed) record = match_execution(sql, executed) + notes = answer_notes(sql, record) + if notes: + parts.append("## Notes on this answer (facts detected by code)\n" + "\n".join(f"- {n}" for n in notes)) parts.append("## Result of this SQL\n" + (_rows_section(record) if record else "This SQL has not run in this turn.")) checks, since = _pending_checks(records or [], executed) if checks: diff --git a/agent/tests/deep_agent/test_validator.py b/agent/tests/deep_agent/test_validator.py index c73a507..24dd8c7 100644 --- a/agent/tests/deep_agent/test_validator.py +++ b/agent/tests/deep_agent/test_validator.py @@ -394,3 +394,31 @@ def test_parse_brief_ignores_an_inline_mention_of_a_sql_block(): brief = ("Provide the SQL in a ```sql block``` and list assumptions. Also ```sql``` here.\n" "```sql\nSELECT 1\n```\n- a") assert parse_brief(brief) == ("SELECT 1", ["a"]) + + +@pytest.mark.parametrize("sql, expected", [ + ("SELECT a FROM t ORDER BY b DESC LIMIT 1", "it ends with LIMIT 1"), + ("WITH r AS (SELECT a, row_number() OVER (ORDER BY b DESC) rn FROM t) SELECT a FROM r WHERE rn = 1", "row_number()"), + ("SELECT max_by(a, b) FROM t", "max_by"), +]) +def test_notes_flag_sql_that_keeps_a_single_row(sql, expected): + from deep_agent.validator.reviewer import answer_notes + + notes = answer_notes(sql, None) + assert len(notes) == 1 and expected in notes[0] and "ties" in notes[0] + + +def test_notes_flag_cut_off_and_empty_results_and_stay_quiet_otherwise(): + from deep_agent.validator.reviewer import answer_notes + + rec = {"columns": ["a"], "rows": [[1]] * 100, "row_count": 100, "truncated": True} + assert "cut off at 100 rows" in answer_notes("SELECT a FROM t", rec)[0] + assert "empty (0 rows)" in answer_notes("SELECT a FROM t", {**rec, "rows": [], "row_count": 0, "truncated": False})[0] + assert answer_notes("SELECT a FROM t LIMIT 10", {**rec, "row_count": 3, "truncated": False}) == [] + + +def test_notes_reach_the_reviewer(): + executed = [{"submitted_sql": "SELECT a FROM t ORDER BY b DESC LIMIT 1", "executed_sql": "x", "columns": ["a"], + "rows": [[1]], "row_count": 1, "truncated": False}] + text = review_request([QUESTION], "SELECT a FROM t ORDER BY b DESC LIMIT 1", [], executed) + assert "## Notes on this answer" in text and "LIMIT 1" in text From cbf217f99da9e7538cf48ce619e85318c7f3c4dd Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 2 Nov 2026 11:16:46 +0200 Subject: [PATCH 29/37] chore: TRINO_TIMEZONE off by default (machine zone); time guidance no longer claims the session zone The Israel session-zone pin (#43) lives in shared core and also changed the legacy agent and the eval service. It is now opt-in (TRINO_TIMEZONE=Asia/Jerusalem); unset keeps the Trino client's own behaviour. The deep agent's guidance keeps the same advice (plain literals, no zones, no hand conversion) without stating what the session zone is. Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/prompts/system.md | 2 +- agent/src/deep_agent/skills/temporal-analyst/SKILL.md | 6 +++--- core/src/core/config.py | 5 +++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index 007c05f..2cbd9c8 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -84,7 +84,7 @@ The user's word is almost never the stored string — the value may be spelled d - **Per-entity ratios**: mind the granularity of numerator vs denominator — "orders per resident" is `COUNT(orders) / SUM(population)`, not `AVG(count_per_row)`. When the denominator comes from another table, aggregate each side in its own CTE, then join and divide. - **Set operations**: prefer `UNION ALL`; `UNION` adds an expensive distributed de-duplication — use it only when de-duplication is required. - **Arrays**: membership `contains(arr, 'v')`; expand with `CROSS JOIN UNNEST(arr) AS t(element)`. -- **Time filters**: a half-open range on the raw column (`col >= start AND col < end`), never a function around the filtered column. Times are Israel time and so is the session: write plain literals (`TIMESTAMP '2024-07-01 00:00:00'`, `DATE '2024-07-01'`) — don't add a time zone and don't convert to UTC yourself. +- **Time filters**: a half-open range on the raw column (`col >= start AND col < end`), never a function around the filtered column. Write plain literals (`TIMESTAMP '2024-07-01 00:00:00'`, `DATE '2024-07-01'`) — don't add a time zone and don't convert time zones yourself. - **Coordinates**: `ST_Point(lon, lat)` and WKT are longitude first; `great_circle_distance(lat1, lon1, lat2, lon2)` is latitude first and returns km. Distances and areas on plain geometry are in degrees — wrap in `to_spherical_geography(...)` for metres. Details in the `spatial-analyst` skill. - **When several logic paths seem plausible** (INNER vs LEFT JOIN, different grouping), run 2–3 variants with `LIMIT 10` and compare before choosing — don't guess. diff --git a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md index 92bd3d2..77d5f23 100644 --- a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md +++ b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md @@ -119,9 +119,9 @@ ORDER BY 1 ## Time zones -Times are Israel time, and so is the session time zone: plain literals (`TIMESTAMP '2024-07-01 00:00:00'`), -`current_date` and `current_timestamp` are already Israel time. Don't add zones to literals and don't convert to UTC -by hand. (Only if a column is a naive `timestamp` documented as UTC: `with_timezone(col, 'UTC')` before comparing.) +Write plain literals (`TIMESTAMP '2024-07-01 00:00:00'`) and use `current_date` / `current_timestamp` as they are. +Don't add zones to literals and don't convert time zones by hand. (Only if a column is a naive `timestamp` documented as +UTC: `with_timezone(col, 'UTC')` before comparing.) --- diff --git a/core/src/core/config.py b/core/src/core/config.py index afa03c9..ccf47c5 100644 --- a/core/src/core/config.py +++ b/core/src/core/config.py @@ -17,8 +17,9 @@ class CoreSettings(BaseSettings): TRINO_SCHEMA: str = "simple_retail" TRINO_HTTP_SCHEME: str = "http" TRINO_REQUEST_TIMEOUT: float = 30.0 - # Session time zone for current_date / now(); otherwise the client sends the machine's zone (UTC in Docker). - TRINO_TIMEZONE: str = "Asia/Jerusalem" + # Optional session time zone for current_date / now() and plain timestamp literals, e.g. "Asia/Jerusalem". + # Unset (default): the Trino client's own behaviour — the machine's zone (UTC in Docker). + TRINO_TIMEZONE: str | None = None TRINO_ENABLED: bool = True TRINO_VERIFY: bool | str = False TRINO_CERT_PATH: str | None = None From 693b8e9819e4b00d1403651ffae219e2da630a62 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 8 Nov 2026 14:21:20 +0200 Subject: [PATCH 30/37] fix(sql-guard): allow SQL comments; ignore them when matching submitted vs executed SQL The comment ban came from the Utils-Server port. The guard checks the parsed AST (single read statement, no writes/table functions), so a comment cannot hide anything; rejecting it only cost the agent a failed tool call. The prompt still asks for no comments. (PR #67 review) Co-Authored-By: Claude Opus 5.5 --- agent/src/agent/utils/sql_guard.py | 10 ---------- agent/src/deep_agent/answer/verification.py | 4 ++-- agent/src/deep_agent/tools/sql.py | 2 +- agent/tests/deep_agent/test_answer.py | 1 + agent/tests/deep_agent/test_trino_tools.py | 2 +- agent/tests/test_sql_guard.py | 19 +++++++++++++++++-- 6 files changed, 22 insertions(+), 16 deletions(-) diff --git a/agent/src/agent/utils/sql_guard.py b/agent/src/agent/utils/sql_guard.py index d19fd50..66587a6 100644 --- a/agent/src/agent/utils/sql_guard.py +++ b/agent/src/agent/utils/sql_guard.py @@ -12,7 +12,6 @@ import sqlglot from sqlglot import exp from sqlglot.errors import SqlglotError -from sqlglot.tokens import Tokenizer _DIALECT = "trino" _SHOW = re.compile( @@ -45,13 +44,6 @@ def effective_cap(requested: int | None, ceiling: int | None) -> int | None: return min(requested, ceiling) if ceiling is not None else requested -def _has_comments(sql: str) -> bool: - try: - return any(token.comments for token in Tokenizer(dialect=_DIALECT).tokenize(sql)) - except SqlglotError: - return "--" in sql or "/*" in sql - - def _reject_pass_through(tree: exp.Expression) -> None: # TABLE(catalog.system.query(query => '...')) runs arbitrary SQL on the underlying source. for table in tree.find_all(exp.Table): @@ -94,8 +86,6 @@ def parse_read_statement(sql: str) -> exp.Expression | None: """ if not sql or not sql.strip(): raise GuardError("empty SQL") - if _has_comments(sql): - raise GuardError("SQL comments are not allowed") try: statements = [s for s in sqlglot.parse(sql, read=_DIALECT) if s is not None] except SqlglotError as e: diff --git a/agent/src/deep_agent/answer/verification.py b/agent/src/deep_agent/answer/verification.py index bebdf4b..24c1ad4 100644 --- a/agent/src/deep_agent/answer/verification.py +++ b/agent/src/deep_agent/answer/verification.py @@ -35,12 +35,12 @@ def normalize_sql(sql: str | None) -> str | None: - """Canonical form for comparing two SQL strings (whitespace, keyword case, trailing ';', fences).""" + """Canonical form for comparing two SQL strings (whitespace, keyword case, comments, trailing ';', fences).""" if not sql: return None cleaned = clean_sql(sql) try: - return sqlglot.parse_one(cleaned, read="trino").sql(dialect="trino") + return sqlglot.parse_one(cleaned, read="trino").sql(dialect="trino", comments=False) except SqlglotError: return " ".join(cleaned.split()) diff --git a/agent/src/deep_agent/tools/sql.py b/agent/src/deep_agent/tools/sql.py index 54dc3e7..76baaf0 100644 --- a/agent/src/deep_agent/tools/sql.py +++ b/agent/src/deep_agent/tools/sql.py @@ -103,7 +103,7 @@ def execute_trino_query(sql: str, limit: int | None = None, runtime: Runtime = N INSUFFICIENT_RESOURCES, INTERNAL_ERROR and EXTERNAL come from the cluster or the source database - error.message: Trino's message; error.location: {line, column} of the offending token Two errors don't come from Trino: FORBIDDEN_STATEMENT (rejected before reaching Trino — rewrite - as a single read-only query without comments) and CONNECTION_ERROR (Trino could not be reached). + as a single read-only query) and CONNECTION_ERROR (Trino could not be reached). Args: sql (str): The exact Trino SQL query string to execute. Markdown fences and trailing diff --git a/agent/tests/deep_agent/test_answer.py b/agent/tests/deep_agent/test_answer.py index 20ccf56..84cb925 100644 --- a/agent/tests/deep_agent/test_answer.py +++ b/agent/tests/deep_agent/test_answer.py @@ -109,6 +109,7 @@ def test_normalize_sql_equivalence(): assert normalize_sql(EXECUTED) == normalize_sql(RESTATED) assert normalize_sql("```sql\nSELECT 1;\n```") == normalize_sql("select 1") assert normalize_sql("SELECT 1") != normalize_sql("SELECT 2") + assert normalize_sql("SELECT a -- pick a\nFROM t") == normalize_sql("SELECT /* other */ a FROM t") def test_verify_without_structured_answer(): diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py index e909929..82ab81e 100644 --- a/agent/tests/deep_agent/test_trino_tools.py +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -20,7 +20,7 @@ def trino(): yield mock -@pytest.mark.parametrize("sql", ["DROP TABLE t", "DELETE FROM t", "SELECT 1; DROP TABLE t", "SELECT 1 -- x"]) +@pytest.mark.parametrize("sql", ["DROP TABLE t", "DELETE FROM t", "SELECT 1; DROP TABLE t", "SELECT 1 -- x\n; DROP TABLE t"]) def test_forbidden_sql_never_reaches_trino(trino, sql): out = json.loads(tools.execute_trino_query.invoke({"sql": sql})) assert out["ok"] is False diff --git a/agent/tests/test_sql_guard.py b/agent/tests/test_sql_guard.py index 9ba9ae4..57af282 100644 --- a/agent/tests/test_sql_guard.py +++ b/agent/tests/test_sql_guard.py @@ -26,8 +26,8 @@ def _outer_limit(sql: str) -> int | None: "SELECT 1; DROP TABLE t", "SELECT 1; SELECT 2", "SELECT * FROM TABLE(postgres.system.query(query => 'DELETE FROM t'))", - "SELECT 1 -- sneaky comment", - "SELECT /* hidden */ 1", + "SELECT 1 -- note\n; DROP TABLE t", + "SHOW TABLES -- note\n; DROP TABLE t", "", " ", ]) @@ -101,6 +101,21 @@ def test_no_cap_still_rejects_writes(): prepare("DELETE FROM t", None) +@pytest.mark.parametrize("sql", [ + "SELECT a -- pick a\nFROM t", + "SELECT /* note */ a FROM t", + "SHOW TABLES FROM postgres.public -- note", +]) +def test_comments_are_allowed(sql): + prepare(sql, 10) + + +def test_comments_survive_the_limit_rewrite(): + guarded = prepare("SELECT a /* pick a */ FROM t LIMIT 5000", 10) + assert _outer_limit(guarded.sql) == 11 + assert "pick a" in guarded.sql + + def test_string_literal_with_dashes_is_not_a_comment(): guarded = prepare("SELECT * FROM t WHERE code = 'a--b'", 10) assert "'a--b'" in guarded.sql From 12631f99499b7a222d7ac8f55eb430913fd214f8 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 8 Nov 2026 14:43:24 +0200 Subject: [PATCH 31/37] fix(deep-agent): distinct values follow only their own limit, not the query row ceiling get_column_distinct_values borrowed DEEP_AGENT_MAX_ROWS, so asking for 200 values silently became 100. It now returns up to the requested limit (default 50) and reports truncated when more exist. (PR #67 review) Co-Authored-By: Claude Opus 5.5 --- agent/src/agent/config.py | 2 +- agent/src/deep_agent/tools/sql.py | 7 +++---- agent/tests/deep_agent/test_trino_tools.py | 9 +++++++++ 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 5819c11..21803d0 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -48,7 +48,7 @@ class AgentSettings(BaseSettings): # ── Deep Agent ──────────────────────────────────────────────────────────── DEEP_AGENT_SKILLS_DIR: str | None = None # Override packaged skills dir (//SKILL.md) # Row ceilings for the deep agent's SQL tools. Set to "none" (or empty) to disable the ceiling. - DEEP_AGENT_MAX_ROWS: int | None = Field(default=100, gt=0) # execute_trino_query / get_column_distinct_values + DEEP_AGENT_MAX_ROWS: int | None = Field(default=100, gt=0) # execute_trino_query DEEP_AGENT_MAX_SAMPLE_ROWS: int | None = Field(default=10, gt=0) # get_sample_rows DEEP_AGENT_TRACING_ENABLED: bool = True # Langfuse callbacks, span metadata and run scores DEEP_AGENT_CLARIFICATIONS_ENABLED: bool = False # let the model ask a clarifying question instead of answering diff --git a/agent/src/deep_agent/tools/sql.py b/agent/src/deep_agent/tools/sql.py index 76baaf0..db7415e 100644 --- a/agent/src/deep_agent/tools/sql.py +++ b/agent/src/deep_agent/tools/sql.py @@ -168,15 +168,14 @@ def get_column_distinct_values(table_name: str, column_name: str, limit: int = 5 Args: table_name (str): The fully qualified exact name of the table. column_name (str): The exact name of the column (plain or double-quoted; spaces and Hebrew are fine). - limit (int): Maximum distinct values to return. Defaults to 50 (bounded by the configured row ceiling). + limit (int): Maximum distinct values to return. Defaults to 50; data.truncated is true when more exist. """ - requested = limit if limit is not None else 50 - row_cap = effective_cap(requested, settings.DEEP_AGENT_MAX_ROWS) + row_cap = max(1, int(limit)) if limit is not None else 50 try: sql = sql_guard.distinct_values_sql(table_name, column_name, row_cap) except sql_guard.GuardError as e: return fail(trino_errors.forbidden(str(e))) - return _run_sql(sql, row_cap, requested) + return _run_sql(sql, row_cap) _VALIDATE_PREFIX = "EXPLAIN (TYPE VALIDATE) " diff --git a/agent/tests/deep_agent/test_trino_tools.py b/agent/tests/deep_agent/test_trino_tools.py index 82ab81e..78e4430 100644 --- a/agent/tests/deep_agent/test_trino_tools.py +++ b/agent/tests/deep_agent/test_trino_tools.py @@ -117,6 +117,15 @@ def test_distinct_values_quotes_hebrew_column(trino): assert trino.call_args.args[0] == 'SELECT DISTINCT "שם עיר" FROM postgres.public.t LIMIT 21' +def test_distinct_values_ignore_the_row_ceiling(trino, monkeypatch): + monkeypatch.setattr(sql_tools.settings, "DEEP_AGENT_MAX_ROWS", 100) + trino.return_value = _ok(301) + out = json.loads(tools.get_column_distinct_values.invoke({"table_name": "t", "column_name": "c", "limit": 300})) + assert trino.call_args.args[0].endswith("LIMIT 301") + assert out["data"]["row_count"] == 300 and out["data"]["truncated"] is True + assert "notice" not in out["data"] + + def test_validate_rejects_writes_without_calling_trino(trino): out = json.loads(tools.validate_sql.invoke({"sql": "DELETE FROM t"})) assert out["ok"] is False From 8e74b9c6dd4008c8e7d5e99102c8850aab80a3cc Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 8 Nov 2026 15:00:52 +0200 Subject: [PATCH 32/37] refactor(deep-agent): AnswerVerificationMiddleware takes has_reviewer (it reports on_demand reviews too) The parameter was named review_required but receives has_reviewer, so it read as if on_demand reviews were dropped from final_result. Test that a failed on_demand review still reaches the user. (PR #67 review) Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/answer/middleware.py | 9 +++++---- agent/tests/deep_agent/test_validator.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/agent/src/deep_agent/answer/middleware.py b/agent/src/deep_agent/answer/middleware.py index 0a9e793..81ed9e4 100644 --- a/agent/src/deep_agent/answer/middleware.py +++ b/agent/src/deep_agent/answer/middleware.py @@ -234,12 +234,13 @@ class AnswerVerificationMiddleware(AgentMiddleware): after_agent keeps the answer only as plain data in final_result and drops the pydantic object: checkpoints can't restore the dynamically built `submit_answer` class. - review_required: whether final_result gets a review summary (with review off it is None). + has_reviewer: whether final_result gets a review summary — the reviewer is available ("always" or + "on_demand"); with review off it is None. """ - def __init__(self, review_required: bool = False) -> None: + def __init__(self, has_reviewer: bool = False) -> None: super().__init__() - self.review_required = review_required + self.has_reviewer = has_reviewer @hook_config(can_jump_to=["model"]) def after_model(self, state, runtime) -> dict[str, Any] | None: @@ -264,7 +265,7 @@ def after_agent(self, state, runtime) -> dict[str, Any] | None: final["recovered_from_text"] = any( (getattr(m, "additional_kwargs", None) or {}).get(RECOVERED_FLAG) for m in current_turn(state.get("messages") or []) ) - records = state.get("semantic_validations") or [] if self.review_required else None + records = state.get("semantic_validations") or [] if self.has_reviewer else None final["semantic_validation"] = validation_summary(records, final.get("sql")) return {"final_result": final, "structured_response": None} diff --git a/agent/tests/deep_agent/test_validator.py b/agent/tests/deep_agent/test_validator.py index 24dd8c7..470c9b4 100644 --- a/agent/tests/deep_agent/test_validator.py +++ b/agent/tests/deep_agent/test_validator.py @@ -332,6 +332,16 @@ async def test_on_demand_review_is_reported_when_the_agent_asks_for_it(scripted_ assert state["final_result"]["semantic_validation"]["verdict"] == "passed" +@pytest.mark.asyncio +async def test_on_demand_failed_review_still_reaches_the_user(scripted_model): + main = scripted_model(_execute(), _review(), _submit()) + state = await _run(main, scripted_model(_verdict("fail", [ISSUE])), mode="on_demand") + assert _submit_results(state) == [ANSWER_RECEIVED] # on_demand: a failed review doesn't block submit + review = state["final_result"]["semantic_validation"] + assert review["verdict"] == "failed" and review["issues"][0]["problem"] == ISSUE["problem"] + assert ISSUE["problem"] in render_markdown(state["final_result"]) + + @pytest.mark.asyncio @pytest.mark.parametrize("mode, offered", [("always", True), ("on_demand", True), ("off", False)]) async def test_modes_offer_the_reviewer(scripted_model, mode, offered): From 6fe2b3eda3e39ecd6ed65b59ce497001f87be26d Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 8 Nov 2026 15:15:37 +0200 Subject: [PATCH 33/37] refactor(deep-agent): rebuild the agent when a prompt changes instead of swapping it per model call PromptRefreshMiddleware replaced the system/validator prompt on every model call, so moving a Langfuse label mid-run switched prompts halfway through a trajectory. The service now compares the current prompt texts (SDK-cached) per request and rebuilds the agent when one changed: a run keeps the prompt it started with, the next request gets the new one, still without a redeploy. The checkpointer is kept across rebuilds. (PR #67 review) Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/agent.py | 8 +-- agent/src/deep_agent/prompts/registry.py | 62 ++----------------- agent/src/deep_agent/service.py | 32 +++++++--- agent/src/deep_agent/validator/reviewer.py | 3 +- .../deep_agent/test_prompts_and_catalog.py | 52 +++++++++++----- 5 files changed, 71 insertions(+), 86 deletions(-) diff --git a/agent/src/deep_agent/agent.py b/agent/src/deep_agent/agent.py index 0529b01..3b55eb6 100644 --- a/agent/src/deep_agent/agent.py +++ b/agent/src/deep_agent/agent.py @@ -19,13 +19,13 @@ from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware from deep_agent.middleware.catalog import CatalogMiddleware from deep_agent.middleware.tool_filter import BuiltinToolFilterMiddleware -from deep_agent.prompts.registry import PromptRefreshMiddleware, load_prompt, local_prompt +from deep_agent.prompts.registry import load_prompt, local_prompt from deep_agent.resources import build_resources from deep_agent.tools import DEEP_AGENT_TOOLS from deep_agent.validator.modes import ON_DEMAND_PROMPT, REVIEW_PROMPT, ReviewTurnMiddleware, validator_subagent from deep_agent.validator.reviewer import ValidationMode -# Packaged system prompt (the Langfuse-managed version, when enabled, is loaded per agent build and refreshed per call). +# Packaged system prompt (the Langfuse-managed version, when enabled, is loaded per agent build; the service rebuilds when it changes). SYSTEM_PROMPT = local_prompt("system") # Appended to the system prompt only when DEEP_AGENT_CLARIFICATIONS_ENABLED is on. @@ -73,8 +73,7 @@ def create_deep_agent( review_required = mode == "always" # submit needs a validator pass has_reviewer = mode in ("always", "on_demand") # the semantic-validator subagent is available review_prompt = {"always": REVIEW_PROMPT, "on_demand": ON_DEMAND_PROMPT}.get(mode, "") - suffix = (CLARIFICATION_PROMPT if clarifications_enabled else "") + review_prompt - system_prompt = load_prompt("system").text + suffix + system_prompt = load_prompt("system").text + (CLARIFICATION_PROMPT if clarifications_enabled else "") + review_prompt subagents = [_general_purpose_subagent()] if has_reviewer: subagents.append(validator_subagent(validator_model or llm, mode)) @@ -87,7 +86,6 @@ def create_deep_agent( middleware=[ DeepAgentContextMiddleware(), CatalogMiddleware(), - PromptRefreshMiddleware("system", system_prompt, suffix=suffix), *submit_fallback(TOOL_NAME), AnswerVerificationMiddleware(has_reviewer), *([ReviewTurnMiddleware()] if has_reviewer else []), diff --git a/agent/src/deep_agent/prompts/registry.py b/agent/src/deep_agent/prompts/registry.py index 51e93fc..b13e464 100644 --- a/agent/src/deep_agent/prompts/registry.py +++ b/agent/src/deep_agent/prompts/registry.py @@ -6,21 +6,18 @@ fallback when Langfuse is unreachable or the prompt doesn't exist, and the only source when DEEP_AGENT_LANGFUSE_PROMPTS is off (tests, offline dev). -PromptRefreshMiddleware swaps in the current Langfuse version on every model call, so moving -a label in Langfuse changes behaviour without a redeploy. Push the packaged prompts with +The service rebuilds the agent when a prompt text changes (deep_agent.service.get_deep_agent), +so moving a label in Langfuse changes behaviour from the next request, without a redeploy; a run +keeps the prompt it started with. Push the packaged prompts with `uv run python scripts/sync_deep_agent_prompts.py --label staging`. """ import logging import time -from collections.abc import Awaitable, Callable from dataclasses import dataclass from pathlib import Path from typing import Any -from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse -from langchain_core.messages import SystemMessage - from agent.config import settings logger = logging.getLogger(__name__) @@ -47,7 +44,7 @@ class LoadedPrompt: # key -> monotonic deadline until which Langfuse is not asked again (prompt missing / unreachable). -# The SDK caches successful fetches but not misses, and load_prompt runs on every model call. +# The SDK caches successful fetches but not misses, and load_prompt runs on every request. _misses: dict[str, float] = {} @@ -81,54 +78,3 @@ def load_prompt(key: str) -> LoadedPrompt: return _miss(key, local) _misses.pop(key, None) return LoadedPrompt(key, client.prompt, "langfuse", getattr(client, "version", None), client) - - -def _system_text(message: SystemMessage | None) -> str: - if message is None: - return "" - content = message.content - if isinstance(content, str): - return content - first = content[0] if content else None - return first.get("text", "") if isinstance(first, dict) else str(first or "") - - -class PromptRefreshMiddleware(AgentMiddleware): - """Replace the prompt the agent was built with by the current version of `key`, per model call. - - deepagents composes the system message as + harness/skills sections, so only that - leading part is swapped; if it isn't found verbatim the request is left untouched. `suffix` is - text appended to the prompt at build time (e.g. the clarification sentence when that flag is - on) and is re-appended to every refreshed version. - """ - - def __init__(self, key: str, built_with: str, suffix: str = "") -> None: - super().__init__() - self.key = key - self.built_with = built_with - self.suffix = suffix - - def _refresh(self, request: ModelRequest) -> ModelRequest: - current = load_prompt(self.key).text + self.suffix - if current == self.built_with or request.system_message is None: - return request - message = request.system_message - if isinstance(message.content, str): - if not message.content.startswith(self.built_with): - return request - new_content: Any = current + message.content[len(self.built_with):] - else: - text = _system_text(message) - if not text.startswith(self.built_with): - return request - first = {**message.content[0], "text": current + text[len(self.built_with):]} - new_content = [first, *message.content[1:]] - return request.override(system_message=SystemMessage(content=new_content)) - - def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse: - return handler(self._refresh(request)) - - async def awrap_model_call( - self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]] - ) -> ModelResponse: - return await handler(self._refresh(request)) diff --git a/agent/src/deep_agent/service.py b/agent/src/deep_agent/service.py index 9d44ed8..3f388fd 100644 --- a/agent/src/deep_agent/service.py +++ b/agent/src/deep_agent/service.py @@ -34,12 +34,15 @@ from deep_agent import observability from deep_agent.answer.render import render_markdown from deep_agent.context import DeepAgentContext, current_turn +from deep_agent.prompts.registry import PROMPT_KEYS, load_prompt from deep_agent.validator.reviewer import VALIDATOR_NAME logger = logging.getLogger(__name__) _agent = None +_agent_prompts: tuple[str, ...] | None = None # the prompt texts _agent was built with _agent_lock: asyncio.Lock | None = None +_checkpointer = None _pg_pool = None UNANSWERED = {"no_answer", "rejected", "re_execution_failed", "not_executed"} @@ -65,24 +68,39 @@ async def build_checkpointer(): return saver +def _current_prompts() -> tuple[str, ...]: + """The prompt texts an agent is built from (Langfuse when enabled — SDK-cached — else the packaged .md).""" + return tuple(load_prompt(key).text for key in PROMPT_KEYS) + + async def get_deep_agent(): - """The process-wide Deep Agent (built once, on first use).""" - global _agent, _agent_lock - if _agent is not None: + """The process-wide Deep Agent, rebuilt when one of its prompts changed (e.g. a Langfuse label moved). + + Checked per request, so a run keeps the prompt it started with and the next request gets the new one. + """ + global _agent, _agent_prompts, _agent_lock, _checkpointer + prompts = await asyncio.to_thread(_current_prompts) + if _agent is not None and prompts == _agent_prompts: return _agent if _agent_lock is None: _agent_lock = asyncio.Lock() async with _agent_lock: - if _agent is None: + if _agent is None or prompts != _agent_prompts: from deep_agent.agent import create_deep_agent - _agent = create_deep_agent(checkpointer=await build_checkpointer()) + if _checkpointer is None: + _checkpointer = await build_checkpointer() + if _agent is not None: + logger.info("Deep agent prompts changed — rebuilding the agent") + _agent = create_deep_agent(checkpointer=_checkpointer) + _agent_prompts = prompts return _agent def reset_for_tests(agent=None) -> None: - global _agent, _agent_lock - _agent, _agent_lock = agent, None + global _agent, _agent_prompts, _agent_lock, _checkpointer + _agent, _agent_lock, _checkpointer = agent, None, None + _agent_prompts = _current_prompts() if agent is not None else None class StreamPublisher(AsyncCallbackHandler): diff --git a/agent/src/deep_agent/validator/reviewer.py b/agent/src/deep_agent/validator/reviewer.py index 97ede6d..985fd22 100644 --- a/agent/src/deep_agent/validator/reviewer.py +++ b/agent/src/deep_agent/validator/reviewer.py @@ -44,7 +44,7 @@ from deep_agent.answer.verification import match_execution, normalize_sql from deep_agent.context import DeepAgentContext, DeepAgentContextMiddleware, DeepAgentRuntimeState from deep_agent.middleware.catalog import CatalogMiddleware -from deep_agent.prompts.registry import PromptRefreshMiddleware, load_prompt +from deep_agent.prompts.registry import load_prompt logger = logging.getLogger(__name__) @@ -240,7 +240,6 @@ def build_validator(model: BaseChatModel): ReviewInputMiddleware(), # first: the date is then added to the built input, not to the brief DeepAgentContextMiddleware(), CatalogMiddleware(), - PromptRefreshMiddleware("validator", prompt), *submit_fallback(VERDICT_TOOL), ReviewRecordMiddleware(), ], diff --git a/agent/tests/deep_agent/test_prompts_and_catalog.py b/agent/tests/deep_agent/test_prompts_and_catalog.py index 386d37d..b6db7e6 100644 --- a/agent/tests/deep_agent/test_prompts_and_catalog.py +++ b/agent/tests/deep_agent/test_prompts_and_catalog.py @@ -118,21 +118,46 @@ def test_langfuse_unavailable_falls_back(langfuse_enabled, behaviour): @pytest.mark.asyncio -async def test_prompt_label_change_takes_effect_without_rebuild(scripted_model, langfuse_enabled): - served = {"text": local_prompt("system")} +async def test_prompt_change_rebuilds_the_agent_on_the_next_request(langfuse_enabled): + from deep_agent import service + + served = {"system": "system v1", "validator": "validator v1"} + fake = MagicMock(get_prompt=MagicMock(side_effect=lambda name, **k: _served(served[name.split("/")[1]]))) + builds = [] + + def fake_build(**kwargs): + builds.append(dict(served)) + return object() + + service.reset_for_tests() + with patch("agent.langfuse_client.langfuse_client", fake), \ + patch("deep_agent.agent.create_deep_agent", fake_build), \ + patch.object(service, "build_checkpointer", MagicMock(side_effect=lambda: _async(object()))): + first = await service.get_deep_agent() + assert await service.get_deep_agent() is first # unchanged prompts: same agent + served["validator"] = "validator v2" + second = await service.get_deep_agent() + service.reset_for_tests() + assert second is not first and builds == [{"system": "system v1", "validator": "validator v1"}, + {"system": "system v1", "validator": "validator v2"}] + + +async def _async(value): + return value + + +@pytest.mark.asyncio +async def test_a_run_keeps_the_prompt_it_started_with(scripted_model, langfuse_enabled): + served = {"text": "You are the deep analyst prompt v4."} fake = MagicMock(get_prompt=MagicMock(side_effect=lambda *a, **k: _served(served["text"]))) - model = scripted_model(AIMessage("one"), AIMessage("one"), AIMessage("two"), AIMessage("two")) # each + reminder reply + model = scripted_model(AIMessage("one"), AIMessage("one")) # answer + reminder reply with patch("agent.langfuse_client.langfuse_client", fake): agent = create_deep_agent(model=model) + served["text"] = "You are the NEW deep analyst prompt v5." # label moved while the agent exists await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "p1"}}) - served["text"] = "You are the NEW deep analyst prompt v4." - await agent.ainvoke({"messages": [("user", "b")]}, {"configurable": {"thread_id": "p2"}}) - - first, second = system_text(model.seen[0]), system_text(model.seen[2]) - assert first.startswith(local_prompt("system")[:80]) - assert second.startswith("You are the NEW deep analyst prompt v4.") - assert "Skills System" in second # harness / skills sections after our prompt are preserved - assert local_prompt("system")[:80] not in second + prompts = [system_text(seen) for seen in model.seen] + assert all(p.startswith("You are the deep analyst prompt v4.") for p in prompts) + assert "Skills System" in prompts[0] def test_run_config_links_generations_to_the_prompt_version(langfuse_enabled): @@ -183,12 +208,11 @@ def test_miss_expires_after_ttl(langfuse_enabled, monkeypatch): @pytest.mark.asyncio -async def test_prompt_refresh_keeps_the_clarification_suffix(scripted_model, langfuse_enabled): +async def test_langfuse_prompt_keeps_the_clarification_suffix(scripted_model, langfuse_enabled): fake = MagicMock(get_prompt=MagicMock(side_effect=lambda *a, **k: _served("NEW system prompt v5."))) model = scripted_model(AIMessage("done"), AIMessage("done")) with patch("agent.langfuse_client.langfuse_client", fake): agent = create_deep_agent(model=model, clarifications_enabled=True) - fake.get_prompt.side_effect = lambda *a, **k: _served("NEWER system prompt v6.") await agent.ainvoke({"messages": [("user", "a")]}, {"configurable": {"thread_id": "s"}}) prompt = system_text(model.seen[0]) - assert prompt.startswith("NEWER system prompt v6." + CLARIFICATION_PROMPT) + assert prompt.startswith("NEW system prompt v5." + CLARIFICATION_PROMPT) From f49c4e0cb86dad960d5449837d11bd03b5624a11 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 8 Nov 2026 16:04:09 +0200 Subject: [PATCH 34/37] fix(deep-agent): say which columns search_column_values really indexes; clearer no-match notice Checked on the live Jeen service: categorical and boolean columns are indexed too (the docs said they return 0), while id / continuous / time / free_text columns and non-existent tables/columns return 0 whatever the value. On an indexed column the nearest values come back even for a term not in the data, so a match is judged by its scores. The no-match notice now points at the column's semantic_type instead of suggesting the value doesn't exist. (PR #67 review) Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/prompts/system.md | 4 ++-- agent/src/deep_agent/tools/metadata.py | 18 ++++++++++-------- agent/tests/deep_agent/test_guidance_lint.py | 2 +- agent/tests/deep_agent/test_tool_contracts.py | 6 ++++++ 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index 2cbd9c8..76c1bc8 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -40,7 +40,7 @@ For complex or aggregation-heavy questions, write 1–2 lines stating the intent The user's word is almost never the stored string — the value may be spelled differently, abbreviated, or stored in another language (a Hebrew question often filters values stored in English). Resolve every text filter value according to the column's `semantic_type`: -> **Tool scope**: `search_column_values` searches ONLY `large_categorical` and `large_unit_id` columns — the only column types it indexes. Standard `categorical` and `boolean` columns are not indexed and return 0 matches; numeric, date/timestamp and geometry columns are not indexed either. +> **Tool scope**: `search_column_values` indexes `large_categorical`, `large_unit_id`, `categorical` and `boolean` columns. `id`, numeric, date/timestamp, free-text and geometry columns are not indexed — a search on them (or on a table/column that doesn't exist) returns 0 results whatever the value. On an indexed column it returns the nearest stored values even when the term isn't in the data, so judge matches by their scores: a returned value is not proof the user's value exists. 1. **High-cardinality (`large_categorical` / `large_unit_id`)** — e.g. customer, company or person names, product SKUs, city names: - Too many values to list; use `search_column_values` with the user's term to find how the database actually spells the entity (e.g. "Acme Corp" → "Acme Corporation LLC"). Use the returned `value`s verbatim. A `keyword_similarity` close to 1.0 is a strong lexical match; a `semantic_distance` close to 0.0 is a strong semantic match. @@ -49,7 +49,7 @@ The user's word is almost never the stored string — the value may be spelled d - Don't call `get_column_distinct_values` on these columns — dumping 50–100 arbitrary values is slow (10–20s), wastes tokens, and rarely contains the entity you need. 2. **Standard `categorical` & `boolean`** — e.g. status, priority, type, gender, active flags: - - **Never call `search_column_values` on them** (not indexed → 0 results). + - `search_column_values` isn't needed for them — their value sets are small; use the catalog's values. - Use the values listed in the catalog. When the catalog lists all values (the domain is complete), that list is definitive: any other string does not exist in the data. - If the values aren't listed, `get_column_distinct_values` shows the full set (usually 5–20 rows). diff --git a/agent/src/deep_agent/tools/metadata.py b/agent/src/deep_agent/tools/metadata.py index 4d31314..d71ce2e 100644 --- a/agent/src/deep_agent/tools/metadata.py +++ b/agent/src/deep_agent/tools/metadata.py @@ -80,13 +80,11 @@ async def search_column_values( """ Searches for exact real values contained within indexed columns across the database. - SUPPORTED COLUMN TYPES: - Works exclusively on high-cardinality columns profiled as: - - `large_categorical` - - `large_unit_id` - ⚠️ Do NOT use on standard `categorical` or `boolean` columns (e.g. a `status` column) — they are - not indexed in vector search and will return 0 matches! Use `get_column_distinct_values` or the catalog instead. - Do NOT use on numeric, date/timestamp, or geometry columns. + SUPPORTED COLUMN TYPES (semantic_type in the catalog): + - Indexed: `large_categorical`, `large_unit_id` (its main use), and `categorical` / `boolean` (whose + values the catalog usually lists already). + - NOT indexed: `id`, `continuous`, `time`, `free_text` and geometry columns. A search on them — or on a + table/column that doesn't exist — returns 0 matches whatever the value; check such values with SQL. WHEN TO USE: - Use whenever you need to find how a high-cardinality entity is represented or spelled in the database @@ -96,6 +94,8 @@ async def search_column_values( Returns data.matches — up to `limit` matching values (use each 'value' verbatim in SQL) with: - 'keyword_similarity' close to 1.0 = strong lexical match - 'semantic_distance' close to 0.0 = strong semantic match + On an indexed column the nearest stored values come back even when the term isn't in the data, so a + weak-scoring match is not evidence that the value exists. data.limit_reached is true when exactly `limit` matches came back: there may be more — call again with a higher `limit` before filtering on the list. @@ -117,7 +117,9 @@ async def search_column_values( matches = [_value_match(v) for v in values] limit_reached = len(matches) >= limit if not matches: - notice = "No matches — the value may not exist in this column, or the column is not indexed (only large_categorical / large_unit_id are)." + notice = ("No matches. Check the column's semantic_type in the catalog: `id`, `continuous`, `time` and " + "`free_text` columns are not indexed and always return 0, as does a table/column that doesn't " + "exist — check those values with SQL instead. On an indexed column, nothing matched the term.") elif limit_reached: notice = f"Returned the first {limit} matches (the limit); there may be more — call again with a higher limit." else: diff --git a/agent/tests/deep_agent/test_guidance_lint.py b/agent/tests/deep_agent/test_guidance_lint.py index 4541b1c..049571f 100644 --- a/agent/tests/deep_agent/test_guidance_lint.py +++ b/agent/tests/deep_agent/test_guidance_lint.py @@ -78,7 +78,7 @@ def test_no_catalog_specific_examples(doc): def test_value_resolution_policy_has_one_owner(): - owners = [name for name, text in DOCS.items() if "the only column types it indexes" in text] + owners = [name for name, text in DOCS.items() if "**Tool scope**: `search_column_values` indexes" in text] assert owners == ["system prompt"] diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py index ff5a30f..c98f9d5 100644 --- a/agent/tests/deep_agent/test_tool_contracts.py +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -160,6 +160,12 @@ async def test_search_values_says_when_the_limit_was_hit(): assert fewer["data"]["limit_reached"] is False and fewer["data"]["notice"] is None +@pytest.mark.asyncio +async def test_search_values_no_match_points_at_unindexed_column_types(): + notice = (await _search([]))["data"]["notice"] + assert all(t in notice for t in ("`id`", "`continuous`", "`time`", "`free_text`", "doesn't exist")) + + @pytest.mark.asyncio async def test_search_values_passes_limit_through_unclamped(): client = MagicMock(search_column_values=AsyncMock(return_value={"values": []})) From 04b3ef077b390adeef039860fc0126384718a647 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 8 Nov 2026 16:25:39 +0200 Subject: [PATCH 35/37] refactor(deep-agent): remove the get_column_profile tool The catalog already carries type / semantic type / distinct count / range / examples, and NULLs, top values or a distribution are one SQL query away (fresher than the stored profile). It was never called in our test runs. Also corrects the tool reference line for search_column_values. (PR #67 review) Co-Authored-By: Claude Opus 5.5 --- agent/src/deep_agent/prompts/system.md | 5 ++-- .../skills/temporal-analyst/SKILL.md | 2 +- agent/src/deep_agent/tools/__init__.py | 5 ++-- agent/src/deep_agent/tools/envelope.py | 1 - agent/src/deep_agent/tools/metadata.py | 29 ++----------------- agent/tests/deep_agent/test_tool_contracts.py | 9 +++--- 6 files changed, 11 insertions(+), 40 deletions(-) diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index 76c1bc8..ce11044 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -139,7 +139,7 @@ The user's word is almost never the stored string — the value may be spelled d | `EXCEEDED_*` (memory / time limits) | Narrow the time or partition range, select fewer columns, pre-aggregate in a CTE | | Missing partition filter | Filter the partition column in its native type | | `error.type` other than `USER_ERROR` | A cluster / source-database problem, not necessarily your SQL — read the message before rewriting | -| 0 rows | Investigate, in order: string filter values (re-resolve them, Phase 3) → join key formats (`get_sample_rows` on both sides) → date range logic and column type → NULLs (`get_column_profile`). Remove conditions one at a time to find the culprit | +| 0 rows | Investigate, in order: string filter values (re-resolve them, Phase 3) → join key formats (`get_sample_rows` on both sides) → date range logic and column type → NULLs (`COUNT(*) FILTER (WHERE col IS NULL)`). Remove conditions one at a time to find the culprit | | Count ≫ expected | Fan-out JOIN — `COUNT(DISTINCT id)` or aggregate before joining | | Suspiciously round number / equals the table size | A Cartesian product (missing or wrong ON key), or a WHERE clause that filters nothing | @@ -176,9 +176,8 @@ Before writing SQL in these areas, read the skill with `read_file`: `temporal-an ## Tool Reference **Values & places** -- `search_column_values` — targeted value search for `large_categorical` / `large_unit_id` columns only. +- `search_column_values` — targeted value search, mainly for high-cardinality columns (see Tool scope, Phase 3). - `get_column_distinct_values` — live distinct values of a low-cardinality `categorical` column (e.g. a `status` column) when the catalog doesn't list them. -- `get_column_profile` — a column's full statistics beyond the catalog: null count / ratio, top values with frequencies, string lengths, quartiles. - `resolve_location_to_wkt` — place name → area polygon (WKT) for `ST_GeometryFromText('...')`. **Execution** diff --git a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md index 77d5f23..c85c72c 100644 --- a/agent/src/deep_agent/skills/temporal-analyst/SKILL.md +++ b/agent/src/deep_agent/skills/temporal-analyst/SKILL.md @@ -6,7 +6,7 @@ description: Trino date and time handling — use when queries involve timestamp ## Step 1 — Know the column type -Check `get_column_profile` (or the catalog) before writing any date filter: +Check the column's type in the catalog before writing any date filter: - **Native `date` / `timestamp`** → compare the column directly against date/timestamp literals with half-open ranges. Never wrap it in a function in `WHERE` (that defeats partition pruning and min/max statistics). diff --git a/agent/src/deep_agent/tools/__init__.py b/agent/src/deep_agent/tools/__init__.py index 6d8e748..7b69c17 100644 --- a/agent/src/deep_agent/tools/__init__.py +++ b/agent/src/deep_agent/tools/__init__.py @@ -5,7 +5,7 @@ {"ok": true, "data": ..., "error": null} | {"ok": false, "data": null, "error": {"name", "message", ...}} - sql.py execute_trino_query, get_sample_rows, get_column_distinct_values, validate_sql -- metadata.py search_column_values, get_column_profile +- metadata.py search_column_values - enrichment.py enrich_sql_filters - location.py resolve_location_to_wkt @@ -15,7 +15,7 @@ from deep_agent.tools.enrichment import enrich_sql_filters from deep_agent.tools.location import resolve_location_to_wkt -from deep_agent.tools.metadata import get_column_profile, search_column_values +from deep_agent.tools.metadata import search_column_values from deep_agent.tools.sql import execute_trino_query, get_column_distinct_values, get_sample_rows, validate_sql # The tools the model gets (order = order shown to the model). @@ -23,7 +23,6 @@ # Values & places search_column_values, get_column_distinct_values, - get_column_profile, resolve_location_to_wkt, # Query execution execute_trino_query, diff --git a/agent/src/deep_agent/tools/envelope.py b/agent/src/deep_agent/tools/envelope.py index e03d639..f14e06b 100644 --- a/agent/src/deep_agent/tools/envelope.py +++ b/agent/src/deep_agent/tools/envelope.py @@ -14,7 +14,6 @@ from typing import Any METADATA_ERROR = "METADATA_ERROR" # the Jeen metadata service failed or returned an unexpected payload -NOT_FOUND = "NOT_FOUND" # the metadata service has nothing stored for the requested object ENRICHMENT_ERROR = "ENRICHMENT_ERROR" # filter enrichment failed; the SQL is unchanged LOCATION_NOT_FOUND = "LOCATION_NOT_FOUND" # the location could not be resolved to an area diff --git a/agent/src/deep_agent/tools/metadata.py b/agent/src/deep_agent/tools/metadata.py index d71ce2e..d2aeced 100644 --- a/agent/src/deep_agent/tools/metadata.py +++ b/agent/src/deep_agent/tools/metadata.py @@ -1,5 +1,5 @@ """ -Metadata tools: stored column statistics and value search, from the Jeen metadata service. +Metadata tools: value search, from the Jeen metadata service. The connection's catalog itself is not a tool: it is loaded for every run and shown to the model by CatalogMiddleware (deep_agent.middleware.catalog). @@ -12,7 +12,7 @@ from agent.utils.jeen_metadata_client import get_jeen_metadata_client from deep_agent.context import Runtime, connection_id -from deep_agent.tools.envelope import METADATA_ERROR, NOT_FOUND, error, fail, ok +from deep_agent.tools.envelope import METADATA_ERROR, error, fail, ok logger = logging.getLogger(__name__) @@ -25,31 +25,6 @@ def metadata_failure(what: str, exc: Exception) -> str: )) -@tool -async def get_column_profile(table_name: str, column_name: str, runtime: Runtime = None) -> str: - """ - Retrieves the full stored statistics of one column — detail the catalog does not show: - null count / ratio, top values with their frequencies, string lengths, quartiles and a histogram. - - The catalog already lists each column's type, semantic_type, distinct count, range and example - values (all values when the domain is complete), so call this only when you need that extra - detail — e.g. checking NULLs when a query returns 0 rows, or a value distribution. - - Args: - table_name (str): The fully qualified exact name of the table, e.g., '"catalog"."schema"."table"'. - column_name (str): The exact name of the column to profile. - """ - try: - profile = await get_jeen_metadata_client().get_column_profile( - table_name, column_name, connection_id=connection_id(runtime) - ) - except Exception as e: - return metadata_failure(f"get_column_profile({table_name}.{column_name})", e) - if not profile: - return fail(error(NOT_FOUND, f"No stored profile for column {table_name}.{column_name}")) - return ok(profile) - - def _round_or_none(value: Any) -> float | None: try: return round(float(value), 3) diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py index c98f9d5..7a67488 100644 --- a/agent/tests/deep_agent/test_tool_contracts.py +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -19,7 +19,6 @@ # Minimal valid arguments for every tool (each must honour the envelope). TOOL_ARGS = { - "get_column_profile": {"table_name": "t", "column_name": "c"}, "search_column_values": {"search_term": "תל אביב"}, "resolve_location_to_wkt": {"location_name": "חיפה"}, "execute_trino_query": {"sql": "SELECT 1"}, @@ -33,7 +32,7 @@ def _client(fail: bool) -> MagicMock: client = MagicMock() names = ["get_catalog_prompt", "get_tables", "get_columns", "get_relationships", "get_table_profile", - "get_column_profile", "search", "search_business_terms", "search_knowledge_pairs", "search_column_values"] + "search", "search_business_terms", "search_knowledge_pairs", "search_column_values"] for name in names: if fail: setattr(client, name, AsyncMock(side_effect=JeenMetadataError(f"{name} exploded"))) @@ -69,7 +68,7 @@ def test_registered_tool_set(): """The catalog is loaded for every run (CatalogMiddleware), so there is no catalog tool, and the tools whose information the catalog already contains are not offered to the model.""" assert {t.name for t in DEEP_AGENT_TOOLS} == { - "search_column_values", "get_column_distinct_values", "get_column_profile", "resolve_location_to_wkt", + "search_column_values", "get_column_distinct_values", "resolve_location_to_wkt", "execute_trino_query", "get_sample_rows", "validate_sql", "enrich_sql_filters", } @@ -93,9 +92,9 @@ async def test_tool_returns_envelope(tool, patched): @pytest.mark.asyncio async def test_metadata_failure_says_data_is_not_empty(): - client = MagicMock(get_column_profile=AsyncMock(side_effect=JeenMetadataError("auth expired"))) + client = MagicMock(search_column_values=AsyncMock(side_effect=JeenMetadataError("auth expired"))) with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client): - out = json.loads(await tools.get_column_profile.ainvoke({"table_name": "t", "column_name": "c"})) + out = json.loads(await tools.search_column_values.ainvoke({"search_term": "x"})) assert out["error"]["name"] == "METADATA_ERROR" assert "auth expired" in out["error"]["message"] assert "does not mean the data is empty" in out["error"]["message"] From 4f8b1aab3bb26f89a966aa8ffcbe1cef09e50e3e Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Sun, 8 Nov 2026 16:29:46 +0200 Subject: [PATCH 36/37] refactor(deep-agent): remove the enrich_sql_filters tool It wrapped the legacy graph's enrichment step (value search + a separate LLM picks the spelling + AST rewrite). In the deep agent resolving values is the agent's own job (search_column_values, judging matches, recorded in assumptions), so the tool added a hidden second LLM decision and a rewrite that had to be re-run; it was rarely used. Also drops the context helpers only it used (cached_catalog, user_request). The legacy graph keeps its enrichment pipeline. (PR #67 review) Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 4 +- agent/src/deep_agent/context.py | 16 --- agent/src/deep_agent/prompts/system.md | 3 - agent/src/deep_agent/tools/__init__.py | 4 - agent/src/deep_agent/tools/enrichment.py | 101 ---------------- agent/src/deep_agent/tools/envelope.py | 1 - agent/tests/deep_agent/test_catalog_state.py | 111 ------------------ agent/tests/deep_agent/test_guidance_lint.py | 1 - agent/tests/deep_agent/test_observability.py | 28 ++--- agent/tests/deep_agent/test_tool_contracts.py | 11 +- agent/tests/deep_agent/test_validator.py | 3 +- 11 files changed, 13 insertions(+), 270 deletions(-) delete mode 100644 agent/src/deep_agent/tools/enrichment.py delete mode 100644 agent/tests/deep_agent/test_catalog_state.py diff --git a/agent/README.md b/agent/README.md index e805091..3f5b001 100644 --- a/agent/README.md +++ b/agent/README.md @@ -47,7 +47,7 @@ cli.py developer CLI context.py per-request context, state fields, user-message helpers, date prefix observability.py Langfuse run config and scores resources.py skills wiring (read-only /skills/) -tools/ what the model can call: sql, metadata, enrichment, location (+ envelope, trino_errors) +tools/ what the model can call: sql, metadata, location (+ envelope, trino_errors) answer/ the final answer: schema, verification (did the SQL run), middleware, render validator/ independent semantic review before submit: reviewer (the agent), modes (wiring) middleware/ cross-cutting: catalog in every model call, built-in tool filter @@ -110,7 +110,7 @@ The guard is an application-level control. The Trino principal used by the agent Every deep-agent run is **one Langfuse trace** built by `deep_agent.observability.build_run_config()`: - session = thread id, user = `user_id`, tag `deep-agent`, metadata `agent_version` (`DEEP_AGENT_VERSION` env, e.g. the git SHA, else the package version) and `connection_id` -- all model calls, tool calls, subagent calls and enrichment LLM calls are nested observations +- all model calls, tool calls, and subagent calls are nested observations - `execute_trino_query` / `get_sample_rows` / `get_column_distinct_values` observations carry `trino_query_id`, `execution_time_ms`, `row_count`, `truncated` (or Trino's `error_name` / `error_type`) as metadata - run-level scores: `deep-agent.model_calls`, `.tool_calls`, `.sql_executions`, `.latency_s` diff --git a/agent/src/deep_agent/context.py b/agent/src/deep_agent/context.py index 6c57367..9a396d1 100644 --- a/agent/src/deep_agent/context.py +++ b/agent/src/deep_agent/context.py @@ -107,22 +107,6 @@ def connection_id(runtime: ToolRuntime | None) -> int | None: return getattr(ctx, "connection_id", None) -def cached_catalog(runtime: ToolRuntime | None) -> str | None: - state = getattr(runtime, "state", None) or {} - return state.get("jeen_catalog") or None - - -def user_request(runtime: ToolRuntime | None) -> str: - """Every human message in the thread, oldest first, one per line. - - A reply to a clarifying question arrives as a new human message on the same thread, so the - request being answered is the original question plus those replies — not just the last one. - """ - state = getattr(runtime, "state", None) or {} - texts = [msg.text for msg in state.get("messages") or [] if is_user_message(msg) and msg.text.strip()] - return "\n".join(texts) - - def _now(tz: str) -> datetime: return datetime.now(ZoneInfo(tz)) diff --git a/agent/src/deep_agent/prompts/system.md b/agent/src/deep_agent/prompts/system.md index ce11044..e26f31f 100644 --- a/agent/src/deep_agent/prompts/system.md +++ b/agent/src/deep_agent/prompts/system.md @@ -55,8 +55,6 @@ The user's word is almost never the stored string — the value may be spelled d 3. **Numeric, date, timestamp or geometry columns**: use the catalog's ranges, `get_sample_rows`, and casting / date parsing (see the `temporal-analyst` skill). Place names → `resolve_location_to_wkt` (see the `spatial-analyst` skill). -4. **Safety net**: after drafting SQL with text filters, run `enrich_sql_filters` — it re-checks and aligns the WHERE-clause text values against the database at the AST level. Resolving values yourself *and* running it is the safest pattern. - --- ## Phase 4 — Draft @@ -186,7 +184,6 @@ Before writing SQL in these areas, read the skill with `read_file`: `temporal-an - `validate_sql` — optional dry-run; not needed before executing. **Post-processing** -- `enrich_sql_filters` — AST-level correction of text filter values. Pass only the SQL. **Delegation** - `task` — spawn a subagent for heavy, separable exploration without filling your own context. diff --git a/agent/src/deep_agent/tools/__init__.py b/agent/src/deep_agent/tools/__init__.py index 7b69c17..532c34e 100644 --- a/agent/src/deep_agent/tools/__init__.py +++ b/agent/src/deep_agent/tools/__init__.py @@ -6,14 +6,12 @@ - sql.py execute_trino_query, get_sample_rows, get_column_distinct_values, validate_sql - metadata.py search_column_values -- enrichment.py enrich_sql_filters - location.py resolve_location_to_wkt The connection's catalog is not a tool: CatalogMiddleware (deep_agent.middleware.catalog) loads it for every run and puts it in the prompt. """ -from deep_agent.tools.enrichment import enrich_sql_filters from deep_agent.tools.location import resolve_location_to_wkt from deep_agent.tools.metadata import search_column_values from deep_agent.tools.sql import execute_trino_query, get_column_distinct_values, get_sample_rows, validate_sql @@ -28,6 +26,4 @@ execute_trino_query, get_sample_rows, validate_sql, - # Post-processing - enrich_sql_filters, ] diff --git a/agent/src/deep_agent/tools/enrichment.py b/agent/src/deep_agent/tools/enrichment.py deleted file mode 100644 index a8deb1e..0000000 --- a/agent/src/deep_agent/tools/enrichment.py +++ /dev/null @@ -1,101 +0,0 @@ -""" -enrich_sql_filters: correct categorical filter values in a draft SQL to the stored spellings, -reusing the legacy graph's enrichment pipeline (agent.services.enrichment_orchestrator). -""" - -import logging - -from langchain_core.messages import ToolMessage -from langchain_core.tools import tool -from langgraph.types import Command - -from agent.utils.jeen_metadata_client import get_jeen_metadata_client -from agent.utils.sql import clean_sql -from deep_agent.context import Runtime, cached_catalog, connection_id, user_request -from deep_agent.tools.envelope import ENRICHMENT_ERROR, error, fail, ok -from deep_agent.tools.metadata import metadata_failure - -logger = logging.getLogger(__name__) - - -@tool -async def enrich_sql_filters(sql: str, runtime: Runtime = None) -> str | Command: - """ - Automatically corrects categorical filter values in a draft SQL query to match exact - database spellings using semantic search and LLM-guided AST transformation. - - Use this AFTER you have written a draft SQL query that contains WHERE clause filters on - categorical (text) columns. It will: - 1. Parse the SQL AST to find comparison filters - 2. Semantically search the database for canonical matching values - 3. Use an LLM to select the best match - 4. Rewrite the SQL with exact canonical values (AST-level, not string replacement) - - The catalog and the user's question are taken from the conversation automatically — - pass only the SQL. - - This is especially powerful for Hebrew→English column value resolution and large categorical - columns where manually calling search_column_values for every filter would be tedious. - - Do NOT use this on purely numeric SQL or when you already have exact confirmed values. - - Returns data.sql (the enriched SQL, or the original if nothing changed), data.enriched and - data.changes (one entry per corrected filter). - - Args: - sql (str): The draft SQL query to enrich. - """ - from agent.nodes.refiner import parse_jeen_catalog_tables - from agent.services.enrichment_orchestrator import EnrichmentOrchestrator - - sql_clean = clean_sql(sql) - - catalog = cached_catalog(runtime) - fetched_catalog = False - if not catalog: - try: - catalog = await get_jeen_metadata_client().get_catalog_prompt(connection_id=connection_id(runtime)) - except Exception as e: - return metadata_failure("enrich_sql_filters (catalog fetch)", e) - fetched_catalog = True - - try: - schema, tables = parse_jeen_catalog_tables(catalog) - if not tables: - return fail(error(ENRICHMENT_ERROR, "No tables could be parsed from the connection catalog. The SQL is unchanged.", - original_sql=sql_clean)) - - refined_sql, plan, enriched = await EnrichmentOrchestrator.enrich_query( - user_request=user_request(runtime), - initial_sql=sql_clean, - schema=schema, - tables=tables, - config=runtime.config if runtime is not None else None, - ) - except Exception as e: - logger.error("enrich_sql_filters failed: %s", e, exc_info=True) - return fail(error(ENRICHMENT_ERROR, f"{e}. The SQL is unchanged.", original_sql=sql_clean)) - - changes = [] - if enriched and plan: - changes = [ - { - "column": tf.column, - "original_value": tf.original_value, - "refined_values": tf.refined_values, - "old_operator": tf.old_operator, - "new_operator": tf.new_operator, - } - for tf in plan.enrichment_details - if tf.changed_filter - ] - is_enriched = bool(enriched and plan) - content = ok({"enriched": is_enriched, "sql": refined_sql if is_enriched else sql_clean, "changes": changes}) - - if fetched_catalog and runtime is not None and runtime.tool_call_id: - # Cache the catalog we had to fetch so the next call in this thread doesn't refetch it. - return Command(update={ - "jeen_catalog": catalog, - "messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id, name="enrich_sql_filters")], - }) - return content diff --git a/agent/src/deep_agent/tools/envelope.py b/agent/src/deep_agent/tools/envelope.py index f14e06b..af403d0 100644 --- a/agent/src/deep_agent/tools/envelope.py +++ b/agent/src/deep_agent/tools/envelope.py @@ -14,7 +14,6 @@ from typing import Any METADATA_ERROR = "METADATA_ERROR" # the Jeen metadata service failed or returned an unexpected payload -ENRICHMENT_ERROR = "ENRICHMENT_ERROR" # filter enrichment failed; the SQL is unchanged LOCATION_NOT_FOUND = "LOCATION_NOT_FOUND" # the location could not be resolved to an area diff --git a/agent/tests/deep_agent/test_catalog_state.py b/agent/tests/deep_agent/test_catalog_state.py deleted file mode 100644 index 046070d..0000000 --- a/agent/tests/deep_agent/test_catalog_state.py +++ /dev/null @@ -1,111 +0,0 @@ -from types import SimpleNamespace -from unittest.mock import AsyncMock, MagicMock, patch - -import pytest -from langchain_core.callbacks import AsyncCallbackHandler -from langchain_core.messages import AIMessage - -from deep_agent import tools -from deep_agent.agent import create_deep_agent -from deep_agent.tools import enrichment as enrichment_tools - -CATALOG = '# Jeen Catalog\n"postgres"."public"."flights_table"\n| launch_country | varchar | categorical |' -QUESTION = "כמה טיסות המריאו מצרפת" -DRAFT = "SELECT COUNT(*) FROM \"postgres\".\"public\".\"flights_table\" WHERE launch_country = 'צרפת'" - - -class Marker(AsyncCallbackHandler): - """A caller-supplied callback handler; it must reach the enrichment LLM calls.""" - - -def _policy(enrich_calls: int): - def policy(messages): - tool_msgs = [m for m in messages if m.type == "tool"] - if len(tool_msgs) < enrich_calls: - return AIMessage("", tool_calls=[{"name": "enrich_sql_filters", "args": {"sql": DRAFT}, "id": f"t{len(tool_msgs)}"}]) - return AIMessage("done") - return policy - - -@pytest.fixture -def enrichment(fake_catalog): - plan = SimpleNamespace(enrichment_details=[SimpleNamespace( - changed_filter=True, column="launch_country", original_value="צרפת", refined_values=["France"], - old_operator="=", new_operator="=", - )]) - enrich = AsyncMock(return_value=(DRAFT.replace("'צרפת'", "'France'"), plan, True)) - parse = MagicMock(return_value=({"flights_table": {"launch_country": "varchar"}}, ["flights_table"])) - client = MagicMock(get_catalog_prompt=AsyncMock(return_value=CATALOG)) - with patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", enrich), \ - patch("agent.nodes.refiner.parse_jeen_catalog_tables", parse), \ - patch.object(enrichment_tools, "get_jeen_metadata_client", return_value=client): - fake_catalog.get_catalog_prompt.return_value = CATALOG # what CatalogMiddleware loads for the run - yield SimpleNamespace(enrich=enrich, parse=parse, client=client, run_catalog=fake_catalog) - - -@pytest.mark.asyncio -async def test_enrichment_uses_the_run_catalog_question_and_parent_config(policy_model, enrichment): - agent = create_deep_agent(model=policy_model(_policy(1))) - marker = Marker() - result = await agent.ainvoke( - {"messages": [("user", QUESTION)]}, - {"configurable": {"thread_id": "e1"}, "callbacks": [marker]}, - ) - - assert result["jeen_catalog"] == CATALOG - enrichment.run_catalog.get_catalog_prompt.assert_awaited_once() # loaded once, by CatalogMiddleware - enrichment.client.get_catalog_prompt.assert_not_awaited() # the tool never fetches it itself - enrichment.parse.assert_called_once_with(CATALOG) # exact loaded text, not a model re-typing - - kwargs = enrichment.enrich.await_args.kwargs - assert kwargs["user_request"] == QUESTION - assert kwargs["initial_sql"] == DRAFT - config = kwargs["config"] - assert config is not None - handlers = getattr(config.get("callbacks"), "handlers", config.get("callbacks")) or [] - assert marker in handlers, "caller callbacks (Langfuse) must propagate into enrichment" - - enrich_msg = next(m for m in result["messages"] if m.type == "tool" and m.name == "enrich_sql_filters") - assert "'France'" in enrich_msg.text - - -@pytest.mark.asyncio -async def test_repeated_enrichment_never_refetches_the_catalog(policy_model, enrichment): - agent = create_deep_agent(model=policy_model(_policy(3))) - await agent.ainvoke({"messages": [("user", QUESTION)]}, {"configurable": {"thread_id": "e2"}}) - - assert enrichment.enrich.await_count == 3 - enrichment.run_catalog.get_catalog_prompt.assert_awaited_once() - enrichment.client.get_catalog_prompt.assert_not_awaited() - - -@pytest.mark.asyncio -async def test_catalog_fetch_failure_is_reported(policy_model, enrichment): - enrichment.client.get_catalog_prompt.side_effect = RuntimeError("mcp down") - out = await tools.enrich_sql_filters.ainvoke({"sql": DRAFT}) - assert '"name":"METADATA_ERROR"' in out - enrichment.enrich.assert_not_awaited() - - -def test_model_only_supplies_sql(): - props = tools.enrich_sql_filters.tool_call_schema.model_json_schema()["properties"] - assert list(props) == ["sql"] - - -@pytest.mark.asyncio -async def test_enrichment_after_clarification_gets_the_question_and_the_reply(policy_model, enrichment): - """The reply to a clarifying question arrives as a new user message; it must not replace the question.""" - def policy(messages): - humans = [m for m in messages if m.type == "human"] - if len(humans) == 1: - return AIMessage("לאיזה מחוז הכוונה?") # clarifying question, no tools - if messages[-1].type == "human": - return AIMessage("", tool_calls=[{"name": "enrich_sql_filters", "args": {"sql": DRAFT}, "id": "e"}]) - return AIMessage("done") - - agent = create_deep_agent(model=policy_model(policy)) - config = {"configurable": {"thread_id": "clarify"}} - await agent.ainvoke({"messages": [("user", "כמה טיסות המריאו מהמחוז הצפוני")]}, config) - await agent.ainvoke({"messages": [("user", "חיפה")]}, config) - - assert enrichment.enrich.await_args.kwargs["user_request"] == "כמה טיסות המריאו מהמחוז הצפוני\nחיפה" diff --git a/agent/tests/deep_agent/test_guidance_lint.py b/agent/tests/deep_agent/test_guidance_lint.py index 049571f..3bd2cc4 100644 --- a/agent/tests/deep_agent/test_guidance_lint.py +++ b/agent/tests/deep_agent/test_guidance_lint.py @@ -42,7 +42,6 @@ (r"@location_name_wkt@|@[a-z_]+_wkt@", "WKT placeholders are a legacy-graph mechanism"), (r"Call (it|this) before every `execute_trino_query`|Always call before `execute_trino_query`", "validation is optional (#42)"), (r"NEVER use Hebrew as SQL identifiers", "Hebrew catalog columns are valid (double-quoted)"), - (r"jeen_catalog \(str\)", "enrich_sql_filters takes only sql (#36)"), (r"prefix_pattern", "search_column_values returns all matches; no prefix guessing (#45)"), (r"sql_literal", "resolve_location_to_wkt returns data.wkt (#45)"), (r"error\.category|error\.hint|error_category", "SQL errors carry Trino's own error.name / error.type (#39)"), diff --git a/agent/tests/deep_agent/test_observability.py b/agent/tests/deep_agent/test_observability.py index 2297a9f..eecf5c8 100644 --- a/agent/tests/deep_agent/test_observability.py +++ b/agent/tests/deep_agent/test_observability.py @@ -48,7 +48,7 @@ def reaches(self, run_id, root): STEPS = [ ("get_sample_rows", {"table_name": '"postgres"."public"."flights_table"'}), ("execute_trino_query", {"sql": "SELECT COUNT(*) FROM flights_table WHERE launch_country = 'France'"}), - ("enrich_sql_filters", {"sql": "SELECT 1 FROM flights_table WHERE launch_country = 'צרפת'"}), + ("search_column_values", {"search_term": "צרפת"}), ] @@ -62,24 +62,16 @@ def _policy(messages): @pytest.mark.asyncio async def test_one_trace_tree_with_no_orphans(policy_model): - enrichment_llm = GenericFakeChatModel(messages=iter([AIMessage("pick France")])) - - async def fake_enrich(**kwargs): - # Like the real orchestrator: an LLM call made with the forwarded config. - await enrichment_llm.ainvoke("choose canonical value", config=kwargs["config"]) - return kwargs["initial_sql"], None, False - recorder = RunTreeRecorder() - client = MagicMock(get_catalog_prompt=AsyncMock(return_value="# catalog")) + client = MagicMock(get_catalog_prompt=AsyncMock(return_value="# catalog"), + search_column_values=AsyncMock(return_value={"values": [{"value": "France"}]})) trino = TrinoExecutionResult(success=True, rows=[[466]], columns=["c"], row_count=1, query_id="q-1", execution_time_ms=12) agent = create_deep_agent(model=policy_model(_policy)) config = build_run_config("thread-obs", user_id="u-1", callbacks=[recorder], tracing=False) with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=client), \ - patch.object(sql_tools, "execute_query_sync", return_value=trino), \ - patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=({"t": {}}, ["t"])), \ - patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", side_effect=fake_enrich): + patch.object(sql_tools, "execute_query_sync", return_value=trino): await agent.ainvoke({"messages": [("user", "כמה טיסות")]}, config) roots = recorder.roots() @@ -89,7 +81,7 @@ async def fake_enrich(**kwargs): tool_runs = {r["name"] for r in recorder.runs.values() if r["kind"] == "tool"} assert {name for name, _ in STEPS} <= tool_runs llm_runs = [rid for rid, r in recorder.runs.items() if r["kind"] == "llm"] - assert len(llm_runs) >= len(STEPS) + 2 # agent turns + the enrichment LLM call + assert len(llm_runs) >= len(STEPS) + 1 # one agent turn per tool call + the final one for rid, run in recorder.runs.items(): assert recorder.reaches(rid, root), f"orphan run: {run}" @@ -191,17 +183,13 @@ async def test_real_langfuse_handler_produces_a_single_trace(policy_model): langfuse = Langfuse(public_key="pk-lf-unit-test", secret_key="sk-lf-unit-test", host="http://127.0.0.1:9", span_exporter=exporter, flush_at=1, flush_interval=0.01) - async def fake_enrich(**kwargs): - return kwargs["initial_sql"], None, False - trino = TrinoExecutionResult(success=True, rows=[[1]], columns=["c"], row_count=1, query_id="q-77", execution_time_ms=9) agent = create_deep_agent(model=policy_model(_policy)) with patch.object(observability, "_langfuse_handler", return_value=CallbackHandler(public_key="pk-lf-unit-test")), \ - patch.object(metadata_tools, "get_jeen_metadata_client", return_value=MagicMock(get_catalog_prompt=AsyncMock(return_value="# c"))), \ - patch.object(sql_tools, "execute_query_sync", return_value=trino), \ - patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=({"t": {}}, ["t"])), \ - patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", side_effect=fake_enrich): + patch.object(metadata_tools, "get_jeen_metadata_client", return_value=MagicMock( + get_catalog_prompt=AsyncMock(return_value="# c"), search_column_values=AsyncMock(return_value={"values": []}))), \ + patch.object(sql_tools, "execute_query_sync", return_value=trino): config = build_run_config("thread-lf", user_id="user-lf", tracing=True) await agent.ainvoke({"messages": [("user", "q")]}, config) langfuse.flush() diff --git a/agent/tests/deep_agent/test_tool_contracts.py b/agent/tests/deep_agent/test_tool_contracts.py index 7a67488..933be66 100644 --- a/agent/tests/deep_agent/test_tool_contracts.py +++ b/agent/tests/deep_agent/test_tool_contracts.py @@ -10,7 +10,6 @@ from agent.utils.jeen_metadata_client import JeenMetadataClient, JeenMetadataError from deep_agent import tools from deep_agent.tools import DEEP_AGENT_TOOLS -from deep_agent.tools import enrichment as enrichment_tools from deep_agent.tools import location as location_tools from deep_agent.tools import metadata as metadata_tools from deep_agent.tools import sql as sql_tools @@ -25,7 +24,6 @@ "get_sample_rows": {"table_name": "t"}, "get_column_distinct_values": {"table_name": "t", "column_name": "c"}, "validate_sql": {"sql": "SELECT 1"}, - "enrich_sql_filters": {"sql": "SELECT 1 FROM t WHERE a = 'x'"}, } @@ -48,15 +46,10 @@ def patched(request): trino_res = (TrinoExecutionResult(success=False, error_message="boom", error_name="GENERIC_INTERNAL_ERROR", error_type="INTERNAL_ERROR") if fail else TrinoExecutionResult(success=True, rows=[[1]], columns=["a"], row_count=1)) - enrich = (AsyncMock(side_effect=RuntimeError("llm down")) if fail - else AsyncMock(return_value=("SELECT 1 FROM t WHERE a = 'X'", SimpleNamespace(enrichment_details=[]), True))) with patch.object(metadata_tools, "get_jeen_metadata_client", return_value=_client(fail)), \ - patch.object(enrichment_tools, "get_jeen_metadata_client", return_value=_client(fail)), \ patch.object(sql_tools, "execute_query_sync", return_value=trino_res), \ patch.object(location_tools, "get_geojson_polygon", return_value=None if fail else {"type": "Polygon"}), \ - patch.object(location_tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"), \ - patch("agent.nodes.refiner.parse_jeen_catalog_tables", return_value=("s", ["t"])), \ - patch("agent.services.enrichment_orchestrator.EnrichmentOrchestrator.enrich_query", enrich): + patch.object(location_tools, "geojson_to_simplified_wkt", return_value="'POLYGON((0 0, 1 0, 1 1, 0 0))'"): yield fail @@ -69,7 +62,7 @@ def test_registered_tool_set(): tools whose information the catalog already contains are not offered to the model.""" assert {t.name for t in DEEP_AGENT_TOOLS} == { "search_column_values", "get_column_distinct_values", "resolve_location_to_wkt", - "execute_trino_query", "get_sample_rows", "validate_sql", "enrich_sql_filters", + "execute_trino_query", "get_sample_rows", "validate_sql", } diff --git a/agent/tests/deep_agent/test_validator.py b/agent/tests/deep_agent/test_validator.py index 470c9b4..909b3c0 100644 --- a/agent/tests/deep_agent/test_validator.py +++ b/agent/tests/deep_agent/test_validator.py @@ -308,11 +308,10 @@ def main_policy(messages): def test_reminder_is_not_the_users_words(): from langchain_core.messages import HumanMessage - from deep_agent.context import REMINDER_NAME, current_turn, user_request + from deep_agent.context import REMINDER_NAME, current_turn messages = [HumanMessage("the question"), AIMessage("text"), HumanMessage("submit!", name=REMINDER_NAME)] assert current_turn(messages) == messages[1:] - assert user_request(SimpleNamespace(state={"messages": messages})) == "the question" @pytest.mark.asyncio From 2b470534c942a2c03050251c43649042145a1af7 Mon Sep 17 00:00:00 2001 From: ben ben zvi Date: Mon, 9 Nov 2026 17:20:37 +0200 Subject: [PATCH 37/37] refactor: a separate deep_agent MCP tool instead of the engine switch in chat_with_agent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit chat_with_agent showed both agents' arguments and picked one by engine / AGENT_ENGINE / thread prefix, so half its arguments silently did nothing. Now each agent has its own tool with only its own arguments: chat_with_agent is the legacy graph, deep_agent the Deep Agent. Each refuses the other's threads (deep-… ids). The backend keeps its engine field and uses it to pick the tool; resumes of deep-… threads go to deep_agent. AGENT_ENGINE removed. Co-Authored-By: Claude Opus 5.5 --- agent/README.md | 8 ++-- agent/src/agent/config.py | 1 - agent/src/agent/mcp_server.py | 54 ++++++++++++++++---------- agent/tests/deep_agent/test_service.py | 34 ++++++++-------- backend/app/routers/agent.py | 41 ++++++++++++------- backend/tests/test_agent_engine.py | 26 +++++++++---- 6 files changed, 100 insertions(+), 64 deletions(-) diff --git a/agent/README.md b/agent/README.md index 3f5b001..ea08cf0 100644 --- a/agent/README.md +++ b/agent/README.md @@ -118,13 +118,13 @@ In Langfuse, filter traces by **tag = `deep-agent`** (save it as a view). Disabl ### Serving the deep agent -The UI → backend → agent path is the `chat_with_agent` MCP tool. It runs the legacy graph or the deep agent: +The agent service exposes one MCP tool per agent: `chat_with_agent` (the legacy graph) and `deep_agent`. Each takes only +its own arguments; the backend's `POST /api/agent/chat` picks the tool: | Setting / argument | Effect | |---|---| -| `AGENT_ENGINE=legacy` (default) / `deep` | default engine for new threads | -| `engine` argument (backend `POST /api/agent/chat` body: `"engine": "deep"`) | per-request choice | -| thread id `deep-…` | resumes always go back to the deep agent (and legacy threads to the legacy graph) | +| backend body `"engine": "deep"` | calls `deep_agent`; omitted / `"legacy"` calls `chat_with_agent` | +| thread id `deep-…` | Deep Agent threads; the backend resumes them on `deep_agent`, and each tool refuses the other's threads | | `DEEP_AGENT_CHECKPOINT_DB_URL=postgresql://…` | durable deep-agent threads (shared by replicas, survive restarts); unset = in-memory | | `timeout_s` argument | how long the caller waits; the run is cancelled then (a query already running finishes first). Omitted = no limit. The backend sends 290 (it waits 300). | diff --git a/agent/src/agent/config.py b/agent/src/agent/config.py index 21803d0..8373f95 100644 --- a/agent/src/agent/config.py +++ b/agent/src/agent/config.py @@ -67,7 +67,6 @@ class AgentSettings(BaseSettings): DEEP_AGENT_PROMPT_LABEL: str = "production" # Langfuse prompt label to serve DEEP_AGENT_PROMPT_CACHE_TTL_S: int = Field(default=60, ge=0) # Serving (see deep_agent/service.py) - AGENT_ENGINE: Literal["legacy", "deep"] = "legacy" # default engine for chat_with_agent (per-call `engine` overrides) DEEP_AGENT_CHECKPOINT_DB_URL: str | None = None # postgresql://... for durable deep-agent threads; unset = in-memory # ── Trino connection info for explicit catalog/schema qualification ── diff --git a/agent/src/agent/mcp_server.py b/agent/src/agent/mcp_server.py index 9c72b26..2e32f76 100644 --- a/agent/src/agent/mcp_server.py +++ b/agent/src/agent/mcp_server.py @@ -11,6 +11,8 @@ mcp = FastMCP("Text2SQL Agent") +DEEP_THREAD_PREFIX = "deep-" # Deep Agent thread ids, so a thread is never resumed on the wrong agent + @mcp.tool() @observe() @@ -25,11 +27,10 @@ async def chat_with_agent( active_skills: list[str] | None = None, execution_mode: str | None = None, hitl_enabled: bool = True, - engine: str | None = None, - user_id: str | None = None, - timeout_s: float | None = None, ) -> str: - """Run the Text2SQL agent to answer database queries. + """Run the legacy Text2SQL agent (LangGraph workflow) to answer database queries. + + The Deep Agent is a separate tool: `deep_agent`. Args: query: The natural language question to answer. @@ -43,16 +44,9 @@ async def chat_with_agent( 'high_quality', 'benchmark'). Overrides flag defaults for this invocation only. hitl_enabled: If False, skip all human-in-the-loop interrupts. - engine: 'legacy' (LangGraph workflow) or 'deep' (Deep Agent). Defaults to AGENT_ENGINE. - Threads started on the deep agent are routed back to it on resume. - user_id: End-user id for tracing (Deep Agent). - timeout_s: How long the caller waits (Deep Agent): the run is cancelled when it expires. - Omit for no limit. """ - if _use_deep_agent(engine, thread_id): - return json.dumps(await _deep_chat(connection_id, query, thread_id, resume_value, hitl_enabled, user_id, - timeout_s), - default=str) + if thread_id and thread_id.startswith(DEEP_THREAD_PREFIX): + return json.dumps({"error": f"Thread '{thread_id}' belongs to the Deep Agent — continue it with the deep_agent tool."}) thread_id = thread_id or str(uuid.uuid4()) @@ -224,15 +218,35 @@ async def chat_with_agent( } ) -DEEP_THREAD_PREFIX = "deep-" - +@mcp.tool() +@observe() +async def deep_agent( + connection_id: int, + query: str | None = None, + thread_id: str | None = None, + resume_value: str | dict | None = None, + hitl_enabled: bool = True, + user_id: str | None = None, + timeout_s: float | None = None, +) -> str: + """Run the Deep Agent to answer a question about the connection's data. -def _use_deep_agent(engine: str | None, thread_id: str | None) -> bool: - if thread_id: # a resumed thread stays on the engine that started it - return thread_id.startswith(DEEP_THREAD_PREFIX) - from agent.config import settings + Returns the same response shape as chat_with_agent, plus engine / verification / executed / + semantic_validation / confidence. - return (engine or settings.AGENT_ENGINE) == "deep" + Args: + connection_id: The connection whose catalog the agent answers against. + query: The natural language question (a new thread). + thread_id: Continue a Deep Agent thread (ids start with 'deep-'); omit to start a new one. + resume_value: The user's answer to a clarifying question (a string or {"feedback": ...}). + hitl_enabled: If False, a clarifying question comes back as the completed answer instead of a pause. + user_id: End-user id for tracing. + timeout_s: How long the caller waits: the run is cancelled when it expires. Omit for no limit. + """ + if thread_id and not thread_id.startswith(DEEP_THREAD_PREFIX): + return json.dumps({"error": f"Thread '{thread_id}' belongs to the legacy agent — continue it with chat_with_agent."}) + return json.dumps(await _deep_chat(connection_id, query, thread_id, resume_value, hitl_enabled, user_id, timeout_s), + default=str) async def _deep_chat(connection_id, query, thread_id, resume_value, hitl_enabled, user_id, timeout_s=None) -> dict: diff --git a/agent/tests/deep_agent/test_service.py b/agent/tests/deep_agent/test_service.py index 1c11e5d..3715741 100644 --- a/agent/tests/deep_agent/test_service.py +++ b/agent/tests/deep_agent/test_service.py @@ -172,32 +172,17 @@ async def test_missing_query_is_an_error(): agent=object()) -# ── MCP tool routing ───────────────────────────────────────────────────────── - -@pytest.mark.parametrize("engine, thread_id, default, deep", [ - ("deep", None, "legacy", True), - (None, None, "deep", True), - (None, None, "legacy", False), - ("legacy", "deep-abc", "legacy", True), # a resumed deep thread stays on the deep agent - ("deep", "legacy-thread", "deep", False), # ...and a legacy thread stays legacy -]) -def test_engine_routing(engine, thread_id, default, deep, monkeypatch): - from agent import mcp_server - from agent.config import settings - - monkeypatch.setattr(settings, "AGENT_ENGINE", default) - assert mcp_server._use_deep_agent(engine, thread_id) is deep - +# ── MCP tools ──────────────────────────────────────────────────────────────── @pytest.mark.asyncio @pytest.mark.parametrize("hitl, expected_status", [(True, "interrupted"), (False, "completed")]) -async def test_chat_with_agent_deep_path(hitl, expected_status): +async def test_deep_agent_tool(hitl, expected_status): from agent import mcp_server clarification = to_response("deep-z", {"status": "clarification", "answer": {"needs_clarification": "?"}}, None, []) with patch("deep_agent.service.run_deep_chat", AsyncMock(return_value=clarification)) as run, \ patch.object(mcp_server.agent_graph, "ainvoke") as legacy: - raw = await mcp_server.chat_with_agent(connection_id=89, query="q", engine="deep", hitl_enabled=hitl) + raw = await mcp_server.deep_agent(connection_id=89, query="q", hitl_enabled=hitl) out = json.loads(raw) legacy.assert_not_called() assert run.await_args.kwargs["thread_id"].startswith("deep-") @@ -205,6 +190,19 @@ async def test_chat_with_agent_deep_path(hitl, expected_status): assert out["status"] == expected_status +@pytest.mark.asyncio +async def test_each_tool_refuses_the_other_agents_threads(): + from agent import mcp_server + + with patch("deep_agent.service.run_deep_chat", AsyncMock()) as run, \ + patch.object(mcp_server.agent_graph, "ainvoke") as legacy: + to_legacy = json.loads(await mcp_server.chat_with_agent(connection_id=89, thread_id="deep-abc", resume_value="x")) + to_deep = json.loads(await mcp_server.deep_agent(connection_id=89, thread_id="legacy-thread", resume_value="x")) + assert "deep_agent tool" in to_legacy["error"] and "chat_with_agent" in to_deep["error"] + run.assert_not_awaited() + legacy.assert_not_called() + + # ── durable threads (real Postgres) ────────────────────────────────────────── PG_URL = os.environ.get("DEEP_AGENT_TEST_PG_URL") diff --git a/backend/app/routers/agent.py b/backend/app/routers/agent.py index a5480ab..f4966b1 100644 --- a/backend/app/routers/agent.py +++ b/backend/app/routers/agent.py @@ -57,7 +57,7 @@ class ChatRequest(BaseModel): execution_mode: str | None = None hitl_enabled: bool = True connection_id: int - engine: Literal["legacy", "deep"] | None = None # None -> the agent service's AGENT_ENGINE + engine: Literal["legacy", "deep"] | None = None # which agent answers; None = legacy (a deep-… thread stays deep) class SuggestFixesRequest(BaseModel): @@ -117,10 +117,10 @@ async def _get_jeen_mcp_client(): yield session -async def _call_agent_mcp(tool_arguments: dict) -> dict: +async def _call_agent_mcp(tool_name: str, tool_arguments: dict) -> dict: """ Connects to the agent MCP server over Streamable HTTP, initializes the session, - calls the 'chat_with_agent' tool, and returns the parsed result. + calls `tool_name` (chat_with_agent or deep_agent), and returns the parsed result. """ url = f"{settings.AGENT_URL}/mcp" logger.debug("Connecting to agent MCP: %s args=%s", url, tool_arguments) @@ -132,7 +132,7 @@ async def _call_agent_mcp(tool_arguments: dict) -> dict: # Call the tool using the MCP client session result = await session.call_tool( - "chat_with_agent", + tool_name, arguments=tool_arguments, read_timeout_seconds=timedelta( seconds=settings.AGENT_READ_TIMEOUT_SECONDS @@ -197,6 +197,16 @@ async def _call_agent_mcp(tool_arguments: dict) -> dict: # --------------------------------------------------------------------------- +DEEP_THREAD_PREFIX = "deep-" # the agent service names Deep Agent threads deep-… + + +def _is_deep(request: ChatRequest) -> bool: + """The Deep Agent answers when chosen, and always continues its own threads (resumes don't resend engine).""" + if request.thread_id: + return request.thread_id.startswith(DEEP_THREAD_PREFIX) + return request.engine == "deep" + + @router.post("/chat", response_model=ChatResponse) async def chat(request: ChatRequest) -> ChatResponse: """ @@ -217,22 +227,25 @@ async def chat(request: ChatRequest) -> ChatResponse: else: resume_val = request.resume_value - tool_arguments: dict = { + common: dict = { "query": request.query, "thread_id": request.thread_id, "resume_value": resume_val, - "allowed_tables": request.allowed_tables, - "allowed_statuses": request.allowed_statuses, - "extractors": request.extractors, "hitl_enabled": request.hitl_enabled, "connection_id": request.connection_id, - # the deep agent stops its run then, so its "stopped" reply arrives before we give up - "timeout_s": settings.AGENT_READ_TIMEOUT_SECONDS - AGENT_STOP_MARGIN_S, } - if request.engine is not None: # only sent when chosen, so older agent services keep working - tool_arguments["engine"] = request.engine - - result = await _call_agent_mcp(tool_arguments) + if _is_deep(request): + # the deep agent stops its run then, so its "stopped" reply arrives before we give up + result = await _call_agent_mcp("deep_agent", { + **common, "timeout_s": settings.AGENT_READ_TIMEOUT_SECONDS - AGENT_STOP_MARGIN_S, + }) + else: + result = await _call_agent_mcp("chat_with_agent", { + **common, + "allowed_tables": request.allowed_tables, + "allowed_statuses": request.allowed_statuses, + "extractors": request.extractors, + }) return ChatResponse(**result) diff --git a/backend/tests/test_agent_engine.py b/backend/tests/test_agent_engine.py index 88ed9d7..fa79492 100644 --- a/backend/tests/test_agent_engine.py +++ b/backend/tests/test_agent_engine.py @@ -9,10 +9,13 @@ @patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, return_value=DEEP_RESPONSE) -def test_chat_forwards_engine_and_returns_verification(mock_call, client): - response = client.post("/api/agent/chat", json={"query": "כמה הזמנות", "connection_id": 89, "engine": "deep"}) +def test_deep_engine_calls_the_deep_agent_tool(mock_call, client): + response = client.post("/api/agent/chat", json={"query": "כמה הזמנות", "connection_id": 89, "engine": "deep", + "allowed_tables": ["t"]}) assert response.status_code == 200, response.text - assert mock_call.await_args.args[0]["engine"] == "deep" + tool, args = mock_call.await_args.args + assert tool == "deep_agent" and "engine" not in args + assert "allowed_tables" not in args # legacy-only arguments are not sent to the deep agent body = response.json() assert body["engine"] == "deep" and body["verification"] == "matched" and body["confidence"] == "high" assert body["executed"] is True and body["recovered_from_text"] is False @@ -25,18 +28,27 @@ def test_chat_tells_the_agent_how_long_it_waits(mock_call, client): client.post("/api/agent/chat", json={"query": "q", "connection_id": 89, "engine": "deep"}) wait = settings.AGENT_READ_TIMEOUT_SECONDS - assert mock_call.await_args.args[0]["timeout_s"] == wait - AGENT_STOP_MARGIN_S < wait + assert mock_call.await_args.args[1]["timeout_s"] == wait - AGENT_STOP_MARGIN_S < wait @patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, return_value={"thread_id": "t", "status": "completed", "summary": "ok"}) -def test_chat_omits_engine_when_not_chosen(mock_call, client): - response = client.post("/api/agent/chat", json={"query": "q", "connection_id": 89}) +def test_default_calls_the_legacy_tool(mock_call, client): + response = client.post("/api/agent/chat", json={"query": "q", "connection_id": 89, "allowed_tables": ["t"]}) assert response.status_code == 200, response.text - assert "engine" not in mock_call.await_args.args[0] + tool, args = mock_call.await_args.args + assert tool == "chat_with_agent" and args["allowed_tables"] == ["t"] + assert "engine" not in args and "timeout_s" not in args assert response.json()["engine"] is None +@patch("app.routers.agent._call_agent_mcp", new_callable=AsyncMock, return_value=DEEP_RESPONSE) +def test_resuming_a_deep_thread_stays_on_the_deep_agent(mock_call, client): + response = client.post("/api/agent/chat", json={"thread_id": "deep-123", "resume_value": "חיפה", "connection_id": 89}) + assert response.status_code == 200, response.text + assert mock_call.await_args.args[0] == "deep_agent" + + def test_chat_rejects_unknown_engine(client): response = client.post("/api/agent/chat", json={"query": "q", "connection_id": 89, "engine": "gpt"}) assert response.status_code == 422