# create_sql_agent

> **Function** in `langchain_community`

📖 [View in docs](https://reference.langchain.com/python/langchain-community/agent_toolkits/sql/base/create_sql_agent)

Construct a SQL agent from an LLM and toolkit or database.

!!! warning
    This agent can execute arbitrary SQL against your database.

    By default, the agent is allowed to generate SQL strings and run them via the
    database connection. This is powerful, but it also means the agent can generate
    expensive or dangerous queries (e.g., long-running queries, large scans/joins,
    locking queries, or unintended writes depending on your database permissions).

    ``create_sql_agent`` returns a ``langchain_classic`` ``AgentExecutor``.
    ``AgentExecutor`` is an agent abstraction that has long been considered legacy
    and is not actively supported as the recommended foundation for new production
    applications.

    For production-grade agent development, prefer building with Deep Agents:
    https://github.com/langchain-ai/deepagents

    If you use this in production, coordinate with your security/DB teams and apply
    server-side controls:

    - Use least-privilege database roles (ideally read-only, schema-limited).
    - Enforce statement timeouts / max execution time and other resource limits at the
      role or session level.
    - Apply query guardrails (e.g., restrict accessible schemas/tables, limit
      concurrency, and monitor/alert on slow queries).

    Client-side timeouts do not always guarantee that a running statement is
    cancelled on the database server.

## Signature

```python
create_sql_agent(
    llm: BaseLanguageModel,
    toolkit: Optional[SQLDatabaseToolkit] = None,
    agent_type: Optional[Union[AgentType, Literal['openai-tools', 'tool-calling']]] = None,
    callback_manager: Optional[BaseCallbackManager] = None,
    prefix: Optional[str] = None,
    suffix: Optional[str] = None,
    format_instructions: Optional[str] = None,
    input_variables: Optional[List[str]] = None,
    top_k: int = 10,
    max_iterations: Optional[int] = 15,
    max_execution_time: Optional[float] = None,
    early_stopping_method: str = 'force',
    verbose: bool = False,
    agent_executor_kwargs: Optional[Dict[str, Any]] = None,
    extra_tools: Sequence[BaseTool] = (),
    *,
    db: Optional[SQLDatabase] = None,
    prompt: Optional[BasePromptTemplate] = None,
    **kwargs: Any = {},
) -> AgentExecutor
```

## Description

Example:

.. code-block:: python

    from langchain_openai import ChatOpenAI
    from langchain_community.agent_toolkits import create_sql_agent
    from langchain_community.utilities import SQLDatabase

    db = SQLDatabase.from_uri("sqlite:///Chinook.db")
    llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
    agent_executor = create_sql_agent(llm, db=db, agent_type="tool-calling", verbose=True)

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `llm` | `BaseLanguageModel` | Yes | Language model to use for the agent. If agent_type is "tool-calling" then llm is expected to support tool calling. |
| `toolkit` | `Optional[SQLDatabaseToolkit]` | No | SQLDatabaseToolkit for the agent to use. Must provide exactly one of 'toolkit' or 'db'. Specify 'toolkit' if you want to use a different model for the agent and the toolkit. (default: `None`) |
| `agent_type` | `Optional[Union[AgentType, Literal['openai-tools', 'tool-calling']]]` | No | One of "tool-calling", "openai-tools", "openai-functions", or "zero-shot-react-description". Defaults to "zero-shot-react-description". "tool-calling" is recommended over the legacy "openai-tools" and "openai-functions" types. (default: `None`) |
| `callback_manager` | `Optional[BaseCallbackManager]` | No | DEPRECATED. Pass "callbacks" key into 'agent_executor_kwargs' instead to pass constructor callbacks to AgentExecutor. (default: `None`) |
| `prefix` | `Optional[str]` | No | Prompt prefix string. Must contain variables "top_k" and "dialect". (default: `None`) |
| `suffix` | `Optional[str]` | No | Prompt suffix string. Default depends on agent type. (default: `None`) |
| `format_instructions` | `Optional[str]` | No | Formatting instructions to pass to ZeroShotAgent.create_prompt() when 'agent_type' is "zero-shot-react-description". Otherwise ignored. (default: `None`) |
| `input_variables` | `Optional[List[str]]` | No | DEPRECATED. (default: `None`) |
| `top_k` | `int` | No | Number of rows to query for by default. (default: `10`) |
| `max_iterations` | `Optional[int]` | No | Passed to AgentExecutor init. (default: `15`) |
| `max_execution_time` | `Optional[float]` | No | Passed to AgentExecutor init. (default: `None`) |
| `early_stopping_method` | `str` | No | Passed to AgentExecutor init. (default: `'force'`) |
| `verbose` | `bool` | No | AgentExecutor verbosity. (default: `False`) |
| `agent_executor_kwargs` | `Optional[Dict[str, Any]]` | No | Arbitrary additional AgentExecutor args. (default: `None`) |
| `extra_tools` | `Sequence[BaseTool]` | No | Additional tools to give to agent on top of the ones that come with SQLDatabaseToolkit. (default: `()`) |
| `db` | `Optional[SQLDatabase]` | No | SQLDatabase from which to create a SQLDatabaseToolkit. Toolkit is created using 'db' and 'llm'. Must provide exactly one of 'db' or 'toolkit'. (default: `None`) |
| `prompt` | `Optional[BasePromptTemplate]` | No | Complete agent prompt. prompt and {prefix, suffix, format_instructions, input_variables} are mutually exclusive. (default: `None`) |
| `**kwargs` | `Any` | No | Arbitrary additional Agent args. (default: `{}`) |

## Returns

`AgentExecutor`

An AgentExecutor with the specified agent_type agent.

---

[View source on GitHub](https://github.com/langchain-ai/langchain-community/blob/4b280287bd55b99b44db2dd849f02d66c89534d5/libs/community/langchain_community/agent_toolkits/sql/base.py#L46)