mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-07-01 21:28:10 +00:00
* feat: adopt directory-based docs versioning with Edge channel Switch docs.crewai.com from navigation-only versioning (every version selector entry rendered the same docs/<lang>/* source files) to Mintlify's directory-based versioning so each version selector entry renders its own snapshot. Add an "Edge" channel under docs/edge/<lang>/* that always reflects main HEAD for unreleased work, eliminating pre-release leakage onto frozen release labels. External links to canonical /<lang>/* URLs are preserved via wildcard redirects that always land on the current default version. Layout: - docs/edge/<lang>/* rolling source (you edit here) - docs/edge/enterprise-api.*.yaml - docs/v<X.Y.Z>/<lang>/* frozen, immutable snapshots - docs/v<X.Y.Z>/enterprise-api.*.yaml - docs/images/ shared, append-only - docs/docs.json nav + redirects URLs follow the Mintlify-idiomatic shape: /edge/<lang>/<page> for Edge, /v<X.Y.Z>/<lang>/<page> for every frozen snapshot. The wildcard redirects /<lang>/:slug* -> /<default>/<lang>/:slug* keep stale links working, and every freeze rewrites them (plus all per-section/per-page redirects) so destinations always resolve to the current default without depending on a second redirect hop. Release flow integration (devtools release): - New module crewai_devtools.docs_versioning.freeze() materialises docs/v<X.Y.Z>/ from docs/edge/, rewrites openapi: refs inside the snapshot, inserts the version into every language block in docs.json, and refreshes all redirect destinations. - _update_docs_and_create_pr() in cli.py now calls that freeze during Phase 2 of devtools release. Edge changelogs are updated first (so the snapshot freeze picks them up), then the snapshot is staged alongside docs.json, branched as docs/freeze-v<X.Y.Z>, and the PR is titled [docs-freeze] docs: snapshot and changelog for v<X.Y.Z> — the title prefix the new CI guard reads. - The PR still gates tag, GitHub release, PyPI publish, and the enterprise release as before; no new PRs are added. - Pre-releases (1.X.YaN, 1.X.YbN, ...) skip the snapshot — they ride Edge — and the docs PR title omits the [docs-freeze] prefix. - docs_check (AI-generated docs scaffolding) writes to docs/edge/<lang>/* so newly-generated unreleased docs land in Edge and never accidentally touch a frozen snapshot. Migration scripts (one-shot): - scripts/docs/freeze_historical_versions.py reconstructs all 16 historical snapshots (v1.10.0 .. v1.14.7) from git tags via git archive | tar, rewriting openapi: MDX refs so each snapshot reads its own enterprise-api YAML rather than the live one. - scripts/docs/prefix_version_paths.py one-shot-migrates docs.json: rewrites every page path in 16 versioned blocks to point under docs/v<X.Y.Z>/, inserts a new Edge entry per language, tags v1.14.7 as Latest (default), prunes pages whose target file doesn't exist in the snapshot (e.g. docs/ar/ didn't exist before v1.12.0), and writes the wildcard + per-section redirects. - scripts/docs/freeze_current_edge.py is now a thin CLI wrapper around docs_versioning.freeze for manual one-off freezes (e.g. retroactively snapshotting a forgotten release). CI guards (.github/workflows/docs-snapshots.yml): - Frozen snapshots under docs/v[0-9]*/ are immutable; only PRs whose title contains [docs-freeze] (i.e. release-cut PRs generated by devtools release or the manual wrapper) may modify them. - Images under docs/images/ are append-only since snapshots share a single image directory. Deleting or renaming an image breaks every historical snapshot that still references it. Restored docs/images/crewai-otel-export.png from PR #3673; it was deleted in PR #4908 but v1.10.0 / v1.10.1 snapshots still reference it. Restoring instead of editing the snapshots preserves historical rendering fidelity and validates the new append-only rule retroactively. Tests: - lib/devtools/tests/test_docs_versioning.py covers the freeze: file copy, openapi rewrite, version insertion, default demotion, redirect upserts, per-section redirect rewriting, idempotency, and invalid inputs. Verified locally with mintlify broken-links: 0 broken links across the full site (Edge + 16 frozen versions, 4 locales). AGENTS.md (repo root) is the contributor guide for the new model; RELEASING.md is the release-cut runbook; README's Contribution section links to both. Co-authored-by: Cursor <cursoragent@cursor.com> * style: resolve linter issues --------- Co-authored-by: Cursor <cursoragent@cursor.com>
176 lines
6.3 KiB
Plaintext
176 lines
6.3 KiB
Plaintext
---
|
|
title: NL2SQL Tool
|
|
description: The `NL2SQLTool` is designed to convert natural language to SQL queries.
|
|
icon: language
|
|
mode: "wide"
|
|
---
|
|
|
|
## Overview
|
|
|
|
|
|
This tool is used to convert natural language to SQL queries. When passed to the agent it will generate queries and then use them to interact with the database.
|
|
|
|
This enables multiple workflows like having an Agent to access the database fetch information based on the goal and then use the information to generate a response, report or any other output.
|
|
Along with that provides the ability for the Agent to update the database based on its goal.
|
|
|
|
**Attention**: By default the tool is read-only (SELECT/SHOW/DESCRIBE/EXPLAIN only). Write operations require `allow_dml=True` or the `CREWAI_NL2SQL_ALLOW_DML=true` environment variable. When write access is enabled, make sure the Agent uses a scoped database user or a read replica where possible.
|
|
|
|
## Security Model
|
|
|
|
`NL2SQLTool` is an execution-capable tool. It runs model-generated SQL directly against the configured database connection.
|
|
|
|
This means risk depends on your deployment choices:
|
|
|
|
- Which credentials you provide in `db_uri`
|
|
- Whether untrusted input can influence prompts
|
|
- Whether you add tool-call guardrails before execution
|
|
|
|
If you route untrusted input to agents using this tool, treat it as a high-risk integration.
|
|
|
|
## Hardening Recommendations
|
|
|
|
Use all of the following in production:
|
|
|
|
- Use a read-only database user whenever possible
|
|
- Prefer a read replica for analytics/retrieval workloads
|
|
- Grant least privilege (no superuser/admin roles, no file/system-level capabilities)
|
|
- Apply database-side resource limits (statement timeout, lock timeout, cost/row limits)
|
|
- Add `before_tool_call` hooks to enforce allowed query patterns
|
|
- Enable query logging and alerting for destructive statements
|
|
|
|
## Read-Only Mode & DML Configuration
|
|
|
|
`NL2SQLTool` operates in **read-only mode by default**. Only the following statement types are permitted without additional configuration:
|
|
|
|
- `SELECT`
|
|
- `SHOW`
|
|
- `DESCRIBE`
|
|
- `EXPLAIN`
|
|
|
|
Any attempt to execute a write operation (`INSERT`, `UPDATE`, `DELETE`, `DROP`, `CREATE`, `ALTER`, `TRUNCATE`, etc.) will raise an error unless DML is explicitly enabled.
|
|
|
|
Multi-statement queries containing semicolons (e.g. `SELECT 1; DROP TABLE users`) are also blocked in read-only mode to prevent injection attacks.
|
|
|
|
### Enabling Write Operations
|
|
|
|
You can enable DML (Data Manipulation Language) in two ways:
|
|
|
|
**Option 1 — constructor parameter:**
|
|
|
|
```python
|
|
from crewai_tools import NL2SQLTool
|
|
|
|
nl2sql = NL2SQLTool(
|
|
db_uri="postgresql://example@localhost:5432/test_db",
|
|
allow_dml=True,
|
|
)
|
|
```
|
|
|
|
**Option 2 — environment variable:**
|
|
|
|
```bash
|
|
CREWAI_NL2SQL_ALLOW_DML=true
|
|
```
|
|
|
|
```python
|
|
from crewai_tools import NL2SQLTool
|
|
|
|
# DML enabled via environment variable
|
|
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
|
```
|
|
|
|
### Usage Examples
|
|
|
|
**Read-only (default) — safe for analytics and reporting:**
|
|
|
|
```python
|
|
from crewai_tools import NL2SQLTool
|
|
|
|
# Only SELECT/SHOW/DESCRIBE/EXPLAIN are permitted
|
|
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
|
```
|
|
|
|
**DML enabled — required for write workloads:**
|
|
|
|
```python
|
|
from crewai_tools import NL2SQLTool
|
|
|
|
# INSERT, UPDATE, DELETE, DROP, etc. are permitted
|
|
nl2sql = NL2SQLTool(
|
|
db_uri="postgresql://example@localhost:5432/test_db",
|
|
allow_dml=True,
|
|
)
|
|
```
|
|
|
|
<Warning>
|
|
Enabling DML gives the agent the ability to modify or destroy data. Only enable this when your use case explicitly requires write access, and ensure the database credentials are scoped to the minimum required privileges.
|
|
</Warning>
|
|
|
|
## Requirements
|
|
|
|
- SqlAlchemy
|
|
- Any DB compatible library (e.g. psycopg2, mysql-connector-python)
|
|
|
|
## Installation
|
|
|
|
Install the crewai_tools package
|
|
|
|
```shell
|
|
pip install 'crewai[tools]'
|
|
```
|
|
|
|
## Usage
|
|
|
|
In order to use the NL2SQLTool, you need to pass the database URI to the tool. The URI should be in the format `dialect+driver://username:password@host:port/database`.
|
|
|
|
|
|
```python Code
|
|
from crewai_tools import NL2SQLTool
|
|
|
|
# psycopg2 was installed to run this example with PostgreSQL
|
|
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
|
|
|
@agent
|
|
def researcher(self) -> Agent:
|
|
return Agent(
|
|
config=self.agents_config["researcher"],
|
|
allow_delegation=False,
|
|
tools=[nl2sql]
|
|
)
|
|
```
|
|
|
|
## Example
|
|
|
|
The primary task goal was:
|
|
|
|
"Retrieve the average, maximum, and minimum monthly revenue for each city, but only include cities that have more than one user. Also, count the number of user in each city and
|
|
sort the results by the average monthly revenue in descending order"
|
|
|
|
So the Agent tried to get information from the DB, the first one is wrong so the Agent tries again and gets the correct information and passes to the next agent.
|
|
|
|

|
|

|
|
|
|
|
|
The second task goal was:
|
|
|
|
"Review the data and create a detailed report, and then create the table on the database with the fields based on the data provided.
|
|
Include information on the average, maximum, and minimum monthly revenue for each city, but only include cities that have more than one user. Also, count the number of users in each city and sort the results by the average monthly revenue in descending order."
|
|
|
|
Now things start to get interesting, the Agent generates the SQL query to not only create the table but also insert the data into the table. And in the end the Agent still returns the final report which is exactly what was in the database.
|
|
|
|

|
|

|
|
|
|

|
|

|
|
|
|
|
|
This is a simple example of how the NL2SQLTool can be used to interact with the database and generate reports based on the data in the database.
|
|
|
|
The Tool provides endless possibilities on the logic of the Agent and how it can interact with the database.
|
|
|
|
```md
|
|
DB -> Agent -> ... -> Agent -> DB
|
|
```
|