A locally operated SQL development agent.
Text-to-SQL agent that turns questions into reviewable, executable and auditable SQL. It generates an OSI semantic layer from the database, plans before writing, and asks instead of guessing. CLI and web interface · MySQL · any OpenAI-compatible model.
Topics: text-to-sql · nl2sql · text2sql · natural-language-to-sql · sql · sql-generator · sql-agent · sql-debugger · sql-debugger-harness · ai-agent · llm · semantic-layer · mysql · data-analysis · cli · python · openai · deepseek · self-hosted · vue
Install with an agent · Quick start · Web interface · Web interface guide · Model endpoints · Commands · Event model · FAQ
Chinese version: README.ch.md
Each run keeps the query plan, the clarification exchange and the debug evidence, so every output can be traced and reproduced. The command-line interface and the Python SDK share a single core; the repository also provides a web interface that reaches that core through a local bridge and behaves identically.
Note
The system runs entirely locally and depends on no hosted service. Apart from the model endpoint and the database declared in configuration, it issues no outbound requests.
The paragraph below is a complete instruction for a local coding agent. Copy it into Claude Code, Codex, Cursor, WorkBuddy or any agent that can run shell commands and let it run: the agent performs the installation itself. No further context is required, because the paragraph names the repository, the interpreter, the [mysql] extra and the verification step.
Install SQL Coder CLI on this machine and verify the installation.
1. Clone https://github.com/AskSqlAI/asksql_coding_assistant.git and enter the directory.
2. Create a virtual environment with Python 3.11 or newer in .venv, and activate it.
3. Run: pip install -e ".[mysql]"
4. Run: coder --version
It must print sql-coder-cli 0.2.0. If the entry point is not on PATH, run
.venv/bin/python -m sql_coder --version instead (.venv\Scripts\python on Windows).
Constraints: do not install into the system interpreter; do not create or edit a runtime
configuration; do not connect to a database; do not run coder scan or coder run.
When finished, report the virtual-environment path, the exact output of the version check, and
any error message verbatim, without summarising it.
The agent stops after verification. Configuring a model endpoint and a database is a separate step, described under Quick start or performed in the web interface.
General-purpose assistants fail on data tasks in three recurring ways: they re-explore the warehouse on every question, invent their own metric logic, and return numbers that disagree with approved definitions. Traditional semantic layers require continuous manual upkeep and absorb little of the organisation's existing knowledge. SQL Coder addresses this with four mechanisms:
- Automated semantic-file retrieval and generation. The system connects directly to the target database, retrieves schema, column types and value distributions, and generates a database semantic file conforming to the OSI standard. The file is maintained as YAML and may be revised locally to suit the business context (aliases, synonyms, weights, enumerated values); such revisions remain in effect as generation context.
- SQL project planning and clarification. Plan mode produces a query plan for human review, and SQL is written only after approval. Where the metric definition, statistical window or column ownership is ambiguous, the system issues a structured clarification with candidate options and a recommendation instead of proceeding on an assumption.
- Stepwise SQL debugging. A complete statement, an editor selection, a specific CTE or a UNION branch may each be executed independently, returning the result set, the number of rows and the elapsed time, bounded by row-count, result-byte and timeout limits. Execution is strictly read-only and the debug evidence is archived as files.
- Memory module. Business metric definitions, definitions and query constraints accumulate per project and can be reviewed as of a point in time or by revision. Memory is injected as context in later sessions, so the agent's understanding of the same business objects converges with use.
A wrong number in a multi-CTE query does not indicate which stage produced it, and copying a CTE into a scratch editor changes its context — the input columns, the row multiplicity, the filters — so the copy no longer reproduces the defect.
SQL Coder parses a statement into addressable segments and executes any one of them in place. Three granularities are available in both the CLI and the web editor, where the scope is chosen by selection:
| Granularity | In the editor | CLI |
|---|---|---|
| The whole statement | nothing selected | --main |
| One complete CTE | a whole CTE declaration | --cte <name> |
| A SELECT fragment inside a CTE | that CTE's SELECT body | --range <line>:<col>-<line>:<col> |
| One UNION branch | — | --branch <n> |
A CTE runs with its transitive dependencies prepended as WITH clauses; a fragment runs with every CTE declared above it. Neither requires editing the statement, and neither can reach the final query.
coder debug --sql-file report.sql --semantic semantic.yaml --list-segments
coder debug --sql-file report.sql --semantic semantic.yaml --cte british
coder debug --sql-file report.sql --semantic semantic.yaml --main--list-segments reports each segment's name, character span and dependency list, so the order of execution is read rather than inferred. The three scopes return different things, which is what makes the failing stage identifiable: on a three-CTE query over the Formula 1 dataset, the british CTE returns 100 rows — the row cap — in 2.9 s, the SELECT inside wins (which joins that CTE to f1.results) returns 21 rows in 3.0 s, and the whole statement returns the final 10 rows in 3.1 s.
The web editor performs the same three scopes and keeps the evidence: the Executed SQL tab shows the statement actually issued, so a fragment run visibly begins with the materialised WITH block instead of assuming it. Section 6 of the web interface guide shows all three cases.
Every target is checked as read-only before it executes and is bounded by row, result-byte and timeout limits. The evidence — generated SQL, columns, rows, elapsed time and truncation flag — is archived under an id that can be cited in review.
| Capability | General-purpose assistant | Traditional semantic layer | SQL Coder |
|---|---|---|---|
| Builds schema and value context automatically | No | Manual | ✓ |
| Generates an OSI semantic file, locally revisable | No | Partial | ✓ |
| Plans first, generates after human review | No | No | ✓ |
| Clarifies ambiguous definitions | Occasional | No | ✓ |
| Read-only stepwise debug (CTEs, UNION branches) | No | No | ✓ |
| Metric memory with point-in-time views | No | Partial | ✓ |
| Independent of hosted services | Vendor-dependent | Vendor-dependent | ✓ |
Use it when: an agent must query an internal warehouse or operational database under approved definitions; business knowledge is scattered across documents and individual experience and needs to accumulate; the generation process must be reviewable, the output traceable and the execution read-only.
Do not use it when: no SQL database is available, or only a single ad-hoc query is required.
Supported: MySQL through the corresponding SQLAlchemy dialect and driver; any Chat Completions-compatible model endpoint. Ready-made templates are given for OpenAI, DeepSeek, Kimi, Doubao, MiniMax, Qwen, GLM, Hunyuan and Xiaomi MiMo; self-hosted gateways work too.
| Need | Requirement | Notes |
|---|---|---|
| Python | 3.11 or newer | Check with python --version; older versions cannot install the package |
| A database | MySQL | Prepare a read-only account on an existing database |
| A model API key | Chat Completions-compatible vendor | See step 3. DeepSeek is the least effort: a few dollars of credit is enough |
You also need network access to the model endpoint and the database. Everything else — sessions, versions, memory — stays in a local directory.
If you do not have the code yet:
git clone <repository-url> sql-coder-cli
cd sql-coder-cliCreate a virtual environment and install (pick one; if uv is not installed, use option B — nothing else is needed):
# Option A: uv
uv venv
.venv\Scripts\activate # Windows PowerShell / CMD
source .venv/bin/activate # macOS / Linux
uv pip install -e ".[mysql]"
# Option B: the standard library venv
python -m venv .venv
.venv\Scripts\activate # Windows
source .venv/bin/activate # macOS / Linux
pip install -e ".[mysql]"The extra in brackets is the database driver: MySQL needs pymysql.
Confirm it worked:
coder --version # prints sql-coder-cli 0.2.0coder: command not foundmeans the virtual environment is not active, or you are not in the repository root.- An active environment shows
(.venv)in the prompt.
Installation provides the dependencies and does not determine how the system is used. Both paths share one core and one runtime configuration; steps 2–5 (read-only account, model key, runtime configuration) are common prerequisites. After those, continue along one of the paths below.
Path 1: web interface
Intended for work that requires inspecting the schema visually, revising SQL over successive turns and reading query results directly. Semantic-file generation, later adjustments to the model and connections, workspace management, conversational generation and SQL validation are all performed in the interface; the semantic scan command of step 6 is not required. Startup is described under Web interface, and the walkthrough is the web interface guide.
Path 2: command line (CLI)
Intended for scripted calls, batch execution and automation. From step 6 onward the work proceeds through commands: generate the semantic file, state the requirement, and validate SQL. The command and option reference is under Commands.
Write down five values for step 5: host, port, database name, account and password. The port defaults to 3306 and cloud instances are often remapped.
Create a dedicated read-only account rather than using root. MySQL:
CREATE USER 'coder_reader'@'%' IDENTIFIED BY 'replace-with-your-password';
GRANT SELECT ON sales.* TO 'coder_reader'@'%';Confirm it worked: the account can connect and list tables.
mysql -h 127.0.0.1 -P 3306 -u coder_reader -p sales -e "show tables;"DeepSeek is used here as the example; other vendors are in Model endpoints.
- Sign up at platform.deepseek.com.
- Create a key under "API keys" and copy the
sk-...string — it is shown once. - New accounts usually need a small top-up, otherwise calls fail on insufficient balance.
Fill it into llm.api_key in step 5 — no environment variables needed. The key is stored in plaintext, so keep coder.yaml out of git (it is listed in .gitignore).
On the web path this step, and steps 5 to 8, can be skipped. The bridge writes an empty configuration on first start — model, connections and memory all blank — and those values are entered in the browser, as described in step 9. The procedure below is for the command line.
examples/runtime.example.yaml carries every option with annotations; for CLI use, copy it and edit:
cp examples/runtime.example.yaml coder.yaml- Where: the repository root, next to the README, is fine. The file name is free-form — point at it with
--config; these docs usecoder.yamlso the commands can be copied verbatim. - One template only:
examples/runtime.example.yamlholds the whole configuration (comments in English) — MySQL + DeepSeek by default, with a several-database layout in section 1.1 and nine model vendors plus self-hosted gateways in sections 2.1-2.10, all inside the same file. Those alternative blocks are commented out: delete the corresponding main block, then uncomment. - Eight values to change: marked
[REQUIRED]in the template (database idsource_id, host, port, database name, account, password, and the modelmodel/api_key).providernames the vendor and the address follows from it;base_urlis only needed for a custom gateway. - Credentials are plaintext: the password and API key sit directly in
coder.yaml, which.gitignoreexcludes. To share one file, switchpassword:/api_key:topassword_env:/api_key_env:and export the variables. - Path rule (the usual trap): relative paths inside the file (
runtime.workspace) resolve against the configuration file's directory; command-line arguments (--output,--semantic,--input) resolve against your current directory. The template writes./content, which lands on<repo>/contentonce copied to the root. - A
--requestJSON follows a third rule: itssemantic_fileandsql_fileresolve againstruntime.workspace, not the current directory.
Shell syntax (Windows users): the commands below use bash. In PowerShell, line continuation is a backtick (`), not \; cp becomes Copy-Item; and <...> placeholders must be replaced before pasting — angle brackets are reserved characters in PowerShell.
Open coder.yaml; every line carries a comment. The essentials:
database section (required — the database you query)
| Field | Meaning | How to fill |
|---|---|---|
source_id |
Name of this database inside the project | Your choice, e.g. sales-mysql. Written into the semantic file; renaming requires a new scan |
dialect |
Database type | mysql |
driver |
Driver | pymysql |
host |
Database host | 127.0.0.1 for local; the console address for a cloud instance |
port |
Port | 3306; use the real value |
database |
Database name | The database/schema name |
username |
Account | The read-only account from step 2 |
password |
Account password | Write the password itself. password_env: VAR_NAME or password_file: ./db.pwd also work (pick exactly one) |
charset |
Character set (MySQL) | utf8mb4 for Chinese content |
connect_timeout_seconds |
Connection timeout | Default 10; 30 for public networks |
statement_timeout_seconds |
Per-statement limit | Default 30; raise it for large scans |
llm section (required — the model endpoint)
| Field | Meaning | How to fill |
|---|---|---|
provider |
Vendor identifier (optional) | Chooses how vendor-private parameters are sent: deepseek / openai / kimi / doubao / qwen / glm / minimax / hunyuan / xiaomi / generic. Omit it and the vendor is inferred from the URL and model name |
base_url |
Model service address | Optional. A known provider supplies it; fill it only for generic (your own gateway, vLLM, Ollama, one-api). Never append /chat/completions — the program adds it |
model |
Model name | Must match a model available to your account exactly, case included |
api_key |
API key | Write the sk-... key itself. api_key_env: VAR_NAME also works (pick one) |
timeout_seconds |
Per-call time limit | Default 120; 180–300 for models that reason by default (MiniMax, GLM, Hunyuan) |
json_mode |
Ask for structured output | Default true; set false if the endpoint rejects response_format: json_object |
provider also accepts familiar aliases: moonshot (=kimi), ark (=doubao), dashscope (=qwen), zhipu (=glm), tencent (=hunyuan), mimo (=xiaomi), openai_compatible (=generic).
The program never turns a vendor's deep reasoning on by itself. provider affects two things only: DeepSeek is explicitly told to disable thinking, and OpenAI reasoning models switch to the developer role. Everything else follows the vendor default, which is why the same model is sometimes slow — it is reasoning. There is no configuration switch to enable it.
base_url is where most first attempts fail. The rule and the vendor table are in Model endpoints; copy-paste blocks live in sections 2.1-2.10 of examples/runtime.example.yaml.
Model settings can also come from the environment. The file still supplies the database and the
workspace; these four variables override the llm section, so a shared file never has to carry a
key:
export CODER_LLM_PROVIDER=deepseek # vendor; its address is applied automatically
export CODER_LLM_MODEL=deepseek-chat
export CODER_LLM_API_KEY=sk-...
# export CODER_LLM_BASE_URL=... # only for a custom gatewayWhen CODER_LLM_PROVIDER names a known vendor, an inherited base_url in the file is dropped
instead of being mixed with the new vendor's address; set CODER_LLM_BASE_URL to keep a custom
endpoint.
The settings page in the web bridge offers the same list: choose a provider, pick or type a model, paste the key. The address field only appears for the custom provider.
runtime / memory sections
| Field | Meaning | How to fill |
|---|---|---|
runtime.workspace |
Runtime output directory | Sessions, versions, events and memory live here; created if missing. ./content is fine |
runtime.language |
Output language | chinese / english |
runtime.mode |
Working mode | ordinary writes SQL directly; plan drafts a query plan for your approval first |
runtime.coding_profile |
Coding emphasis | general, or sp for stored procedures and complex scripts |
memory.enabled |
Memory switch | false by default: nothing is stored or injected. Set true, or turn on Memory in the settings page, when definitions should accumulate |
memory.project_id |
Memory partition | Single database: align it with source_id. Several databases: use one project name (e.g. demo) and let source_id separate them |
memory.actor_id |
Actor identity | Your choice, e.g. local-user |
memory.timezone |
Memory time zone | e.g. Asia/Shanghai |
coder scan --config coder.yaml --output semantic.yamlThis step reads table structures and value distributions and never calls the model, which makes it the right way to test the database configuration: if it passes, account, host, database name and driver are all correct.
Confirm it worked: the command prints an indented JSON block (add --format jsonl for one line), for example
{"status": "completed", "output": "C:\\path\\to\\semantic.yaml", "tables": 12}tables above zero means tables were found; semantic.yaml now exists and its semantic_model: section groups columns by table.
If it fails: Access denied for user points back to step 2; ModuleNotFoundError: No module named 'pymysql' means the extra from step 1 was not installed.
Add --overwrite when the target exists, and --table orders --table customers to scan only some tables.
coder run "Total order amount per customer, top 10" --config coder.yaml --window orders --semantic semantic.yaml--window names the session window (your choice; one window is one continuous conversation); --semantic is only used when the window is created.
Confirm it worked: the printed JSON contains
{"status": "completed", "session_id": "session_...", "run_id": "run_...", "sql_version": 1}-
status: completedwithsql_version≥ 1 means SQL has been produced. -
Keep
session_idfor step 8. -
rundoes not return the SQL text. To read it:coder history --config coder.yaml --session <session_id> --version 1
Continuing the same conversation: run coder run "..." --config coder.yaml --window orders again (without --semantic; passing it is ignored with a notice). Reusing a window name continues it; only switching databases needs a new name — passing another database's semantic file to an existing window fails with Semantic file belongs to another database.
If status is pending, the model needs a decision from you — a clarification, or (in plan mode) approval of the query plan. Inspect it with:
coder status --config coder.yaml --session <session_id>The returned pending is the pending checkpoint; pending.questions lists the questions (in plan mode, pending.plan_version instead). Event history requires --run:
coder status --config coder.yaml --run <run_id> --eventsThe simplest way to answer is interactive mode, which asks each question in the terminal:
coder chat --config coder.yaml --window ordersFor scripted use, write an answer file as answer.json and submit it:
{
"submission_id": "answer-1",
"session_id": "<session_id from the previous step>",
"checkpoint_id": "<pending.hook_id>",
"action": "answer",
"answers": [
{"question_id": "<pending.questions[0].id>", "answer_type": "manual", "text": "Count by order creation time, paid orders only"}
]
}coder resume --config coder.yaml --request answer.jsonsubmission_ididentifies this submission — any unused string works (resubmitting the same id does not run twice).checkpoint_idmust equalpending.hook_id, otherwiseCheckpoint changed or was consumed.answersmust cover every question (one entry each); copyquestion_idfrompending.questions[].idrather than inventing one.- In
planmode the action is notanswer: approve with{"action": "approve_plan", "plan_version": <pending.plan_version>, "submission_id": ..., "session_id": ..., "checkpoint_id": ...}, or request changes with"action": "revise_plan"plus"instruction": "group by quarter instead".
coder debug --config coder.yaml --session <session_id> --main--main executes the whole statement; --cte, --branch and --range run a single segment instead. Each entry of the returned results list carries columns, rows, returned (row count) and elapsed_ms, with rows bounded by data_access.max_rows.
Confirm it worked: results contains columns and rows with no error. The pipeline is complete.
No configuration file is required beforehand. Start the bridge, open the page, and work through the four settings in order; the web interface guide covers each with screenshots.
- Model service — pick a provider, enter the model name and API key, use Test connection, then save.
- Database connections — add the read-only account and choose Save & generate semantic file; the file is written to
content/semantic/. - Memory — the switch at the bottom of the settings page, off by default; enable it when business definitions should accumulate.
- New workspace — select the database from the previous step as the subject and start asking.
Settings go to the file named when the bridge starts (by default runtime.private.yaml in the repository root, created on first start and already in .gitignore). The CLI and the interface then read and write that one file. Startup is described under Web interface.
Read the error class first: ContractError is a configuration mistake, ModelError a model-endpoint problem, DatabaseError a database problem. Exit codes are listed under Commands.
| Error or symptom | Cause | Fix |
|---|---|---|
Provide --config or CODER_CONFIG |
No --config on the command |
Add --config coder.yaml, or set CODER_CONFIG |
KeyError: 'CODER_LLM_API_KEY' / 'CODER_DB_PASSWORD' |
Only with the *_env style: variable unset, misspelled, or lost with a new terminal |
Match the *_env names exactly and verify with echo, or go back to password: / api_key: |
Access denied / HTTP 401 with credentials that look filled in |
The template placeholders (change-me, sk-replace-with-your-key) were left unchanged |
Put in the real password and key |
Missing llm configuration fields |
base_url or model absent |
Add the two required fields |
Unsupported llm.provider |
provider not recognised |
Use a value from the supported list in the message, or delete the line |
runtime config version must be 1 |
version at the top is not 1 |
Set version: 1 |
HTTP 404 or model not found |
/chat/completions included in base_url, a wrong path prefix (missing compatible-mode, api/v1 instead of api/paas/v4), or a model name absent from the account / misspelled |
Compare both address and model name against the table in Model endpoints |
HTTP 401 / Authentication failed |
Wrong or truncated key, stray spaces, or a key paired with another vendor's address | Re-copy the key; MiMo pay-as-you-go keys (sk-) and Token Plan keys (tp-) must match their own address |
Configured LLM request failed: Connection error |
Network blocked, proxy, unreachable host | Test the same address with curl; configure a proxy if required |
Configured LLM request deadline exceeded |
The model is slower than timeout_seconds |
Raise timeout_seconds (300 for models that reason by default) |
ModuleNotFoundError: No module named 'pymysql' |
Wrong extra at install time | Reinstall with pip install -e ".[mysql]" |
Access denied for user |
Wrong credentials, or the account may not connect from your IP | Check the account; in MySQL 'user'@'%' and 'user'@'localhost' are different grants |
Unknown database 'xxx' |
Wrong or missing database name | Use the output of show databases; |
Scan succeeds but tables is 0 (or semantic_model.tables is empty) |
No SELECT privilege, or the wrong schema |
Grant SELECT on the schema you scan |
Choose a database |
Several databases configured, none selected | Add --database <key>, i.e. the key under databases / its source_id (e.g. dw), not the database field |
Database key must equal its source_id |
Key under databases differs from source_id |
Make them identical |
Unknown database ... known=[...] |
The semantic file's source_id is not a configured database (renamed without rescanning, or the wrong file) |
Rescan, or point --semantic at the right file |
Semantic file belongs to another database |
Another database's semantic file was passed to an existing window | Use a new --window name; a window never switches databases |
Window name already exists |
A new window reused an existing name | Pick another name; to continue, reuse the original --window |
SQL file debug requires --semantic |
debug --sql-file without a semantic file, so the database is unknown |
Add --semantic semantic.yaml |
chat requires a TTY |
A TTY is an interactive terminal; stdin/stdout are not one in a pipeline, redirect or CI job | Use run / resume |
Checkpoint changed or was consumed |
checkpoint_id does not match the pending checkpoint, or it was already answered |
Re-read the latest pending.hook_id with coder status --session |
MODEL_DECISION_INVALID |
The model's JSON could not be parsed (common with small models) | Switch to a stronger model; check json_mode against endpoint capability |
| Garbled Chinese text | Database charset is not utf8mb4, or a terminal encoding issue |
Set charset: utf8mb4; on Windows use PowerShell 7 or chcp 65001 |
The web interface shares the same SDK as the CLI; the bridge works against the core and the workspace store through that SDK. A step-by-step walkthrough with screenshots, from model configuration to SQL validation, is in the web interface guide.
Prerequisite: one — Node.js 18 or later. No configuration file and no placeholder have to be prepared: when the bridge cannot find one it writes an empty skeleton (llm: {}, databases: {}, memory.enabled: false), and the model service, connections, semantic files and memory switch are all set in the interface.
If a configuration file already exists (for instance one left by the CLI flow), the interface reads and writes that same file, so the two entry points never keep separate settings. The semantic file may be generated in the interface (Section 3 of the guide); if one was produced by coder scan, its semantic_model.name must equal that connection's identifier — that value is how the web interface matches data subjects.
Two startup modes are available. They expose the same functionality and read the same configuration; they differ in whether the frontend code is modified. Mode 1 suits work on web/src, provides hot reload and requires two terminals. Mode 2 is for using the interface only: the bridge serves the build output and a single terminal is sufficient.
Mode 1: frontend development server (two terminals, hot reload)
# Terminal 1: local bridge (long-running, foreground; .venv activated)
cd web
pip install -e .. # only when the editable package is absent
python server/bridge.py --port 8777 # no --config needed: created on first start
# Terminal 2: frontend dev server (/ask is proxied to 8777)
cd web
npm install
npm run dev # http://127.0.0.1:5173Open http://127.0.0.1:5173. Frontend edits are reloaded by the development server without a rebuild.
Mode 2: build once, serve from the bridge (one terminal, no hot reload)
cd web
npm install
npm run build # output goes to web/dist
python server/bridge.py --port 8777 # no --config needed: created on first startOpen http://127.0.0.1:8777. The bridge serves the static files under web/dist for every path other than /ask/, falling back to index.html when a file is absent. This mode has no hot reload: rerun npm run build after frontend changes.
Debugging from the interface. The editor doubles as a read-only debugger. Validate query executes the statement as written; with text selected it executes the selection instead — complete CTE declarations run as those CTEs, and a CTE's SELECT body runs as a fragment with the CTEs above it prepended as WITH. The panel lists the columns and rows returned for each target, and the Executed SQL tab shows the statement actually issued, so the injected WITH block is visible rather than assumed; a failed run shows the database error verbatim. Every run is archived as evidence under an id that also records elapsed time, row count and the truncation flag. Section 6 of the web interface guide covers all three scopes with screenshots; addressing a segment by name (--cte, --branch) remains a CLI capability, described under CTE-level debugging.
The interface provides SQL editing and formatting, conversational generation and modification, clarification cards, plan review, version history and restoration, read-only result tables, diff review, and session listing and creation (the "subject" corresponds to a configured database).
The llm section only asks two things: which vendor's address to call, and how deep that address goes.
This project implements OpenAI Chat Completions only (POST /chat/completions), so the llm section has no protocol field: the address comes from base_url, and vendor differences are expressed by provider below.
provider is optional. It does not change the address; it only decides how vendor-specific reasoning controls are passed: DeepSeek reads extra_body.thinking, OpenAI reads reasoning_effort, and the remaining vendors take a plain Chat Completions call.
When omitted, the vendor is inferred from the address and model name (anything containing deepseek is DeepSeek, gpt-5/o1/o3/o4 is OpenAI, everything else is generic). With a third-party gateway, set provider: generic explicitly — gateway URLs often contain deepseek, and inference would send a thinking field to an endpoint that does not accept it.
The program calls through the OpenAI SDK, which appends /chat/completions to base_url. Fill in the version prefix, not the full endpoint path.
| Value | Result | |
|---|---|---|
| ✗ | https://api.deepseek.com/chat/completions |
The request becomes .../chat/completions/chat/completions; 404 |
| ✗ | https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions |
Same, 404 |
| ✗ | https://open.bigmodel.cn/api/v1 |
That is the Responses endpoint, not Chat Completions; 404 |
| ✓ | https://api.deepseek.com |
Requests https://api.deepseek.com/chat/completions |
| ✓ | https://dashscope.aliyuncs.com/compatible-mode/v1 |
Requests .../compatible-mode/v1/chat/completions |
Handled by the program, so you must not write them:
/chat/completions— appended automatically; this project only uses that one path.- A trailing
/— stripped (https://api.deepseek.com/v1/works, but leave it off). /responses,/messages,/anthropic,/embeddings— other protocols; this project never uses those entries.- Query strings such as
?api-version=...— unsupported; supply a clean address.
What you must get right: the host and path prefix exactly as the vendor documents them (Bailian's compatible-mode, Zhipu's api/paas/v4, Ark's api/v3 cannot be shortened or altered).
The table reflects the official model lists as of 2026-11. Model names change with each release — trust your console; the shape of base_url is stable.
| Vendor | provider |
base_url (stop here) |
Example model |
|---|---|---|---|
| OpenAI | openai |
https://api.openai.com/v1 |
gpt-5.2, gpt-5.2-chat-latest |
| DeepSeek | deepseek |
https://api.deepseek.com |
deepseek-v4-flash, deepseek-v4-pro |
| Kimi (Moonshot) | kimi |
https://api.moonshot.cn/v1 |
kimi-k2.6, kimi-k2.5 |
| Doubao (Volcengine Ark) | doubao |
https://ark.cn-beijing.volces.com/api/v3 |
doubao-seed-2-1-pro-260915 or ep-xxxxxxxx |
| MiniMax | minimax |
https://api.minimaxi.com/v1 |
MiniMax-M2.7, MiniMax-M3 |
| Qwen (Alibaba Bailian) | qwen |
https://dashscope.aliyuncs.com/compatible-mode/v1 |
qwen3.8-max, qwen3.8-flash |
| GLM (Zhipu) | glm |
https://open.bigmodel.cn/api/paas/v4 |
glm-5, glm-5.3 |
| Hunyuan HY (Tencent) | hunyuan |
https://api.hunyuan.cloud.tencent.com/v1 or https://tokenhub.tencentmaas.com/v1 |
hy4, hy4-flash, hy3 |
| Xiaomi MiMo | xiaomi |
https://api.xiaomimimo.com/v1 (https://token-plan-cn.xiaomimimo.com/v1 for Token Plan) |
mimo-v2.6-pro, mimo-v2.6-flash |
To switch vendors, replace the whole llm section. Sections 2.1-2.10 of examples/runtime.example.yaml hold ten copy-paste blocks in the same order (OpenAI, DeepSeek, Kimi, Doubao, MiniMax, Qwen, GLM, Hunyuan, Xiaomi, self-hosted) — delete the active llm: in the main body before uncommenting one, otherwise the duplicate key is silently overridden.
The traps are almost entirely about paths and key pairing:
- OpenAI:
/v1is required (nothing adds it for you);gpt-5.2is a reasoning model and uses thedeveloperrole, whilegpt-5.2-chat-latestis called withsystem. - DeepSeek:
/v1is optional;deepseek-chat/deepseek-reasonerwere retired in July 2026 — usedeepseek-v4-flash/deepseek-v4-pro;provider: deepseekexplicitly disables thinking. - Kimi: use
/v1only — not/anthropic(Anthropic protocol) or/v1/responses. - Doubao: the path is
api/v3, notv1; with an inference endpoint put theep-identifier inmodel; swapcn-beijingfor your region. - MiniMax: the host ends in
minimaxi.com(notapi.minimax.chat); M2/M3 reason by default, so allowtimeout_seconds: 300. - Qwen:
compatible-modeis mandatory;https://dashscope.aliyuncs.com/api/v1is the native protocol, not the OpenAI-compatible entry. - GLM: Chat Completions lives under
api/paas/v4;api/v1is Responses andapi/anthropicis Anthropic. - Hunyuan: pick one of the two hosts (compatible endpoint or TokenHub); the default five concurrent requests show up as slowness, not errors.
- Xiaomi: pay-as-you-go
sk-keys pair withhttps://api.xiaomimimo.com/v1; Token Plantp-/ttp-keys pair withhttps://token-plan-cn.xiaomimimo.com/v1. Never mix them. - Self-hosted gateways: set
provider: genericso adeepseekin the URL is not mistaken for DeepSeek; addjson_mode: falsewhen the gateway rejectsresponse_format: json_object.
Replace the database section with a databases mapping; each entry takes exactly the fields of the single-database form:
databases:
sales:
source_id: sales # must equal the key
dialect: mysql
driver: pymysql
host: 10.0.0.11
port: 3306
database: sales
username: coder_reader
password: sales-password
reporting:
source_id: reporting # must equal the key
dialect: mysql
driver: pymysql
host: 10.0.0.12
port: 3306
database: reporting
username: coder_reader
password: reporting-passwordFour rules:
-
The key must equal
source_id, otherwiseDatabase key must equal its source_id. That name is written into the semantic file and is the "data topic" shown in the web interface.--databasetakes this key (e.g.dw), not thedatabasefield (warehouse). -
Scan one semantic file per database, naming it with
--database:coder scan --config coder.yaml --database sales --output semantic.sales.yaml coder scan --config coder.yaml --database dw --output semantic.dw.yaml
With several databases configured, a
scanwithout--databasefails withChoose a database— deliberate, so the wrong database is never scanned silently. -
The semantic file decides the binding: when a window is created, whichever file you pass to
--semanticfixes the database, and a session never switches mid-conversation. Switching databases requires a window name that has never been used — passing another database's semantic file to an existing window fails withSemantic file belongs to another database; the same database's file is ignored with a notice.coder run "..." --config coder.yaml --semantic semantic.dw.yaml --window dw -
Fill the password in each entry (
sales-password,dw-passwordin the example) rather than sharing one credential across databases.
A complete annotated form is in section 1.3 of examples/runtime.example.yaml (delete the main-body database: block before uncommenting it).
src/sql_coder/ CLI and Python SDK (shared core)
├── cli.py command-line entry point (coder)
├── runtime.py sessions, runs, versions, export, debugging
├── core/ planner / policy / tools / history / memory hooks
├── agent/ agent loop, events, JSON repair
└── extraction/ semantic extraction
web/ web interface (Vue 3 + Naive UI + CodeMirror 6)
├── server/bridge.py local bridge, calls the SDK only
└── src/ frontend sources
examples/ configuration and request-body examples
reports/ design notes, test records, self-check scripts
content/ runtime workspace (sessions, versions, memory, events)
Version control covers src/, web/src/, examples/ and the configuration templates; content/ (runtime data), reports/ (local design notes and self-check scripts), .runtime/ and build/ are excluded by .gitignore and are absent after a clone.
scan, run, chat, resume and debug require --config coder.yaml (or CODER_CONFIG) — database connection and model endpoint both come from it. The remaining commands (status, history, restore, import, export, recover, memory) may instead use --workspace <dir> pointing at an existing runtime directory.
| Command | Purpose | Principal options |
|---|---|---|
scan |
generate the semantic YAML | --output (required), --database, --schema, --table, --sample-rows, --overwrite |
run |
open a window or ask again | --window (omit with --request), --semantic, --mode, --coding-profile, --language, --format |
chat |
interactive multi-turn session in a terminal | --window, --semantic; requires a TTY |
resume |
submit clarifications, review a plan, continue an interrupted run | --request (see examples/resume.request.json) |
status |
query run or session status | --run / --session, --events (only with --run), --after-sequence |
cancel |
cancel a running operation | --run |
debug |
execute SQL read-only | --sql-file (needs --semantic to resolve the database) / --session, --main / --range / --cte / --branch, --row-limit, --timeout-seconds |
history |
list or read versions | --session, --kind sql|plan, --version |
restore |
restore a version as a new version | --session, --kind, --version |
import |
import SQL or semantics from a file | --session, --kind, --input |
export |
export a work record or artifact | --record (use the id from history, not reference_id) / --artifact, --output |
recover |
repair runs and the memory index after abnormal termination | --run / --memory-index |
memory show |
inspect business memory | --database, --type, --query, --history, --as-of |
memory forget |
delete a single memory record | --id / --request |
Output is JSON by default (chat is plain text). With --format jsonl, run and resume write events line by line; the other commands that accept the flag print only the final result line.
Exit codes: 0 success, 1 run failed, 2 invalid request, 3 awaiting human decision, 4 model or database error, 5 partial completion or I/O error, 130 cancelled.
{"type":"run.started","payload":{"operation_id":"...","instruction":"..."}}
{"type":"message.delta","payload":{"message_id":"...","text":"..."}}
{"type":"work_record.committed","payload":{"revision":{"kind":"sql","version":1}}}
{"type":"run.finished","payload":{"status":"pending","sql_version":1}}When human intervention is required, run.finished.status is pending and the result carries a checkpoint (coder_clarification or coder_plan_review); the run continues after the answers or review comments are submitted through coder resume --request.
- Is schema or query output sent to a hosted service? No. The system runs locally; the only outbound request targets the configured model endpoint.
- Can the database connection write data? No. The execution path permits read-only queries only, and both debugging and verification are bounded by row and timeout limits.
- What happens when the model returns an unparsable decision? A local structural repair is attempted first (removing redundant brackets, taking the first complete object, closing missing brackets); if that fails, one repair request carrying the original text and the parser error is issued, and it may correct structure only, never content.
- Is plan mode mandatory? No. Ordinary mode produces SQL directly; plan mode suits structurally complex work or cases where the definition must be confirmed first.
- How are multiple databases distinguished? By
source_id, which must equal the key underdatabases. A session binds to one of them at creation and does not switch across databases. - How do I know the configuration is right? In two steps:
coder scantouches only the database, so passing it proves the database section;coder runthen proves the model endpoint. The two failure modes never mask each other. - What changes when I switch models? Only the
llmsection:provider,base_url,modelandapi_key. Templates are in Model endpoints. - Can credentials sit directly in the configuration? That is the default (
password:/api_key:): copy the template, fill it in, run.coder.yamlis excluded by.gitignore; if the file is shared with others, switch to*_envpointing at environment variables or*_filepointing at a separate file.
# backend self-check scripts live in the local reports/ directory (not committed)
# frontend and bridge (two terminals)
cd web && python server/bridge.py --config ../coder.yaml --port 8777
cd web && npm install && npm run dev| Path | Purpose |
|---|---|
src/sql_coder/cli.py |
command definition and dispatch |
src/sql_coder/runtime.py |
sessions, runs, versions, export, debugging |
src/sql_coder/core/ |
planning, policy, tools, history and memory hooks |
web/server/bridge.py |
HTTP bridge and event forwarding |