@deepagents/text2sql 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1741,333 +1741,14 @@ import {
1741
1741
  user as user4
1742
1742
  } from "@deepagents/agent";
1743
1743
 
1744
- // packages/text2sql/src/lib/agents/bi.agent.ts
1744
+ // packages/text2sql/src/lib/agents/chat1.agent.ts
1745
1745
  import { groq as groq6 } from "@ai-sdk/groq";
1746
1746
  import { tool as tool3 } from "ai";
1747
- import dedent4 from "dedent";
1748
1747
  import z6 from "zod";
1749
1748
  import { agent as agent6, toState as toState3 } from "@deepagents/agent";
1750
1749
  import { scratchpad_tool as scratchpad_tool3 } from "@deepagents/toolbox";
1751
1750
  var tools3 = {
1752
- /**
1753
- * Validate SQL query syntax without executing.
1754
- * Use this to verify queries are correct before embedding in dashboard components.
1755
- */
1756
- validate_query: tool3({
1757
- description: dedent4`
1758
- Validate SQL query syntax before embedding in dashboard components.
1759
- Use this to verify your queries are syntactically correct and reference valid tables/columns.
1760
-
1761
- This tool does NOT execute the query or return data.
1762
- Only SELECT or WITH statements are allowed.
1763
- `,
1764
- inputSchema: z6.object({
1765
- reasoning: z6.string().describe(
1766
- "Why this query helps understand the data for dashboard design."
1767
- ),
1768
- sql: z6.string().min(1, { message: "SQL query cannot be empty." }).refine(
1769
- (sql) => sql.trim().toUpperCase().startsWith("SELECT") || sql.trim().toUpperCase().startsWith("WITH"),
1770
- {
1771
- message: "Only read-only SELECT or WITH queries are allowed."
1772
- }
1773
- ).describe("The SQL query to validate.")
1774
- }),
1775
- execute: async ({ sql }, options) => {
1776
- const state = toState3(options);
1777
- const result = await state.adapter.validate(sql);
1778
- if (typeof result === "string") {
1779
- return { valid: false, error: result };
1780
- }
1781
- return { valid: true };
1782
- }
1783
- }),
1784
- /**
1785
- * Record insights and reasoning during schema analysis and dashboard design.
1786
- */
1787
- scratchpad: scratchpad_tool3
1788
- };
1789
- var COMPONENTS_DOC = dedent4`
1790
- ## Available Components
1791
-
1792
- You output markdown with embedded HTML custom elements. Use kebab-case tags with closing tags.
1793
-
1794
- ### Chart Components
1795
-
1796
- #### Area Charts
1797
- | Component | Required Props | Optional Props | Use Case |
1798
- |-----------|----------------|----------------|----------|
1799
- | \`<area-chart>\` | \`title\`, \`sql\` | \`x-key\`, \`y-key\`, \`variant\` | Cumulative values, trends with volume |
1800
-
1801
- **Variants** (use \`variant\` prop):
1802
- - \`default\` - Basic area with smooth curves
1803
- - \`linear\` - Sharp-edged lines showing precise changes
1804
- - \`step\` - Step-based segments for discrete data
1805
- - \`stacked\` - Multiple series stacked on top of each other
1806
- - \`stacked-expand\` - Normalized to 100% showing percentage contribution
1807
- - \`gradient\` - Filled with gradient for visual depth
1808
-
1809
- #### Bar Charts
1810
- | Component | Required Props | Optional Props | Use Case |
1811
- |-----------|----------------|----------------|----------|
1812
- | \`<bar-chart>\` | \`title\`, \`sql\` | \`x-key\`, \`y-key\`, \`variant\`, \`orientation\` | Categorical comparisons, grouped data |
1813
-
1814
- **Variants** (use \`variant\` prop):
1815
- - \`default\` - Basic vertical bars
1816
- - \`multiple\` - Multiple series side by side
1817
- - \`stacked\` - Multiple series stacked
1818
- - \`labeled\` - With value labels on bars
1819
- - \`negative\` - Supports positive/negative values with conditional coloring
1820
- - \`mixed\` - Different colors per category
1821
-
1822
- **Orientation** (use \`orientation\` prop):
1823
- - \`vertical\` (default) - Vertical bars
1824
- - \`horizontal\` - Horizontal bars (good for long category names)
1825
-
1826
- #### Line Charts
1827
- | Component | Required Props | Optional Props | Use Case |
1828
- |-----------|----------------|----------------|----------|
1829
- | \`<line-chart>\` | \`title\`, \`sql\` | \`x-key\`, \`y-key\`, \`variant\` | Trends over time, continuous data |
1830
-
1831
- **Variants** (use \`variant\` prop):
1832
- - \`default\` - Smooth curved lines
1833
- - \`linear\` - Straight lines between points
1834
- - \`step\` - Step-based transitions
1835
- - \`dots\` - Lines with visible data point markers
1836
- - \`multiple\` - Multiple series for comparisons (A/B testing, etc.)
1837
- - \`interactive\` - With metric switching capability
1838
- - \`labeled\` - With value labels at each point
1839
-
1840
- #### Pie & Donut Charts
1841
- | Component | Required Props | Optional Props | Use Case |
1842
- |-----------|----------------|----------------|----------|
1843
- | \`<pie-chart>\` | \`title\`, \`sql\` | \`label-key\`, \`value-key\`, \`variant\` | Part-to-whole relationships, distributions |
1844
- | \`<donut-chart>\` | \`title\`, \`sql\` | \`label-key\`, \`value-key\`, \`variant\` | Same as pie but with center space for text/KPI |
1845
-
1846
- **Variants** (use \`variant\` prop):
1847
- - \`default\` - Basic pie/donut
1848
- - \`labeled\` - With labels on segments
1849
- - \`legend\` - With external legend
1850
- - \`interactive\` - With hover highlighting and selection
1851
- - \`stacked\` - Multiple concentric rings for comparison
1852
-
1853
- #### Radar Charts
1854
- | Component | Required Props | Optional Props | Use Case |
1855
- |-----------|----------------|----------------|----------|
1856
- | \`<radar-chart>\` | \`title\`, \`sql\` | \`label-key\`, \`value-key\`, \`variant\` | Multi-dimensional comparisons, skill assessments |
1857
-
1858
- **Variants** (use \`variant\` prop):
1859
- - \`default\` - Basic radar with polygon grid
1860
- - \`dots\` - With visible data point markers
1861
- - \`filled\` - With filled area
1862
- - \`multiple\` - Multiple series overlapping
1863
- - \`circle\` - Circular grid instead of polygon
1864
- - \`legend\` - With integrated legend
1865
-
1866
- #### Radial Charts
1867
- | Component | Required Props | Optional Props | Use Case |
1868
- |-----------|----------------|----------------|----------|
1869
- | \`<radial-chart>\` | \`title\`, \`sql\` | \`value-key\`, \`variant\` | Progress indicators, gauges, circular metrics |
1870
-
1871
- **Variants** (use \`variant\` prop):
1872
- - \`default\` - Basic radial bars from center outward
1873
- - \`text\` - With centered value/caption text
1874
- - \`shape\` - Gauge-style arc (not full circle)
1875
- - \`stacked\` - Concentric arcs for multiple metrics
1876
- - \`grid\` - With background grid rings
1877
-
1878
- #### KPI Component
1879
- | Component | Required Props | Optional Props | Use Case |
1880
- |-----------|----------------|----------------|----------|
1881
- | \`<kpi>\` | \`title\`, \`sql\` | \`variant\`, \`format\`, \`trend-sql\`, \`target\`, \`icon\`, \`description\`, \`color\` | Rich metric displays with trends, progress, sparklines |
1882
-
1883
- **Variants** (use \`variant\` prop):
1884
- - \`default\` - Simple value card
1885
- - \`trend\` - Value with change indicator (↑12.5% or ↓3.2%)
1886
- - \`comparison\` - Value with previous period value shown
1887
- - \`progress\` - Value with horizontal progress bar toward target
1888
- - \`ring\` - Value with circular progress gauge toward target
1889
- - \`sparkline\` - Value with mini area chart showing recent trend
1890
-
1891
- **Props Reference**:
1892
- - \`title\` (required) - Display label
1893
- - \`sql\` (required) - Query returning \`{ value: number }\`
1894
- - \`variant\` - Display style (see above)
1895
- - \`format\` - Value format: \`currency\`, \`percent\`, \`number\`, \`compact\`, \`duration\`
1896
- - \`trend-sql\` - Query for trend data:
1897
- - For \`trend\`/\`comparison\`: returns \`{ change: number }\` or \`{ previous: number }\`
1898
- - For \`sparkline\`: returns time-series \`[{ date, value }]\`
1899
- - \`target\` - Target value for \`progress\`/\`ring\` variants
1900
- - \`icon\` - Icon identifier: \`dollar\`, \`users\`, \`cart\`, \`chart\`, \`percent\`, \`clock\`
1901
- - \`description\` - Subtitle/context text
1902
- - \`color\` - Accent color: \`positive\` (green), \`negative\` (red), \`neutral\`, \`primary\`
1903
-
1904
- #### Data Table
1905
- | Component | Required Props | Optional Props | Use Case |
1906
- |-----------|----------------|----------------|----------|
1907
- | \`<data-table>\` | \`title\`, \`sql\` | \`columns\` | Detailed data, lists, rankings |
1908
-
1909
- ### Layout Components
1910
- | Component | Props | Description |
1911
- |-----------|-------|-------------|
1912
- | \`<row>\` | \`gap?\` | Horizontal flex container (small, medium, or large) |
1913
- | \`<column>\` | \`span\` (1-12) | Column within row, 12-column grid |
1914
- | \`<grid>\` | \`cols\`, \`gap?\` | CSS Grid container |
1915
-
1916
- ### Chart Selection Guide
1917
- - **Time series / Trends with volume**: Use \`<area-chart>\` (shows magnitude over time)
1918
- - **Time series / Precise trends**: Use \`<line-chart>\` (clean trend lines)
1919
- - **Categories / Comparisons**: Use \`<bar-chart>\`
1920
- - **Part-to-whole / Proportions**: Use \`<pie-chart>\` or \`<donut-chart>\`
1921
- - **Multi-dimensional comparisons**: Use \`<radar-chart>\` (e.g., comparing skills, features)
1922
- - **Progress / Gauges**: Use \`<radial-chart>\` (circular progress indicators)
1923
- - **Detailed data / Rankings**: Use \`<data-table>\`
1924
- - **Single metrics**: Use \`<kpi>\` with appropriate variant:
1925
- - Simple value → \`default\`
1926
- - Value with change indicator → \`trend\`
1927
- - Value vs previous period → \`comparison\`
1928
- - Value toward goal → \`progress\` or \`ring\`
1929
- - Value with recent history → \`sparkline\`
1930
-
1931
- ### Example Output
1932
- \`\`\`markdown
1933
- ## Sales Dashboard
1934
-
1935
- <row>
1936
- <column span="3">
1937
- <kpi
1938
- title="Total Revenue"
1939
- sql="SELECT SUM(amount) as value FROM orders"
1940
- trend-sql="SELECT ((SUM(CASE WHEN created_at >= NOW() - INTERVAL '30 days' THEN amount END) - SUM(CASE WHEN created_at >= NOW() - INTERVAL '60 days' AND created_at < NOW() - INTERVAL '30 days' THEN amount END)) / NULLIF(SUM(CASE WHEN created_at >= NOW() - INTERVAL '60 days' AND created_at < NOW() - INTERVAL '30 days' THEN amount END), 0) * 100) as change FROM orders"
1941
- variant="trend"
1942
- format="currency"
1943
- icon="dollar">
1944
- </kpi>
1945
- </column>
1946
- <column span="3">
1947
- <kpi
1948
- title="Orders Today"
1949
- sql="SELECT COUNT(*) as value FROM orders WHERE DATE(created_at) = CURRENT_DATE"
1950
- trend-sql="SELECT DATE(created_at) as date, COUNT(*) as value FROM orders WHERE created_at >= NOW() - INTERVAL '7 days' GROUP BY 1 ORDER BY 1"
1951
- variant="sparkline"
1952
- icon="cart">
1953
- </kpi>
1954
- </column>
1955
- <column span="3">
1956
- <kpi
1957
- title="Sales Target"
1958
- sql="SELECT SUM(amount) as value FROM orders WHERE EXTRACT(QUARTER FROM created_at) = EXTRACT(QUARTER FROM NOW())"
1959
- target="100000"
1960
- variant="progress"
1961
- format="currency"
1962
- description="Q4 2024 Goal">
1963
- </kpi>
1964
- </column>
1965
- <column span="3">
1966
- <kpi
1967
- title="Conversion Rate"
1968
- sql="SELECT (COUNT(DISTINCT buyer_id)::float / COUNT(DISTINCT visitor_id) * 100) as value FROM sessions"
1969
- variant="ring"
1970
- target="100"
1971
- format="percent"
1972
- color="primary">
1973
- </kpi>
1974
- </column>
1975
- </row>
1976
-
1977
- <row>
1978
- <column span="8">
1979
- <area-chart
1980
- title="Revenue Over Time"
1981
- sql="SELECT DATE_TRUNC('month', created_at) as month, SUM(amount) as revenue FROM orders GROUP BY 1 ORDER BY 1"
1982
- x-key="month"
1983
- y-key="revenue"
1984
- variant="gradient">
1985
- </area-chart>
1986
- </column>
1987
- <column span="4">
1988
- <donut-chart
1989
- title="Revenue by Category"
1990
- sql="SELECT category, SUM(amount) as revenue FROM orders GROUP BY category"
1991
- label-key="category"
1992
- value-key="revenue"
1993
- variant="interactive">
1994
- </donut-chart>
1995
- </column>
1996
- </row>
1997
-
1998
- <row>
1999
- <column span="6">
2000
- <bar-chart
2001
- title="Monthly Comparison"
2002
- sql="SELECT DATE_TRUNC('month', created_at) as month, SUM(CASE WHEN EXTRACT(YEAR FROM created_at) = 2024 THEN amount END) as this_year, SUM(CASE WHEN EXTRACT(YEAR FROM created_at) = 2023 THEN amount END) as last_year FROM orders GROUP BY 1"
2003
- variant="multiple"
2004
- x-key="month">
2005
- </bar-chart>
2006
- </column>
2007
- <column span="6">
2008
- <radar-chart
2009
- title="Product Performance"
2010
- sql="SELECT metric, score FROM product_metrics WHERE product_id = 1"
2011
- label-key="metric"
2012
- value-key="score"
2013
- variant="filled">
2014
- </radar-chart>
2015
- </column>
2016
- </row>
2017
-
2018
- <data-table
2019
- title="Top 10 Products"
2020
- sql="SELECT name, SUM(quantity) as sold, SUM(amount) as revenue FROM order_items GROUP BY name ORDER BY revenue DESC LIMIT 10">
2021
- </data-table>
2022
- \`\`\`
2023
- `;
2024
- var biAgent = agent6({
2025
- model: groq6("gpt-oss-20b"),
2026
- tools: tools3,
2027
- name: "bi_agent",
2028
- prompt: (state) => {
2029
- return dedent4`
2030
- You are an expert BI analyst that creates dashboard specifications using HTML custom elements.
2031
-
2032
- ${COMPONENTS_DOC}
2033
-
2034
- ## Your Workflow
2035
-
2036
- 1. **PLAN**: Analyze the request and schema to determine what metrics/visualizations to create
2037
- 2. **VALIDATE**: Use \`validate_query\` to verify SQL syntax is correct before embedding
2038
- 3. **OUTPUT**: Generate the dashboard using layout and chart components
2039
-
2040
- ## Critical Rules
2041
-
2042
- - **Design from schema**: Use the provided schema introspection to understand available tables, columns, and relationships
2043
- - **Validate all queries**: Use \`validate_query\` to ensure SQL is syntactically correct before embedding in components
2044
- - **Use kebab-case HTML tags** with closing tags (e.g., \`<bar-chart></bar-chart>\`)
2045
- - Use \`scratchpad\` to record schema analysis insights and design decisions
2046
- - Choose chart types based on column types (dates → line/area, categories → bar/pie, numbers → KPI)
2047
- - Use layout components (row, column, grid) to organize the dashboard
2048
- - Include a text introduction explaining what the dashboard shows
2049
-
2050
- ## SQL Rules
2051
-
2052
- - Only SELECT or WITH statements
2053
- - Use proper date/time functions for the database
2054
- - Include appropriate GROUP BY, ORDER BY clauses
2055
- - Use aliases for calculated columns
2056
-
2057
- ${state?.teachings || ""}
2058
- ${state?.introspection || ""}
2059
- `;
2060
- }
2061
- });
2062
-
2063
- // packages/text2sql/src/lib/agents/chat1.agent.ts
2064
- import { groq as groq7 } from "@ai-sdk/groq";
2065
- import { tool as tool4 } from "ai";
2066
- import z7 from "zod";
2067
- import { agent as agent7, toState as toState4 } from "@deepagents/agent";
2068
- import { scratchpad_tool as scratchpad_tool4 } from "@deepagents/toolbox";
2069
- var tools4 = {
2070
- query_database: tool4({
1751
+ query_database: tool3({
2071
1752
  description: `Query the database to answer a question. Provide your question in natural language and this tool will:
2072
1753
  1. Generate the appropriate SQL query
2073
1754
  2. Validate the SQL syntax
@@ -2075,16 +1756,16 @@ var tools4 = {
2075
1756
  4. Return the results
2076
1757
 
2077
1758
  Use this tool when you need to retrieve data to answer the user's question.`,
2078
- inputSchema: z7.object({
2079
- question: z7.string().min(1).describe(
1759
+ inputSchema: z6.object({
1760
+ question: z6.string().min(1).describe(
2080
1761
  "The question to answer, expressed in natural language. Be specific about what data you need."
2081
1762
  ),
2082
- reasoning: z7.string().optional().describe(
1763
+ reasoning: z6.string().optional().describe(
2083
1764
  "Your reasoning for why this query is needed to answer the user."
2084
1765
  )
2085
1766
  }),
2086
1767
  execute: async ({ question }, options) => {
2087
- const state = toState4(options);
1768
+ const state = toState3(options);
2088
1769
  try {
2089
1770
  const sqlResult = await toSql({
2090
1771
  input: question,
@@ -2112,12 +1793,12 @@ Use this tool when you need to retrieve data to answer the user's question.`,
2112
1793
  }
2113
1794
  }
2114
1795
  }),
2115
- scratchpad: scratchpad_tool4
1796
+ scratchpad: scratchpad_tool3
2116
1797
  };
2117
- var chat1Agent = agent7({
1798
+ var chat1Agent = agent6({
2118
1799
  name: "chat1-combined",
2119
- model: groq7("openai/gpt-oss-20b"),
2120
- tools: tools4,
1800
+ model: groq6("openai/gpt-oss-20b"),
1801
+ tools: tools3,
2121
1802
  prompt: (state) => {
2122
1803
  return `
2123
1804
  ${state?.teachings || ""}
@@ -2127,13 +1808,13 @@ ${state?.introspection || ""}
2127
1808
  });
2128
1809
 
2129
1810
  // packages/text2sql/src/lib/agents/chat2.agent.ts
2130
- import { groq as groq8 } from "@ai-sdk/groq";
2131
- import { tool as tool5 } from "ai";
2132
- import z8 from "zod";
2133
- import { agent as agent8, toState as toState5 } from "@deepagents/agent";
2134
- import { scratchpad_tool as scratchpad_tool5 } from "@deepagents/toolbox";
2135
- var tools5 = {
2136
- generate_sql: tool5({
1811
+ import { groq as groq7 } from "@ai-sdk/groq";
1812
+ import { tool as tool4 } from "ai";
1813
+ import z7 from "zod";
1814
+ import { agent as agent7, toState as toState4 } from "@deepagents/agent";
1815
+ import { scratchpad_tool as scratchpad_tool4 } from "@deepagents/toolbox";
1816
+ var tools4 = {
1817
+ generate_sql: tool4({
2137
1818
  description: `Generate a SQL query from a natural language question. This tool will:
2138
1819
  1. Translate your question into SQL
2139
1820
  2. Validate the SQL syntax
@@ -2144,14 +1825,14 @@ Use this BEFORE execute_sql to see what query will be run. You can then:
2144
1825
  - Explain the approach to the user
2145
1826
  - Decide if the SQL looks correct
2146
1827
  - Refine your question and regenerate if needed`,
2147
- inputSchema: z8.object({
2148
- question: z8.string().min(1).describe(
1828
+ inputSchema: z7.object({
1829
+ question: z7.string().min(1).describe(
2149
1830
  "The question to translate into SQL. Be specific about what data you need."
2150
1831
  ),
2151
- reasoning: z8.string().optional().describe("Your reasoning for why this data is needed.")
1832
+ reasoning: z7.string().optional().describe("Your reasoning for why this data is needed.")
2152
1833
  }),
2153
1834
  execute: async ({ question }, options) => {
2154
- const state = toState5(options);
1835
+ const state = toState4(options);
2155
1836
  try {
2156
1837
  const sqlResult = await toSql({
2157
1838
  input: question,
@@ -2179,21 +1860,21 @@ Use this BEFORE execute_sql to see what query will be run. You can then:
2179
1860
  }
2180
1861
  }
2181
1862
  }),
2182
- execute_sql: tool5({
1863
+ execute_sql: tool4({
2183
1864
  description: `Execute a SQL query and return the results. Use this AFTER generate_sql to run the query.
2184
1865
 
2185
1866
  Only SELECT and WITH (CTE) queries are allowed - no data modification.`,
2186
- inputSchema: z8.object({
2187
- sql: z8.string().min(1).refine(
1867
+ inputSchema: z7.object({
1868
+ sql: z7.string().min(1).refine(
2188
1869
  (sql) => sql.trim().toUpperCase().startsWith("SELECT") || sql.trim().toUpperCase().startsWith("WITH"),
2189
1870
  {
2190
1871
  message: "Only read-only SELECT or WITH queries are allowed."
2191
1872
  }
2192
1873
  ).describe("The SQL query to execute (must be SELECT or WITH)."),
2193
- reasoning: z8.string().optional().describe("Brief explanation of what this query retrieves.")
1874
+ reasoning: z7.string().optional().describe("Brief explanation of what this query retrieves.")
2194
1875
  }),
2195
1876
  execute: async ({ sql }, options) => {
2196
- const state = toState5(options);
1877
+ const state = toState4(options);
2197
1878
  try {
2198
1879
  const data = await state.adapter.execute(sql);
2199
1880
  return {
@@ -2209,12 +1890,12 @@ Only SELECT and WITH (CTE) queries are allowed - no data modification.`,
2209
1890
  }
2210
1891
  }
2211
1892
  }),
2212
- scratchpad: scratchpad_tool5
1893
+ scratchpad: scratchpad_tool4
2213
1894
  };
2214
- var chat2Agent = agent8({
1895
+ var chat2Agent = agent7({
2215
1896
  name: "chat2-with-peek",
2216
- model: groq8("openai/gpt-oss-20b"),
2217
- tools: tools5,
1897
+ model: groq7("openai/gpt-oss-20b"),
1898
+ tools: tools4,
2218
1899
  prompt: (state) => {
2219
1900
  return `
2220
1901
  ${state?.teachings || ""}
@@ -2232,34 +1913,34 @@ If the generated SQL doesn't look right, you can refine your question and regene
2232
1913
  });
2233
1914
 
2234
1915
  // packages/text2sql/src/lib/agents/chat3.agent.ts
2235
- import { groq as groq9 } from "@ai-sdk/groq";
2236
- import { defaultSettingsMiddleware as defaultSettingsMiddleware2, tool as tool6, wrapLanguageModel as wrapLanguageModel2 } from "ai";
2237
- import z9 from "zod";
2238
- import { agent as agent9, generate as generate3, toState as toState6, user as user2 } from "@deepagents/agent";
2239
- import { scratchpad_tool as scratchpad_tool6 } from "@deepagents/toolbox";
2240
- var collaborativeSqlOutputSchema = z9.discriminatedUnion("status", [
2241
- z9.object({
2242
- status: z9.literal("success"),
2243
- sql: z9.string().describe("The generated SQL query"),
2244
- confidence: z9.enum(["high", "medium", "low"]).describe("Confidence level in this SQL being correct"),
2245
- assumptions: z9.array(z9.string()).optional().describe("Assumptions made during SQL generation"),
2246
- reasoning: z9.string().optional().describe("Brief explanation of the query approach")
1916
+ import { groq as groq8 } from "@ai-sdk/groq";
1917
+ import { defaultSettingsMiddleware as defaultSettingsMiddleware2, tool as tool5, wrapLanguageModel as wrapLanguageModel2 } from "ai";
1918
+ import z8 from "zod";
1919
+ import { agent as agent8, generate as generate3, toState as toState5, user as user2 } from "@deepagents/agent";
1920
+ import { scratchpad_tool as scratchpad_tool5 } from "@deepagents/toolbox";
1921
+ var collaborativeSqlOutputSchema = z8.discriminatedUnion("status", [
1922
+ z8.object({
1923
+ status: z8.literal("success"),
1924
+ sql: z8.string().describe("The generated SQL query"),
1925
+ confidence: z8.enum(["high", "medium", "low"]).describe("Confidence level in this SQL being correct"),
1926
+ assumptions: z8.array(z8.string()).optional().describe("Assumptions made during SQL generation"),
1927
+ reasoning: z8.string().optional().describe("Brief explanation of the query approach")
2247
1928
  }),
2248
- z9.object({
2249
- status: z9.literal("clarification_needed"),
2250
- question: z9.string().describe("Question to clarify the request"),
2251
- context: z9.string().optional().describe("Why this clarification is needed"),
2252
- options: z9.array(z9.string()).optional().describe("Possible options if applicable")
1929
+ z8.object({
1930
+ status: z8.literal("clarification_needed"),
1931
+ question: z8.string().describe("Question to clarify the request"),
1932
+ context: z8.string().optional().describe("Why this clarification is needed"),
1933
+ options: z8.array(z8.string()).optional().describe("Possible options if applicable")
2253
1934
  }),
2254
- z9.object({
2255
- status: z9.literal("unanswerable"),
2256
- reason: z9.string().describe("Why this question cannot be answered"),
2257
- suggestions: z9.array(z9.string()).optional().describe("Alternative questions that could be answered")
1935
+ z8.object({
1936
+ status: z8.literal("unanswerable"),
1937
+ reason: z8.string().describe("Why this question cannot be answered"),
1938
+ suggestions: z8.array(z8.string()).optional().describe("Alternative questions that could be answered")
2258
1939
  })
2259
1940
  ]);
2260
- var collaborativeSqlAgent = agent9({
1941
+ var collaborativeSqlAgent = agent8({
2261
1942
  name: "collaborative-sql",
2262
- model: groq9("openai/gpt-oss-20b"),
1943
+ model: groq8("openai/gpt-oss-20b"),
2263
1944
  output: collaborativeSqlOutputSchema,
2264
1945
  prompt: (state) => {
2265
1946
  return `
@@ -2293,8 +1974,8 @@ Prefer asking for clarification over making low-confidence guesses.
2293
1974
  `;
2294
1975
  }
2295
1976
  });
2296
- var tools6 = {
2297
- consult_sql_agent: tool6({
1977
+ var tools5 = {
1978
+ consult_sql_agent: tool5({
2298
1979
  description: `Consult the SQL specialist agent to generate a query. The SQL agent may:
2299
1980
  - Return a SQL query with confidence level and assumptions
2300
1981
  - Ask for clarification if the question is ambiguous
@@ -2304,15 +1985,15 @@ Based on the response:
2304
1985
  - If clarification is needed, you can provide context or ask the user
2305
1986
  - If assumptions were made, verify them with the user for important queries
2306
1987
  - If unanswerable, relay the suggestions to the user`,
2307
- inputSchema: z9.object({
2308
- question: z9.string().min(1).describe("The question to translate into SQL."),
2309
- context: z9.string().optional().describe("Additional context from the conversation that might help."),
2310
- previousClarification: z9.string().optional().describe(
1988
+ inputSchema: z8.object({
1989
+ question: z8.string().min(1).describe("The question to translate into SQL."),
1990
+ context: z8.string().optional().describe("Additional context from the conversation that might help."),
1991
+ previousClarification: z8.string().optional().describe(
2311
1992
  "Answer to a previous clarification question from the SQL agent."
2312
1993
  )
2313
1994
  }),
2314
1995
  execute: async ({ question, context: context2, previousClarification }, options) => {
2315
- const state = toState6(options);
1996
+ const state = toState5(options);
2316
1997
  try {
2317
1998
  let fullQuestion = question;
2318
1999
  if (context2) {
@@ -2382,11 +2063,11 @@ Clarification provided: ${previousClarification}`;
2382
2063
  }
2383
2064
  }
2384
2065
  }),
2385
- execute_sql: tool6({
2066
+ execute_sql: tool5({
2386
2067
  description: `Execute a SQL query directly. Use this when you have SQL that you want to run
2387
2068
  (e.g., after receiving SQL from consult_sql_agent or for follow-up queries).`,
2388
- inputSchema: z9.object({
2389
- sql: z9.string().min(1).refine(
2069
+ inputSchema: z8.object({
2070
+ sql: z8.string().min(1).refine(
2390
2071
  (sql) => sql.trim().toUpperCase().startsWith("SELECT") || sql.trim().toUpperCase().startsWith("WITH"),
2391
2072
  {
2392
2073
  message: "Only read-only SELECT or WITH queries are allowed."
@@ -2394,7 +2075,7 @@ Clarification provided: ${previousClarification}`;
2394
2075
  ).describe("The SQL query to execute.")
2395
2076
  }),
2396
2077
  execute: async ({ sql }, options) => {
2397
- const state = toState6(options);
2078
+ const state = toState5(options);
2398
2079
  try {
2399
2080
  const validationError = await state.adapter.validate(sql);
2400
2081
  if (validationError) {
@@ -2417,12 +2098,12 @@ Clarification provided: ${previousClarification}`;
2417
2098
  }
2418
2099
  }
2419
2100
  }),
2420
- scratchpad: scratchpad_tool6
2101
+ scratchpad: scratchpad_tool5
2421
2102
  };
2422
- var chat3Agent = agent9({
2103
+ var chat3Agent = agent8({
2423
2104
  name: "chat3-collaborative",
2424
- model: groq9("openai/gpt-oss-20b"),
2425
- tools: tools6,
2105
+ model: groq8("openai/gpt-oss-20b"),
2106
+ tools: tools5,
2426
2107
  prompt: (state) => {
2427
2108
  return `
2428
2109
  ${state?.teachings || ""}
@@ -2442,39 +2123,39 @@ For clarification requests, try to answer from conversation context first before
2442
2123
  });
2443
2124
 
2444
2125
  // packages/text2sql/src/lib/agents/chat4.agent.ts
2445
- import { groq as groq10 } from "@ai-sdk/groq";
2446
- import { defaultSettingsMiddleware as defaultSettingsMiddleware3, tool as tool7, wrapLanguageModel as wrapLanguageModel3 } from "ai";
2447
- import z10 from "zod";
2448
- import { agent as agent10, generate as generate4, toState as toState7, user as user3 } from "@deepagents/agent";
2449
- import { scratchpad_tool as scratchpad_tool7 } from "@deepagents/toolbox";
2450
- var questionDecompositionSchema = z10.object({
2451
- originalQuestion: z10.string().describe("The original question being decomposed"),
2452
- breakdown: z10.array(z10.string()).min(1).describe(
2126
+ import { groq as groq9 } from "@ai-sdk/groq";
2127
+ import { defaultSettingsMiddleware as defaultSettingsMiddleware3, tool as tool6, wrapLanguageModel as wrapLanguageModel3 } from "ai";
2128
+ import z9 from "zod";
2129
+ import { agent as agent9, generate as generate4, toState as toState6, user as user3 } from "@deepagents/agent";
2130
+ import { scratchpad_tool as scratchpad_tool6 } from "@deepagents/toolbox";
2131
+ var questionDecompositionSchema = z9.object({
2132
+ originalQuestion: z9.string().describe("The original question being decomposed"),
2133
+ breakdown: z9.array(z9.string()).min(1).describe(
2453
2134
  "Semantic breakdown of the question into its component parts. Each part describes an aspect of what is being asked, NOT how to implement it."
2454
2135
  ),
2455
- entities: z10.array(z10.string()).optional().describe(
2136
+ entities: z9.array(z9.string()).optional().describe(
2456
2137
  "Key entities/concepts mentioned (e.g., customers, orders, products)"
2457
2138
  ),
2458
- filters: z10.array(z10.string()).optional().describe(
2139
+ filters: z9.array(z9.string()).optional().describe(
2459
2140
  'Filtering criteria mentioned (e.g., "last quarter", "above $100")'
2460
2141
  ),
2461
- aggregation: z10.string().optional().describe(
2142
+ aggregation: z9.string().optional().describe(
2462
2143
  'Type of aggregation if any (e.g., "count", "sum", "average", "top N")'
2463
2144
  ),
2464
- ambiguities: z10.array(z10.string()).optional().describe("Any ambiguous parts that might need clarification")
2145
+ ambiguities: z9.array(z9.string()).optional().describe("Any ambiguous parts that might need clarification")
2465
2146
  });
2466
- var decompositionSqlOutputSchema = z10.union([
2467
- z10.object({
2468
- sql: z10.string().describe("The SQL query that answers the decomposed question"),
2469
- reasoning: z10.string().optional().describe("How each breakdown component was addressed")
2147
+ var decompositionSqlOutputSchema = z9.union([
2148
+ z9.object({
2149
+ sql: z9.string().describe("The SQL query that answers the decomposed question"),
2150
+ reasoning: z9.string().optional().describe("How each breakdown component was addressed")
2470
2151
  }),
2471
- z10.object({
2472
- error: z10.string().describe("Error message if the question cannot be answered")
2152
+ z9.object({
2153
+ error: z9.string().describe("Error message if the question cannot be answered")
2473
2154
  })
2474
2155
  ]);
2475
- var decompositionSqlAgent = agent10({
2156
+ var decompositionSqlAgent = agent9({
2476
2157
  name: "decomposition-sql",
2477
- model: groq10("openai/gpt-oss-20b"),
2158
+ model: groq9("openai/gpt-oss-20b"),
2478
2159
  output: decompositionSqlOutputSchema,
2479
2160
  prompt: (state) => {
2480
2161
  return `
@@ -2501,8 +2182,8 @@ If there are ambiguities, make reasonable assumptions and note them in your reas
2501
2182
  }
2502
2183
  });
2503
2184
  var RETRY_TEMPERATURES2 = [0, 0.2, 0.3];
2504
- var tools7 = {
2505
- query_with_decomposition: tool7({
2185
+ var tools6 = {
2186
+ query_with_decomposition: tool6({
2506
2187
  description: `Query the database using question decomposition. This tool:
2507
2188
  1. Breaks down your question into semantic components (entities, filters, aggregations)
2508
2189
  2. Passes the decomposition to the SQL specialist
@@ -2510,22 +2191,22 @@ var tools7 = {
2510
2191
  4. Executes and returns results
2511
2192
 
2512
2193
  This approach helps ensure all aspects of the question are addressed in the query.`,
2513
- inputSchema: z10.object({
2514
- question: z10.string().min(1).describe("The question to answer."),
2515
- breakdown: z10.array(z10.string()).min(1).describe(
2194
+ inputSchema: z9.object({
2195
+ question: z9.string().min(1).describe("The question to answer."),
2196
+ breakdown: z9.array(z9.string()).min(1).describe(
2516
2197
  'Break down the question into its semantic parts. Each part should describe an ASPECT of what is being asked, not instructions. Example for "top customers by revenue last month": ["customers who made purchases", "revenue from those purchases", "time period: last month", "ranking: top by total revenue"]'
2517
2198
  ),
2518
- entities: z10.array(z10.string()).optional().describe(
2199
+ entities: z9.array(z9.string()).optional().describe(
2519
2200
  'Key entities mentioned (e.g., ["customers", "orders", "products"])'
2520
2201
  ),
2521
- filters: z10.array(z10.string()).optional().describe('Filter criteria (e.g., ["last month", "status = active"])'),
2522
- aggregation: z10.string().optional().describe(
2202
+ filters: z9.array(z9.string()).optional().describe('Filter criteria (e.g., ["last month", "status = active"])'),
2203
+ aggregation: z9.string().optional().describe(
2523
2204
  'Aggregation type if any (e.g., "sum revenue", "count orders", "top 10")'
2524
2205
  ),
2525
- ambiguities: z10.array(z10.string()).optional().describe("Note any ambiguous parts you identified")
2206
+ ambiguities: z9.array(z9.string()).optional().describe("Note any ambiguous parts you identified")
2526
2207
  }),
2527
2208
  execute: async ({ question, breakdown, entities, filters, aggregation, ambiguities }, options) => {
2528
- const state = toState7(options);
2209
+ const state = toState6(options);
2529
2210
  const decomposition = {
2530
2211
  originalQuestion: question,
2531
2212
  breakdown,
@@ -2597,10 +2278,10 @@ Previous attempt failed with: ${lastError}. Please fix the query.` : decomposedP
2597
2278
  }
2598
2279
  }
2599
2280
  }),
2600
- execute_sql: tool7({
2281
+ execute_sql: tool6({
2601
2282
  description: `Execute a SQL query directly. Use for follow-up queries or when you already have SQL.`,
2602
- inputSchema: z10.object({
2603
- sql: z10.string().min(1).refine(
2283
+ inputSchema: z9.object({
2284
+ sql: z9.string().min(1).refine(
2604
2285
  (sql) => sql.trim().toUpperCase().startsWith("SELECT") || sql.trim().toUpperCase().startsWith("WITH"),
2605
2286
  {
2606
2287
  message: "Only read-only SELECT or WITH queries are allowed."
@@ -2608,7 +2289,7 @@ Previous attempt failed with: ${lastError}. Please fix the query.` : decomposedP
2608
2289
  ).describe("The SQL query to execute.")
2609
2290
  }),
2610
2291
  execute: async ({ sql }, options) => {
2611
- const state = toState7(options);
2292
+ const state = toState6(options);
2612
2293
  try {
2613
2294
  const validationError = await state.adapter.validate(sql);
2614
2295
  if (validationError) {
@@ -2631,7 +2312,7 @@ Previous attempt failed with: ${lastError}. Please fix the query.` : decomposedP
2631
2312
  }
2632
2313
  }
2633
2314
  }),
2634
- scratchpad: scratchpad_tool7
2315
+ scratchpad: scratchpad_tool6
2635
2316
  };
2636
2317
  function formatDecomposition(decomposition) {
2637
2318
  const parts = [
@@ -2662,10 +2343,10 @@ function formatDecomposition(decomposition) {
2662
2343
  );
2663
2344
  return parts.join("\n");
2664
2345
  }
2665
- var chat4Agent = agent10({
2346
+ var chat4Agent = agent9({
2666
2347
  name: "chat4-decomposition",
2667
- model: groq10("openai/gpt-oss-20b"),
2668
- tools: tools7,
2348
+ model: groq9("openai/gpt-oss-20b"),
2349
+ tools: tools6,
2669
2350
  prompt: (state) => {
2670
2351
  return `
2671
2352
  ${state?.teachings || ""}
@@ -2874,7 +2555,7 @@ var Text2Sql = class {
2874
2555
  instruct(...dataset) {
2875
2556
  this.#config.instructions.push(...dataset);
2876
2557
  }
2877
- async inspect(agent11) {
2558
+ async inspect(agent10) {
2878
2559
  const [grounding] = await Promise.all([this.index()]);
2879
2560
  const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(
2880
2561
  (name) => name.startsWith("render_")
@@ -2894,14 +2575,14 @@ var Text2Sql = class {
2894
2575
  })
2895
2576
  ] : []
2896
2577
  ];
2897
- const tools8 = Object.keys({
2898
- ...agent11.handoff.tools,
2578
+ const tools7 = Object.keys({
2579
+ ...agent10.handoff.tools,
2899
2580
  ...this.#config.memory ? memoryTools : {},
2900
2581
  ...this.#config.tools
2901
2582
  });
2902
2583
  return {
2903
- tools: tools8,
2904
- prompt: agent11.instructions({
2584
+ tools: tools7,
2585
+ prompt: agent10.instructions({
2905
2586
  introspection: grounding,
2906
2587
  teachings: toInstructions("instructions", ...allInstructions)
2907
2588
  })
@@ -3064,7 +2745,7 @@ var Text2Sql = class {
3064
2745
  chat1Agent.clone({
3065
2746
  model: this.#config.model,
3066
2747
  tools: {
3067
- ...tools4,
2748
+ ...tools3,
3068
2749
  ...this.#config.memory ? memoryTools : {},
3069
2750
  ...this.#config.tools
3070
2751
  }
@@ -3130,7 +2811,7 @@ var Text2Sql = class {
3130
2811
  chat2Agent.clone({
3131
2812
  model: this.#config.model,
3132
2813
  tools: {
3133
- ...tools5,
2814
+ ...tools4,
3134
2815
  ...this.#config.memory ? memoryTools : {},
3135
2816
  ...this.#config.tools
3136
2817
  }
@@ -3195,7 +2876,7 @@ var Text2Sql = class {
3195
2876
  chat3Agent.clone({
3196
2877
  model: this.#config.model,
3197
2878
  tools: {
3198
- ...tools6,
2879
+ ...tools5,
3199
2880
  ...this.#config.memory ? memoryTools : {},
3200
2881
  ...this.#config.tools
3201
2882
  }
@@ -3263,7 +2944,7 @@ var Text2Sql = class {
3263
2944
  chat4Agent.clone({
3264
2945
  model: this.#config.model,
3265
2946
  tools: {
3266
- ...tools7,
2947
+ ...tools6,
3267
2948
  ...this.#config.memory ? memoryTools : {},
3268
2949
  ...this.#config.tools
3269
2950
  }
@@ -3289,58 +2970,6 @@ var Text2Sql = class {
3289
2970
  originalMessage
3290
2971
  );
3291
2972
  }
3292
- /**
3293
- * Business intelligence focused chat agent.
3294
- *
3295
- * Creates dashboards using MDX components with embedded SQL queries.
3296
- * The agent explores data, validates SQL, and outputs markdown with
3297
- * JSX chart components that the frontend renders via MDX.
3298
- *
3299
- * @example
3300
- * ```typescript
3301
- * const result = await text2sql.bi(
3302
- * [user("Show me a sales dashboard for last 30 days")],
3303
- * { chatId: 'dashboard-1', userId: 'user-1' }
3304
- * );
3305
- * // Result contains markdown with <BarChart sql="..." />, <KPI sql="..." />, etc.
3306
- * ```
3307
- */
3308
- async bi(messages, params) {
3309
- const [introspection, userTeachables] = await Promise.all([
3310
- this.index({ onProgress: console.log }),
3311
- this.#config.memory ? this.#config.memory.toTeachables(params.userId) : []
3312
- ]);
3313
- const chat = await this.#config.history.upsertChat({
3314
- id: params.chatId,
3315
- userId: params.userId,
3316
- title: "Chat " + params.chatId
3317
- });
3318
- const originalMessages = [
3319
- ...chat.messages.map((it) => it.content),
3320
- ...messages
3321
- ];
3322
- const result = stream(
3323
- biAgent.clone({
3324
- model: this.#config.model
3325
- }),
3326
- originalMessages,
3327
- {
3328
- teachings: toInstructions(
3329
- "instructions",
3330
- ...this.#config.instructions,
3331
- teachable("user_profile", ...userTeachables)
3332
- ),
3333
- adapter: this.#config.adapter,
3334
- introspection
3335
- }
3336
- );
3337
- return this.#createUIMessageStream(
3338
- result,
3339
- messages,
3340
- params,
3341
- originalMessages
3342
- );
3343
- }
3344
2973
  /**
3345
2974
  * Developer-focused conversational interface for SQL generation.
3346
2975
  *
@@ -3364,36 +2993,26 @@ var Text2Sql = class {
3364
2993
  this.index({ onProgress: console.log }),
3365
2994
  this.#config.memory ? this.#config.memory.toTeachables(params.userId) : []
3366
2995
  ]);
3367
- const chat = await this.#config.history.upsertChat({
3368
- id: params.chatId,
3369
- userId: params.userId,
3370
- title: "Chat " + params.chatId
3371
- });
3372
- const originalMessages = [
3373
- ...chat.messages.map((it) => it.content),
3374
- ...messages
3375
- ];
3376
- const result = stream(
3377
- developerAgent.clone({
3378
- model: this.#config.model
3379
- }),
3380
- originalMessages,
3381
- {
3382
- teachings: toInstructions(
3383
- "instructions",
3384
- ...this.#config.instructions,
3385
- teachable("user_profile", ...userTeachables)
3386
- ),
3387
- adapter: this.#config.adapter,
3388
- introspection,
3389
- instructions: this.#config.instructions
3390
- }
3391
- );
3392
- return this.#createUIMessageStream(
3393
- result,
3394
- messages,
2996
+ return withChat(
2997
+ this.#config.history,
3395
2998
  params,
3396
- originalMessages
2999
+ messages,
3000
+ (originalMessages) => stream(
3001
+ developerAgent.clone({
3002
+ model: this.#config.model
3003
+ }),
3004
+ originalMessages,
3005
+ {
3006
+ teachings: toInstructions(
3007
+ "instructions",
3008
+ ...this.#config.instructions,
3009
+ teachable("user_profile", ...userTeachables)
3010
+ ),
3011
+ adapter: this.#config.adapter,
3012
+ introspection,
3013
+ instructions: this.#config.instructions
3014
+ }
3015
+ )
3397
3016
  );
3398
3017
  }
3399
3018
  /**
@@ -3442,6 +3061,58 @@ var Text2Sql = class {
3442
3061
  });
3443
3062
  }
3444
3063
  };
3064
+ async function withChat(history, params, messages, streamFn) {
3065
+ const chat = await history.upsertChat({
3066
+ id: params.chatId,
3067
+ userId: params.userId,
3068
+ title: "Chat " + params.chatId
3069
+ });
3070
+ const originalMessages = [
3071
+ ...chat.messages.map((it) => it.content),
3072
+ ...messages
3073
+ ];
3074
+ const result = streamFn(originalMessages);
3075
+ return result.toUIMessageStream({
3076
+ onError: (error) => {
3077
+ if (NoSuchToolError.isInstance(error)) {
3078
+ return "The model tried to call an unknown tool.";
3079
+ } else if (InvalidToolInputError.isInstance(error)) {
3080
+ return "The model called a tool with invalid arguments.";
3081
+ } else if (ToolCallRepairError.isInstance(error)) {
3082
+ return "The model tried to call a tool with invalid arguments, but it was repaired.";
3083
+ } else {
3084
+ return "An unknown error occurred.";
3085
+ }
3086
+ },
3087
+ sendStart: true,
3088
+ sendFinish: true,
3089
+ sendReasoning: true,
3090
+ sendSources: true,
3091
+ originalMessages,
3092
+ generateMessageId: generateId,
3093
+ onFinish: async ({ responseMessage, isContinuation }) => {
3094
+ const userMessage = messages.at(-1);
3095
+ if (!isContinuation && userMessage) {
3096
+ console.log(
3097
+ "Saving user message to history:",
3098
+ JSON.stringify(userMessage)
3099
+ );
3100
+ await history.addMessage({
3101
+ id: v72(),
3102
+ chatId: params.chatId,
3103
+ role: userMessage.role,
3104
+ content: userMessage
3105
+ });
3106
+ }
3107
+ await history.addMessage({
3108
+ id: v72(),
3109
+ chatId: params.chatId,
3110
+ role: responseMessage.role,
3111
+ content: responseMessage
3112
+ });
3113
+ }
3114
+ });
3115
+ }
3445
3116
  export {
3446
3117
  Adapter,
3447
3118
  Checkpoint,
@@ -3465,6 +3136,7 @@ export {
3465
3136
  matchesFilter,
3466
3137
  memoryTools,
3467
3138
  suggestionsAgent,
3468
- t_a_g
3139
+ t_a_g,
3140
+ withChat
3469
3141
  };
3470
3142
  //# sourceMappingURL=index.js.map