mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-04-09 04:28:16 +00:00
docs: document NL2SQLTool read-only default and DML configuration
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,7 @@ mode: "wide"
|
||||
|
||||
يتيح ذلك سير عمل متعددة مثل أن يقوم وكيل بالوصول إلى قاعدة البيانات واسترجاع المعلومات بناءً على الهدف ثم استخدام تلك المعلومات لتوليد استجابة أو تقرير أو أي مخرجات أخرى. بالإضافة إلى ذلك، يوفر القدرة للوكيل على تحديث قاعدة البيانات بناءً على هدفه.
|
||||
|
||||
**تنبيه**: تأكد من أن الوكيل لديه وصول إلى نسخة قراءة فقط أو أنه من المقبول أن يقوم الوكيل بتنفيذ استعلامات إدراج/تحديث على قاعدة البيانات.
|
||||
**تنبيه**: الأداة للقراءة فقط بشكل افتراضي (SELECT/SHOW/DESCRIBE/EXPLAIN فقط). تتطلب عمليات الكتابة تمرير `allow_dml=True` أو ضبط متغير البيئة `CREWAI_NL2SQL_ALLOW_DML=true`. عند تفعيل الكتابة، تأكد من أن الوكيل يستخدم مستخدم قاعدة بيانات محدود الصلاحيات أو نسخة قراءة كلما أمكن.
|
||||
|
||||
## نموذج الأمان
|
||||
|
||||
@@ -36,6 +36,74 @@ mode: "wide"
|
||||
- أضف خطافات `before_tool_call` لفرض أنماط الاستعلام المسموح بها
|
||||
- فعّل تسجيل الاستعلامات والتنبيهات للعبارات التدميرية
|
||||
|
||||
## وضع القراءة فقط وتهيئة DML
|
||||
|
||||
تعمل `NL2SQLTool` في **وضع القراءة فقط بشكل افتراضي**. لا يُسمح إلا بأنواع العبارات التالية دون تهيئة إضافية:
|
||||
|
||||
- `SELECT`
|
||||
- `SHOW`
|
||||
- `DESCRIBE`
|
||||
- `EXPLAIN`
|
||||
|
||||
أي محاولة لتنفيذ عملية كتابة (`INSERT`، `UPDATE`، `DELETE`، `DROP`، `CREATE`، `ALTER`، `TRUNCATE`، إلخ) ستُسبب خطأً ما لم يتم تفعيل DML صراحةً.
|
||||
|
||||
كما تُحظر الاستعلامات متعددة العبارات التي تحتوي على فاصلة منقوطة (مثل `SELECT 1; DROP TABLE users`) في وضع القراءة فقط لمنع هجمات الحقن.
|
||||
|
||||
### تفعيل عمليات الكتابة
|
||||
|
||||
يمكنك تفعيل DML (لغة معالجة البيانات) بطريقتين:
|
||||
|
||||
**الخيار الأول — معامل المُنشئ:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
nl2sql = NL2SQLTool(
|
||||
db_uri="postgresql://example@localhost:5432/test_db",
|
||||
allow_dml=True,
|
||||
)
|
||||
```
|
||||
|
||||
**الخيار الثاني — متغير البيئة:**
|
||||
|
||||
```bash
|
||||
CREWAI_NL2SQL_ALLOW_DML=true
|
||||
```
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# DML مفعّل عبر متغير البيئة
|
||||
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
||||
```
|
||||
|
||||
### أمثلة الاستخدام
|
||||
|
||||
**القراءة فقط (الافتراضي) — آمن للتحليلات والتقارير:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# يُسمح فقط بـ SELECT/SHOW/DESCRIBE/EXPLAIN
|
||||
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
||||
```
|
||||
|
||||
**مع تفعيل DML — مطلوب لأعباء عمل الكتابة:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# يُسمح بـ INSERT وUPDATE وDELETE وDROP وغيرها
|
||||
nl2sql = NL2SQLTool(
|
||||
db_uri="postgresql://example@localhost:5432/test_db",
|
||||
allow_dml=True,
|
||||
)
|
||||
```
|
||||
|
||||
<Warning>
|
||||
يمنح تفعيل DML للوكيل القدرة على تعديل البيانات أو حذفها. لا تفعّله إلا عندما يتطلب حالة الاستخدام صراحةً وصولاً للكتابة، وتأكد من أن بيانات اعتماد قاعدة البيانات محدودة بالحد الأدنى من الصلاحيات المطلوبة.
|
||||
</Warning>
|
||||
|
||||
## المتطلبات
|
||||
|
||||
- SqlAlchemy
|
||||
|
||||
@@ -13,7 +13,7 @@ This tool is used to convert natural language to SQL queries. When passed to the
|
||||
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**: Make sure that the Agent has access to a Read-Replica or that is okay for the Agent to run insert/update queries on the database.
|
||||
**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
|
||||
|
||||
@@ -38,6 +38,74 @@ Use all of the following in production:
|
||||
- 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
|
||||
|
||||
@@ -11,7 +11,75 @@ mode: "wide"
|
||||
|
||||
이를 통해 에이전트가 데이터베이스에 접근하여 목표에 따라 정보를 가져오고, 해당 정보를 사용해 응답, 보고서 또는 기타 출력물을 생성하는 다양한 워크플로우가 가능해집니다. 또한 에이전트가 자신의 목표에 맞춰 데이터베이스를 업데이트할 수 있는 기능도 제공합니다.
|
||||
|
||||
**주의**: 에이전트가 Read-Replica에 접근할 수 있거나, 에이전트가 데이터베이스에 insert/update 쿼리를 실행해도 괜찮은지 반드시 확인하십시오.
|
||||
**주의**: 도구는 기본적으로 읽기 전용(SELECT/SHOW/DESCRIBE/EXPLAIN만 허용)으로 동작합니다. 쓰기 작업을 수행하려면 `allow_dml=True` 매개변수 또는 `CREWAI_NL2SQL_ALLOW_DML=true` 환경 변수가 필요합니다. 쓰기 접근이 활성화된 경우, 가능하면 권한이 제한된 데이터베이스 사용자나 읽기 복제본을 사용하십시오.
|
||||
|
||||
## 읽기 전용 모드 및 DML 구성
|
||||
|
||||
`NL2SQLTool`은 기본적으로 **읽기 전용 모드**로 동작합니다. 추가 구성 없이 허용되는 구문 유형은 다음과 같습니다:
|
||||
|
||||
- `SELECT`
|
||||
- `SHOW`
|
||||
- `DESCRIBE`
|
||||
- `EXPLAIN`
|
||||
|
||||
DML을 명시적으로 활성화하지 않으면 쓰기 작업(`INSERT`, `UPDATE`, `DELETE`, `DROP`, `CREATE`, `ALTER`, `TRUNCATE` 등)을 실행하려고 할 때 오류가 발생합니다.
|
||||
|
||||
읽기 전용 모드에서는 세미콜론이 포함된 다중 구문 쿼리(예: `SELECT 1; DROP TABLE users`)도 인젝션 공격을 방지하기 위해 차단됩니다.
|
||||
|
||||
### 쓰기 작업 활성화
|
||||
|
||||
DML(데이터 조작 언어)을 활성화하는 방법은 두 가지입니다:
|
||||
|
||||
**옵션 1 — 생성자 매개변수:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
nl2sql = NL2SQLTool(
|
||||
db_uri="postgresql://example@localhost:5432/test_db",
|
||||
allow_dml=True,
|
||||
)
|
||||
```
|
||||
|
||||
**옵션 2 — 환경 변수:**
|
||||
|
||||
```bash
|
||||
CREWAI_NL2SQL_ALLOW_DML=true
|
||||
```
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# 환경 변수를 통해 DML 활성화
|
||||
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
||||
```
|
||||
|
||||
### 사용 예시
|
||||
|
||||
**읽기 전용(기본값) — 분석 및 보고 워크로드에 안전:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# SELECT/SHOW/DESCRIBE/EXPLAIN만 허용
|
||||
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
||||
```
|
||||
|
||||
**DML 활성화 — 쓰기 워크로드에 필요:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# INSERT, UPDATE, DELETE, DROP 등이 허용됨
|
||||
nl2sql = NL2SQLTool(
|
||||
db_uri="postgresql://example@localhost:5432/test_db",
|
||||
allow_dml=True,
|
||||
)
|
||||
```
|
||||
|
||||
<Warning>
|
||||
DML을 활성화하면 에이전트가 데이터를 수정하거나 삭제할 수 있습니다. 사용 사례에서 명시적으로 쓰기 접근이 필요한 경우에만 활성화하고, 데이터베이스 자격 증명이 최소 필요 권한으로 제한되어 있는지 확인하십시오.
|
||||
</Warning>
|
||||
|
||||
## 요구 사항
|
||||
|
||||
|
||||
@@ -11,7 +11,75 @@ Esta ferramenta é utilizada para converter linguagem natural em consultas SQL.
|
||||
|
||||
Isso possibilita múltiplos fluxos de trabalho, como por exemplo ter um Agente acessando o banco de dados para buscar informações com base em um objetivo e, então, usar essas informações para gerar uma resposta, relatório ou qualquer outro tipo de saída. Além disso, permite que o Agente atualize o banco de dados de acordo com seu objetivo.
|
||||
|
||||
**Atenção**: Certifique-se de que o Agente tenha acesso a um Read-Replica ou que seja permitido que o Agente execute consultas de inserção/atualização no banco de dados.
|
||||
**Atenção**: Por padrão, a ferramenta opera em modo somente leitura (apenas SELECT/SHOW/DESCRIBE/EXPLAIN). Operações de escrita exigem `allow_dml=True` ou a variável de ambiente `CREWAI_NL2SQL_ALLOW_DML=true`. Quando o acesso de escrita estiver habilitado, certifique-se de que o Agente use um usuário de banco de dados com privilégios mínimos ou um Read-Replica sempre que possível.
|
||||
|
||||
## Modo Somente Leitura e Configuração de DML
|
||||
|
||||
O `NL2SQLTool` opera em **modo somente leitura por padrão**. Apenas os seguintes tipos de instrução são permitidos sem configuração adicional:
|
||||
|
||||
- `SELECT`
|
||||
- `SHOW`
|
||||
- `DESCRIBE`
|
||||
- `EXPLAIN`
|
||||
|
||||
Qualquer tentativa de executar uma operação de escrita (`INSERT`, `UPDATE`, `DELETE`, `DROP`, `CREATE`, `ALTER`, `TRUNCATE`, etc.) resultará em erro, a menos que o DML seja habilitado explicitamente.
|
||||
|
||||
Consultas com múltiplas instruções contendo ponto e vírgula (ex.: `SELECT 1; DROP TABLE users`) também são bloqueadas no modo somente leitura para prevenir ataques de injeção.
|
||||
|
||||
### Habilitando Operações de Escrita
|
||||
|
||||
Você pode habilitar DML (Linguagem de Manipulação de Dados) de duas formas:
|
||||
|
||||
**Opção 1 — parâmetro do construtor:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
nl2sql = NL2SQLTool(
|
||||
db_uri="postgresql://example@localhost:5432/test_db",
|
||||
allow_dml=True,
|
||||
)
|
||||
```
|
||||
|
||||
**Opção 2 — variável de ambiente:**
|
||||
|
||||
```bash
|
||||
CREWAI_NL2SQL_ALLOW_DML=true
|
||||
```
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# DML habilitado via variável de ambiente
|
||||
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
||||
```
|
||||
|
||||
### Exemplos de Uso
|
||||
|
||||
**Somente leitura (padrão) — seguro para análise e relatórios:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# Apenas SELECT/SHOW/DESCRIBE/EXPLAIN são permitidos
|
||||
nl2sql = NL2SQLTool(db_uri="postgresql://example@localhost:5432/test_db")
|
||||
```
|
||||
|
||||
**Com DML habilitado — necessário para workloads de escrita:**
|
||||
|
||||
```python
|
||||
from crewai_tools import NL2SQLTool
|
||||
|
||||
# INSERT, UPDATE, DELETE, DROP, etc. são permitidos
|
||||
nl2sql = NL2SQLTool(
|
||||
db_uri="postgresql://example@localhost:5432/test_db",
|
||||
allow_dml=True,
|
||||
)
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Habilitar DML concede ao agente a capacidade de modificar ou destruir dados. Ative apenas quando o seu caso de uso exigir explicitamente acesso de escrita e certifique-se de que as credenciais do banco de dados estejam limitadas aos privilégios mínimos necessários.
|
||||
</Warning>
|
||||
|
||||
## Requisitos
|
||||
|
||||
|
||||
Reference in New Issue
Block a user