feat: Add SQL Query Generator AgentKit#159
Conversation
WalkthroughThis pull request delivers the complete SQL Query Generator kit—a new Lamatic agent that translates natural-language database questions into optimized, read-only SELECT queries. It bundles a schema-constrained LLM flow, server-side orchestration, and a Next.js UI frontend with sample data, error handling, and result display including confidence scoring and SQL explanation. ChangesSQL Query Generator Kit
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
PR Validation ResultsNew Contributions Detected
Check Results
Errors
🛑 Please fix the errors above before this PR can be merged. Refer to CONTRIBUTING.md and CLAUDE.md for the expected folder structure. |
:robot_face: AgentKit Structural ValidationNew Contributions Detected
Check Results
|
There was a problem hiding this comment.
Actionable comments posted: 12
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@kits/sql-query-generator/agent.md`:
- Around line 3-4: The "## Overview" heading in agent.md needs a blank line
after it to satisfy MD022; insert a single empty line immediately following the
"## Overview" heading so the heading is separated from the paragraph that
follows, and if this file is generated from a template (e.g., the
constitutions/default.md template used by kits/*), apply the same change in that
template (update the "## Overview" heading in constitutions/default.md) so
future kits inherit the correct spacing.
- Around line 6-19: Add a blank line after each Markdown heading in this
document (e.g., after "Architecture", "Key Design Decisions", and "Flows") to
satisfy MD022; update the file's headings so there is one empty line between
each heading and the following paragraph/list. Also fix the source template
(kits/*/constitutions/default.md) that generates these kit README/constitution
files so future kits are created with correct blank lines after headings.
In `@kits/sql-query-generator/apps/.env.example`:
- Around line 1-4: Update the .env example to remove spaces around the equals
sign so entries follow KEY=VALUE convention; specifically change lines for
SQL_QUERY_GENERATOR_FLOW_ID, LAMATIC_API_URL, LAMATIC_PROJECT_ID, and
LAMATIC_API_KEY to use SQL_QUERY_GENERATOR_FLOW_ID="YOUR_FLOW_ID",
LAMATIC_API_URL="YOUR_API_ENDPOINT", LAMATIC_PROJECT_ID="YOUR_PROJECT_ID", and
LAMATIC_API_KEY="YOUR_API_KEY" (no spaces around =).
In `@kits/sql-query-generator/apps/actions/orchestrate.ts`:
- Around line 19-31: parseResponse currently returns JSON.parse(cleaned) cast to
SQLGeneratorResult without runtime shape checks; add defensive validation after
parsing in parseResponse to ensure the returned object conforms to
SQLGeneratorResult: verify parsed.sql and parsed.explanation are strings (or set
safe defaults), ensure parsed.tables_used is an array (or []), ensure
parsed.assumptions is a string (or null/empty), and validate parsed.confidence
against allowed values ["high","medium","low"] (default to "low" if invalid);
construct and return a sanitized object matching SQLGeneratorResult rather than
returning the raw parsed value so downstream calls like
confidenceColor(result.confidence) and table/assumption rendering cannot crash.
In `@kits/sql-query-generator/apps/app/page.tsx`:
- Around line 46-60: The form allows editing the schema and question while
handleSubmit is running (loading true), which can confuse users; update the UI
to disable the input controls when loading is true: wire the loading state
(loading) into the textarea/input elements that bind to schema and question so
they receive disabled={loading} (and apply any existing disabled styling) and
ensure any buttons or interactive controls related to generateQuery also respect
loading; adjust any client-side handlers that mutate schema/question during
loading to be no-ops or blocked while loading is true.
- Around line 95-100: Import the required icons from lucide-react (e.g.,
FileCode and Sparkles or Zap) at the top of the module and add them to the two
button JSX elements that call loadSample and the generate handler (e.g.,
generateSql/generate) so the "Load sample" and "Generate SQL" buttons render
icons alongside their labels; update the button markup to include the icon
components and adjust spacing classes (e.g., add a small gap and align items) to
match existing styling while keeping the onClick handlers (loadSample and
generate*) unchanged.
- Around line 6-12: QueryResult is a duplicate of SQLGeneratorResult; remove the
local QueryResult type and instead export SQLGeneratorResult from
actions/orchestrate.ts (ensure it's exported as a named export) and import that
type into this file, then update any usages/state declarations that referenced
QueryResult to use SQLGeneratorResult (references: QueryResult,
SQLGeneratorResult, actions/orchestrate.ts, and any state variables in page.tsx
that were typed with QueryResult).
- Around line 102-117: The two textarea controls bound to value={schema} and
value={question} lack semantic linkage to their visual labels; add unique id
attributes (e.g., "schema-textarea" and "question-textarea") to those textarea
elements, update the corresponding <label> elements to include htmlFor set to
those ids, and also add either aria-label or aria-labelledby on each textarea
for screen readers (or use aria-labelledby pointing to the label text) so the
schema and question inputs (the elements using setSchema and setQuestion) are
properly announced.
- Around line 160-167: Update the Copy button to use the lucide-react Copy icon
and add accessibility attributes: import Copy from 'lucide-react' at the top of
page.tsx, replace the button content so the icon is rendered (e.g., <Copy .../>)
alongside or instead of the "Copy" text, and add an aria-label like
aria-label="Copy SQL to clipboard" (optionally title="Copy SQL") to the <button>
element; keep the existing onClick handler
(navigator.clipboard.writeText(result.sql)) and existing classes but adjust icon
sizing via className on the Copy component for visual parity.
In `@kits/sql-query-generator/apps/package.json`:
- Line 17: The dependency "lamatic": "latest" in package.json is unpinned and
must be fixed; replace the "latest" specifier with an explicit, immutable
version (e.g., the version from this app's lockfile or the current npm registry)
so the entry reads "lamatic": "<exact-version>"; update package.json accordingly
and run npm/yarn install to refresh the lockfile so the kit has a pinned,
reproducible dependency.
In `@kits/sql-query-generator/README.md`:
- Around line 46-51: Add a language identifier to the markdown code fence that
shows the environment variables (the block containing
SQL_QUERY_GENERATOR_FLOW_ID, LAMATIC_API_URL, LAMATIC_PROJECT_ID,
LAMATIC_API_KEY) so editors render proper syntax highlighting; change the
opening triple backticks to include a language like env or bash (e.g., ```env)
and keep the variable lines unchanged.
- Line 41: Replace the README's local env copy step so developers create a
Next.js safe local file: change the instruction that runs "cp .env.example .env"
to copy into ".env.local" instead (update the line that currently reads cp
.env.example .env to use .env.local); also verify the repository .gitignore
excludes both .env and .env.local to avoid committing secrets.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI (base), Organization UI (inherited)
Review profile: ASSERTIVE
Plan: Pro
Run ID: 51f5c30c-b072-4e4f-82e8-0534afb447c2
⛔ Files ignored due to path filters (1)
kits/sql-query-generator/apps/package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (19)
kits/sql-query-generator/README.mdkits/sql-query-generator/agent.mdkits/sql-query-generator/apps/.env.examplekits/sql-query-generator/apps/.gitignorekits/sql-query-generator/apps/actions/orchestrate.tskits/sql-query-generator/apps/app/globals.csskits/sql-query-generator/apps/app/layout.tsxkits/sql-query-generator/apps/app/page.tsxkits/sql-query-generator/apps/lib/lamatic-client.tskits/sql-query-generator/apps/next.config.mjskits/sql-query-generator/apps/package.jsonkits/sql-query-generator/apps/postcss.config.mjskits/sql-query-generator/apps/tsconfig.jsonkits/sql-query-generator/constitutions/default.mdkits/sql-query-generator/flows/sql-query-generator.tskits/sql-query-generator/lamatic.config.tskits/sql-query-generator/model-configs/sql-query-generator_model.tskits/sql-query-generator/prompts/sql-query-generator_system.mdkits/sql-query-generator/prompts/sql-query-generator_user.md
| ## Overview | ||
| This agent converts natural language questions into optimized, read-only SQL queries. Users provide their database schema (as CREATE TABLE statements) and ask questions in plain English. The agent returns a well-structured SQL SELECT query along with an explanation, the tables used, any assumptions made, and a confidence score. |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | 💤 Low value
Agent, your documentation formatting needs a tactical adjustment.
The heading "## Overview" (line 3) should have a blank line after it according to markdown best practices (MD022). This improves readability across different renderers.
Note: If agent.md is a templated file like constitutions/default.md, this fix should be applied at the template/source level so all future kits inherit the correct format.
📄 Proposed fix for heading spacing
## Overview
+
This agent converts natural language questions into optimized, read-only SQL queries. Users provide their database schema (as CREATE TABLE statements) and ask questions in plain English. The agent returns a well-structured SQL SELECT query along with an explanation, the tables used, any assumptions made, and a confidence score.Based on learnings: "In kits/*/constitutions/default.md, the default.md constitution file is a templated/auto-generated file that ships as part of every new kit. It may have markdownlint MD022 (blanks-around-headings) warnings by default. When flagging such warnings in these files, note that the fix should be applied at the template/source level so all future kits inherit the corrected format."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ## Overview | |
| This agent converts natural language questions into optimized, read-only SQL queries. Users provide their database schema (as CREATE TABLE statements) and ask questions in plain English. The agent returns a well-structured SQL SELECT query along with an explanation, the tables used, any assumptions made, and a confidence score. | |
| ## Overview | |
| This agent converts natural language questions into optimized, read-only SQL queries. Users provide their database schema (as CREATE TABLE statements) and ask questions in plain English. The agent returns a well-structured SQL SELECT query along with an explanation, the tables used, any assumptions made, and a confidence score. |
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)
[warning] 3-3: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/agent.md` around lines 3 - 4, The "## Overview"
heading in agent.md needs a blank line after it to satisfy MD022; insert a
single empty line immediately following the "## Overview" heading so the heading
is separated from the paragraph that follows, and if this file is generated from
a template (e.g., the constitutions/default.md template used by kits/*), apply
the same change in that template (update the "## Overview" heading in
constitutions/default.md) so future kits inherit the correct spacing.
| ## Architecture | ||
| The agent uses a single Lamatic Flow with three nodes: | ||
| 1. **API Request** — receives the database schema and question via GraphQL | ||
| 2. **Generate Text (LLM)** — processes the inputs using a system prompt tuned for SQL generation | ||
| 3. **API Response** — returns the generated SQL as a JSON string | ||
|
|
||
| ## Key Design Decisions | ||
| - **Read-only queries only** — the agent is explicitly instructed to never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements, making it safe for production use | ||
| - **Structured JSON output** — the response includes sql, explanation, tables_used, assumptions, and confidence fields for easy frontend parsing | ||
| - **Cross-database compatibility** — queries target standard SQL that works across PostgreSQL, MySQL, and SQLite | ||
| - **Explicit JOINs** — the agent prefers explicit JOIN syntax over implicit joins for readability | ||
|
|
||
| ## Flows | ||
| 1. `sql-query-generator` — the single flow that handles schema parsing, SQL generation, and response formatting |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | 💤 Low value
Field report: multiple heading spacing issues detected.
Agent, your document has four headings that need blank lines after them (lines 6, 12, 18) for proper markdown formatting (MD022). This is a consistent pattern throughout the file.
📄 Proposed fix for all heading spacing issues
## Architecture
+
The agent uses a single Lamatic Flow with three nodes:
1. **API Request** — receives the database schema and question via GraphQL
2. **Generate Text (LLM)** — processes the inputs using a system prompt tuned for SQL generation
3. **API Response** — returns the generated SQL as a JSON string
## Key Design Decisions
+
- **Read-only queries only** — the agent is explicitly instructed to never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements, making it safe for production use
- **Structured JSON output** — the response includes sql, explanation, tables_used, assumptions, and confidence fields for easy frontend parsing
- **Cross-database compatibility** — queries target standard SQL that works across PostgreSQL, MySQL, and SQLite
- **Explicit JOINs** — the agent prefers explicit JOIN syntax over implicit joins for readability
## Flows
+
1. `sql-query-generator` — the single flow that handles schema parsing, SQL generation, and response formattingBased on learnings: "In kits/*/constitutions/default.md, the default.md constitution file is a templated/auto-generated file that ships as part of every new kit. It may have markdownlint MD022 (blanks-around-headings) warnings by default. When flagging such warnings in these files, note that the fix should be applied at the template/source level so all future kits inherit the corrected format."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ## Architecture | |
| The agent uses a single Lamatic Flow with three nodes: | |
| 1. **API Request** — receives the database schema and question via GraphQL | |
| 2. **Generate Text (LLM)** — processes the inputs using a system prompt tuned for SQL generation | |
| 3. **API Response** — returns the generated SQL as a JSON string | |
| ## Key Design Decisions | |
| - **Read-only queries only** — the agent is explicitly instructed to never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements, making it safe for production use | |
| - **Structured JSON output** — the response includes sql, explanation, tables_used, assumptions, and confidence fields for easy frontend parsing | |
| - **Cross-database compatibility** — queries target standard SQL that works across PostgreSQL, MySQL, and SQLite | |
| - **Explicit JOINs** — the agent prefers explicit JOIN syntax over implicit joins for readability | |
| ## Flows | |
| 1. `sql-query-generator` — the single flow that handles schema parsing, SQL generation, and response formatting | |
| ## Architecture | |
| The agent uses a single Lamatic Flow with three nodes: | |
| 1. **API Request** — receives the database schema and question via GraphQL | |
| 2. **Generate Text (LLM)** — processes the inputs using a system prompt tuned for SQL generation | |
| 3. **API Response** — returns the generated SQL as a JSON string | |
| ## Key Design Decisions | |
| - **Read-only queries only** — the agent is explicitly instructed to never generate INSERT, UPDATE, DELETE, DROP, or ALTER statements, making it safe for production use | |
| - **Structured JSON output** — the response includes sql, explanation, tables_used, assumptions, and confidence fields for easy frontend parsing | |
| - **Cross-database compatibility** — queries target standard SQL that works across PostgreSQL, MySQL, and SQLite | |
| - **Explicit JOINs** — the agent prefers explicit JOIN syntax over implicit joins for readability | |
| ## Flows | |
| 1. `sql-query-generator` — the single flow that handles schema parsing, SQL generation, and response formatting |
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)
[warning] 6-6: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 12-12: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 18-18: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/agent.md` around lines 6 - 19, Add a blank line
after each Markdown heading in this document (e.g., after "Architecture", "Key
Design Decisions", and "Flows") to satisfy MD022; update the file's headings so
there is one empty line between each heading and the following paragraph/list.
Also fix the source template (kits/*/constitutions/default.md) that generates
these kit README/constitution files so future kits are created with correct
blank lines after headings.
| SQL_QUERY_GENERATOR_FLOW_ID = "YOUR_FLOW_ID" | ||
| LAMATIC_API_URL = "YOUR_API_ENDPOINT" | ||
| LAMATIC_PROJECT_ID = "YOUR_PROJECT_ID" | ||
| LAMATIC_API_KEY = "YOUR_API_KEY" |
There was a problem hiding this comment.
Agent, tighten up your .env format—remove those extraneous spaces.
Standard .env protocol requires no spaces around the equals sign. Your current format (KEY = VALUE) works but deviates from convention—should be KEY=VALUE.
🔧 Proposed fix to align with standard format
-SQL_QUERY_GENERATOR_FLOW_ID = "YOUR_FLOW_ID"
-LAMATIC_API_URL = "YOUR_API_ENDPOINT"
-LAMATIC_PROJECT_ID = "YOUR_PROJECT_ID"
-LAMATIC_API_KEY = "YOUR_API_KEY"
+SQL_QUERY_GENERATOR_FLOW_ID="YOUR_FLOW_ID"
+LAMATIC_API_URL="YOUR_API_ENDPOINT"
+LAMATIC_PROJECT_ID="YOUR_PROJECT_ID"
+LAMATIC_API_KEY="YOUR_API_KEY"📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| SQL_QUERY_GENERATOR_FLOW_ID = "YOUR_FLOW_ID" | |
| LAMATIC_API_URL = "YOUR_API_ENDPOINT" | |
| LAMATIC_PROJECT_ID = "YOUR_PROJECT_ID" | |
| LAMATIC_API_KEY = "YOUR_API_KEY" | |
| SQL_QUERY_GENERATOR_FLOW_ID="YOUR_FLOW_ID" | |
| LAMATIC_API_URL="YOUR_API_ENDPOINT" | |
| LAMATIC_PROJECT_ID="YOUR_PROJECT_ID" | |
| LAMATIC_API_KEY="YOUR_API_KEY" |
🧰 Tools
🪛 dotenv-linter (4.0.0)
[warning] 1-1: [SpaceCharacter] The line has spaces around equal sign
(SpaceCharacter)
[warning] 2-2: [SpaceCharacter] The line has spaces around equal sign
(SpaceCharacter)
[warning] 2-2: [UnorderedKey] The LAMATIC_API_URL key should go before the SQL_QUERY_GENERATOR_FLOW_ID key
(UnorderedKey)
[warning] 3-3: [SpaceCharacter] The line has spaces around equal sign
(SpaceCharacter)
[warning] 3-3: [UnorderedKey] The LAMATIC_PROJECT_ID key should go before the SQL_QUERY_GENERATOR_FLOW_ID key
(UnorderedKey)
[warning] 4-4: [SpaceCharacter] The line has spaces around equal sign
(SpaceCharacter)
[warning] 4-4: [UnorderedKey] The LAMATIC_API_KEY key should go before the LAMATIC_API_URL key
(UnorderedKey)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/apps/.env.example` around lines 1 - 4, Update the
.env example to remove spaces around the equals sign so entries follow KEY=VALUE
convention; specifically change lines for SQL_QUERY_GENERATOR_FLOW_ID,
LAMATIC_API_URL, LAMATIC_PROJECT_ID, and LAMATIC_API_KEY to use
SQL_QUERY_GENERATOR_FLOW_ID="YOUR_FLOW_ID", LAMATIC_API_URL="YOUR_API_ENDPOINT",
LAMATIC_PROJECT_ID="YOUR_PROJECT_ID", and LAMATIC_API_KEY="YOUR_API_KEY" (no
spaces around =).
| function parseResponse(raw: string): SQLGeneratorResult { | ||
| let cleaned = raw.trim(); | ||
| if (cleaned.startsWith("```json")) { | ||
| cleaned = cleaned.slice(7); | ||
| } else if (cleaned.startsWith("```")) { | ||
| cleaned = cleaned.slice(3); | ||
| } | ||
| if (cleaned.endsWith("```")) { | ||
| cleaned = cleaned.slice(0, -3); | ||
| } | ||
| cleaned = cleaned.trim(); | ||
| return JSON.parse(cleaned); | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
The package is trusted but never inspected, Agent. parseResponse casts JSON.parse(cleaned) straight to SQLGeneratorResult with no runtime shape check. If the model emits valid JSON of the wrong shape (missing confidence, tables_used not an array, etc.), the malformed object reaches the UI where confidenceColor(result.confidence) and the assumptions/tables rendering have no guards — risking a runtime fault. The JSON.parse throw is already caught, so only structural validation is missing.
🛡️ Suggested defensive validation
function parseResponse(raw: string): SQLGeneratorResult {
let cleaned = raw.trim();
if (cleaned.startsWith("```json")) {
cleaned = cleaned.slice(7);
} else if (cleaned.startsWith("```")) {
cleaned = cleaned.slice(3);
}
if (cleaned.endsWith("```")) {
cleaned = cleaned.slice(0, -3);
}
cleaned = cleaned.trim();
- return JSON.parse(cleaned);
+ const parsed = JSON.parse(cleaned);
+ const validConfidence = ["high", "medium", "low"];
+ return {
+ sql: typeof parsed.sql === "string" ? parsed.sql : null,
+ explanation: typeof parsed.explanation === "string" ? parsed.explanation : "",
+ tables_used: Array.isArray(parsed.tables_used) ? parsed.tables_used : [],
+ assumptions: typeof parsed.assumptions === "string" ? parsed.assumptions : null,
+ confidence: validConfidence.includes(parsed.confidence) ? parsed.confidence : "low",
+ };
}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/apps/actions/orchestrate.ts` around lines 19 - 31,
parseResponse currently returns JSON.parse(cleaned) cast to SQLGeneratorResult
without runtime shape checks; add defensive validation after parsing in
parseResponse to ensure the returned object conforms to SQLGeneratorResult:
verify parsed.sql and parsed.explanation are strings (or set safe defaults),
ensure parsed.tables_used is an array (or []), ensure parsed.assumptions is a
string (or null/empty), and validate parsed.confidence against allowed values
["high","medium","low"] (default to "low" if invalid); construct and return a
sanitized object matching SQLGeneratorResult rather than returning the raw
parsed value so downstream calls like confidenceColor(result.confidence) and
table/assumption rendering cannot crash.
| interface QueryResult { | ||
| sql: string | null; | ||
| explanation: string; | ||
| tables_used: string[]; | ||
| assumptions: string | null; | ||
| confidence: "high" | "medium" | "low"; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Agent briefing: Type duplication detected in the field.
The QueryResult interface is an exact duplicate of SQLGeneratorResult from actions/orchestrate.ts. This creates a maintenance risk—if the server response shape evolves, both definitions must be synchronized.
Mission directive: Export SQLGeneratorResult from orchestrate.ts and import it here.
As per coding guidelines: TypeScript usage should eliminate redundancy.
🔧 Proposed fix to eliminate duplication
In actions/orchestrate.ts, export the type:
-interface SQLGeneratorResult {
+export interface SQLGeneratorResult {
sql: string | null;
explanation: string;
tables_used: string[];
assumptions: string | null;
confidence: "high" | "medium" | "low";
}Then in this file:
"use client";
import { useState } from "react";
-import { generateQuery } from "`@/actions/orchestrate`";
-
-interface QueryResult {
- sql: string | null;
- explanation: string;
- tables_used: string[];
- assumptions: string | null;
- confidence: "high" | "medium" | "low";
-}
+import { generateQuery, type SQLGeneratorResult } from "`@/actions/orchestrate`";And update the state typing:
- const [result, setResult] = useState<QueryResult | null>(null);
+ const [result, setResult] = useState<SQLGeneratorResult | null>(null);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/apps/app/page.tsx` around lines 6 - 12, QueryResult
is a duplicate of SQLGeneratorResult; remove the local QueryResult type and
instead export SQLGeneratorResult from actions/orchestrate.ts (ensure it's
exported as a named export) and import that type into this file, then update any
usages/state declarations that referenced QueryResult to use SQLGeneratorResult
(references: QueryResult, SQLGeneratorResult, actions/orchestrate.ts, and any
state variables in page.tsx that were typed with QueryResult).
| <textarea | ||
| value={schema} | ||
| onChange={(e) => setSchema(e.target.value)} | ||
| placeholder="Paste your CREATE TABLE statements here..." | ||
| className="w-full h-44 p-3 border border-gray-300 rounded-lg font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" | ||
| /> | ||
|
|
||
| <label className="block text-sm font-medium text-gray-700 mt-5 mb-2"> | ||
| Your Question | ||
| </label> | ||
| <textarea | ||
| value={question} | ||
| onChange={(e) => setQuestion(e.target.value)} | ||
| placeholder='e.g. "Find all users who placed more than 3 orders last month"' | ||
| className="w-full h-20 p-3 border border-gray-300 rounded-lg text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" | ||
| /> |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | 💤 Low value
Intel update: Accessibility protocol can be strengthened.
The textareas lack explicit id/htmlFor associations and aria-label attributes. While visual labels are present, screen reader users would benefit from proper semantic linkage.
Optional enhancement: Add id to textareas and htmlFor to labels.
♿ Proposed accessibility improvements
<label
+ htmlFor="schema-input"
className="block text-sm font-medium text-gray-700"
>
Database Schema
</label>
...
<textarea
+ id="schema-input"
+ aria-label="Database schema input"
value={schema}
onChange={(e) => setSchema(e.target.value)}
placeholder="Paste your CREATE TABLE statements here..."
className="w-full h-44 p-3 border border-gray-300 rounded-lg font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
<label
+ htmlFor="question-input"
className="block text-sm font-medium text-gray-700 mt-5 mb-2"
>
Your Question
</label>
<textarea
+ id="question-input"
+ aria-label="Natural language question input"
value={question}
onChange={(e) => setQuestion(e.target.value)}
placeholder='e.g. "Find all users who placed more than 3 orders last month"'
className="w-full h-20 p-3 border border-gray-300 rounded-lg text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/apps/app/page.tsx` around lines 102 - 117, The two
textarea controls bound to value={schema} and value={question} lack semantic
linkage to their visual labels; add unique id attributes (e.g.,
"schema-textarea" and "question-textarea") to those textarea elements, update
the corresponding <label> elements to include htmlFor set to those ids, and also
add either aria-label or aria-labelledby on each textarea for screen readers (or
use aria-labelledby pointing to the label text) so the schema and question
inputs (the elements using setSchema and setQuestion) are properly announced.
| <button | ||
| onClick={() => { | ||
| if (result.sql) navigator.clipboard.writeText(result.sql); | ||
| }} | ||
| className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600 transition-colors" | ||
| > | ||
| Copy | ||
| </button> |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
Equipment requisition: Copy operation requires visual indicator.
The copy button lacks an icon (violates "Use lucide-react for icons throughout kits" guideline) and accessibility attributes. Adding a Copy icon and aria-label would improve both visual clarity and screen reader support.
As per coding guidelines: kits/**/*.{ts,tsx} should use lucide-react for icons.
📋 Proposed enhancement with icon and accessibility
import { useState } from "react";
import { generateQuery, type SQLGeneratorResult } from "`@/actions/orchestrate`";
-import { FileCode, Sparkles } from "lucide-react";
+import { FileCode, Sparkles, Copy } from "lucide-react"; <button
onClick={() => {
if (result.sql) navigator.clipboard.writeText(result.sql);
}}
+ aria-label="Copy SQL to clipboard"
className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600 transition-colors"
>
+ <Copy className="inline-block w-3 h-3 mr-1" />
Copy
</button>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| <button | |
| onClick={() => { | |
| if (result.sql) navigator.clipboard.writeText(result.sql); | |
| }} | |
| className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600 transition-colors" | |
| > | |
| Copy | |
| </button> | |
| import { useState } from "react"; | |
| import { generateQuery, type SQLGeneratorResult } from "`@/actions/orchestrate`"; | |
| import { FileCode, Sparkles, Copy } from "lucide-react"; | |
| // ... other code ... | |
| <button | |
| onClick={() => { | |
| if (result.sql) navigator.clipboard.writeText(result.sql); | |
| }} | |
| aria-label="Copy SQL to clipboard" | |
| className="absolute top-2 right-2 px-2 py-1 bg-gray-700 text-gray-300 text-xs rounded hover:bg-gray-600 transition-colors" | |
| > | |
| <Copy className="inline-block w-3 h-3 mr-1" /> | |
| Copy | |
| </button> |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/apps/app/page.tsx` around lines 160 - 167, Update
the Copy button to use the lucide-react Copy icon and add accessibility
attributes: import Copy from 'lucide-react' at the top of page.tsx, replace the
button content so the icon is rendered (e.g., <Copy .../>) alongside or instead
of the "Copy" text, and add an aria-label like aria-label="Copy SQL to
clipboard" (optionally title="Copy SQL") to the <button> element; keep the
existing onClick handler (navigator.clipboard.writeText(result.sql)) and
existing classes but adjust icon sizing via className on the Copy component for
visual parity.
| "start": "next start" | ||
| }, | ||
| "dependencies": { | ||
| "lamatic": "latest", |
There was a problem hiding this comment.
Agent, your package dependency is compromised—pin that version immediately.
The "lamatic": "latest" dependency violates protocol. Using "latest" means each installation pulls a different version, breaking reproducibility and risking mission failure when breaking changes slip through. Your orders are clear: pin to an explicit version (e.g., "lamatic": "1.2.3").
🔒 Proposed fix to secure the dependency
- "lamatic": "latest",
+ "lamatic": "1.0.0",Note: Replace 1.0.0 with the actual current version from your lock file or npm registry.
As per coding guidelines: "Each kit must have its own package.json with pinned dependency versions; do not rely on workspace-level hoisting or a root package.json"
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "lamatic": "latest", | |
| "lamatic": "1.0.0", |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/apps/package.json` at line 17, The dependency
"lamatic": "latest" in package.json is unpinned and must be fixed; replace the
"latest" specifier with an explicit, immutable version (e.g., the version from
this app's lockfile or the current npm registry) so the entry reads "lamatic":
"<exact-version>"; update package.json accordingly and run npm/yarn install to
refresh the lockfile so the kit has a pinned, reproducible dependency.
| ### 3. Configure environment | ||
|
|
||
| ```bash | ||
| cp .env.example .env |
There was a problem hiding this comment.
Mission briefing, agent: use .env.local for Next.js development secrets.
Your deployment package correctly references .env.example as the template, but the local copy command should target .env.local instead of .env. Next.js prioritizes .env.local for developer-specific secrets and most kits' .gitignore files exclude it by default (along with .env). This prevents accidental commits of live credentials.
🔒 Recommended fix for secure local development
-cp .env.example .env
+cp .env.example .env.localAs per coding guidelines: "The .gitignore file must exclude .env and .env.local to prevent accidental secret commits."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| cp .env.example .env | |
| cp .env.example .env.local |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/README.md` at line 41, Replace the README's local
env copy step so developers create a Next.js safe local file: change the
instruction that runs "cp .env.example .env" to copy into ".env.local" instead
(update the line that currently reads cp .env.example .env to use .env.local);
also verify the repository .gitignore excludes both .env and .env.local to avoid
committing secrets.
| ``` | ||
| SQL_QUERY_GENERATOR_FLOW_ID = "your-flow-id" | ||
| LAMATIC_API_URL = "https://your-org.lamatic.dev" | ||
| LAMATIC_PROJECT_ID = "your-project-id" | ||
| LAMATIC_API_KEY = "sk-your-api-key" | ||
| ``` |
There was a problem hiding this comment.
Mission briefing: code fence needs a language identifier.
The environment variable example block (lines 46-51) is missing a language specifier. Intelligence analysts recommend adding env or bash to improve syntax highlighting and comply with markdown standards.
📋 Proposed fix for code fence language
-```
+```env
SQL_QUERY_GENERATOR_FLOW_ID = "your-flow-id"
LAMATIC_API_URL = "https://your-org.lamatic.dev"
LAMATIC_PROJECT_ID = "your-project-id"
LAMATIC_API_KEY = "sk-your-api-key"
</details>
<!-- suggestion_start -->
<details>
<summary>📝 Committable suggestion</summary>
> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
```suggestion
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)
[warning] 46-46: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@kits/sql-query-generator/README.md` around lines 46 - 51, Add a language
identifier to the markdown code fence that shows the environment variables (the
block containing SQL_QUERY_GENERATOR_FLOW_ID, LAMATIC_API_URL,
LAMATIC_PROJECT_ID, LAMATIC_API_KEY) so editors render proper syntax
highlighting; change the opening triple backticks to include a language like env
or bash (e.g., ```env) and keep the variable lines unchanged.
What This Kit Does
An AI-powered agent that converts natural language questions into optimized SQL queries. Users paste their database schema and ask questions in plain English. The agent returns production-ready SELECT queries with explanations, confidence scores, and assumption tracking.
Problem It Solves
Writing SQL from scratch is time-consuming, especially for complex joins and aggregations. This tool lets developers and analysts quickly get a working query by describing what they need in plain English.
Key Features
Providers & Prerequisites
How to Run Locally
cd kits/sql-query-generator/appsnpm installcp .env.example .env.localand fill in valuesnpm run devLive Preview
https://agent-kit-git-vercel-react-server-co-47ca9a-aakritipps-projects.vercel.app
Lamatic Flow
Flow ID:
26053fbe-e183-48b9-a6a1-a2eb14dac2aaChecklist
npm run dev.env.examplehas no secrets, only placeholdersREADME.mddocuments setup and usagekits/sql-query-generator/lamatic.config.tsis present and validflows/folderFiles Added
Documentation
Flow Configuration
Next.js Application
generateQuery()that validates inputs, calls the Lamatic flow, parses JSON response, and returns typed resultFlow Architecture & Node Types
The SQL Query Generator uses a 3-node sequential flow:
schemaandquestionas JSON inputsresultfield and returns JSON responseThe flow transforms natural language questions into structured SQL outputs containing: SQL query, explanation, tables used, assumptions, and confidence score (high/medium/low). It enforces read-only SELECT queries, supports PostgreSQL/MySQL/SQLite, and handles ambiguous questions gracefully.