LangChain SQL Agent OutputParserException: Fix Parse Errors
A LangChain SQL agent OutputParserException (Could not parse LLM output) happens because the text-based ReAct parser cannot read a chat model's free-form reply. Use ChatOpenAI with agent_type='openai-tools' and set handle_parsing_errors=True.
- The error means the zero-shot ReAct parser did not find the exact Action / Action Input or Final Answer lines in the model's reply.
- Use ChatOpenAI (not the legacy OpenAI class) for gpt-3.5-turbo, gpt-4 and gpt-4o, with temperature=0.
- agent_type='openai-tools' or 'tool-calling' replaces text parsing with structured tool calls, which removes most parse failures.
- Pass agent_executor_kwargs={'handle_parsing_errors': True} and a sane max_iterations as a safety net, not as the main fix.
- Connect with a read-only Postgres role and limit tables with include_tables so a wrong query cannot damage data or flood the context window.
Which problem do you have? A quick diagnosis
The message 'OutputParserException: Could not parse LLM output' comes from the agent's output parser, not from the database or the API. The model answered, but the answer was not in the shape the agent loop requires. Work through the table from top to bottom, because the first match is usually the cause.
The pattern is simple: the more the agent depends on the model writing exact text, the more often a chat model breaks it.
| Symptom | Likely cause | Fix |
|---|---|---|
| You use OpenAI(model_name='gpt-3.5-turbo') or text-davinci-003 | Completion class pointed at a chat model, or a retired model | Switch to ChatOpenAI(model='gpt-4o-mini' or similar) |
| agent_type is 'zero-shot-react-description' (the default in older code) | Fragile Thought / Action text parsing | Use agent_type='openai-tools' or 'tool-calling' |
| Error text shows a reply with ```sql fences or prose before the answer | Model ignored the ReAct format | Tool-calling agent, plus handle_parsing_errors=True |
| Imports from langchain.agents.agent_toolkits or langchain.llms | Old import paths mixed with new packages | Upgrade and use langchain_community and langchain_openai imports |
| Works on one table, fails on the full database | Huge tool output or schema pushing the model off format | Limit tables, sample rows and top_k |
| Fails only after several steps | Loop hit max_iterations or the context filled | Simplify the question, raise limits carefully, use a longer-context model |
What is a working create_sql_agent setup for Postgres?
The following is a complete setup on the split packages. Install them first: pip install -U langchain langchain-community langchain-openai langchain-experimental psycopg2-binary. Set OPENAI_API_KEY in the environment rather than in code.
Before and after: the broken version typically used OpenAI(temperature=0) with the default zero-shot ReAct agent, with imports from langchain.agents. The fixed version below swaps in a chat model and a tool-calling agent.
from langchain_community.utilities import SQLDatabase
from langchain_community.agent_toolkits.sql.toolkit import SQLDatabaseToolkit
from langchain_community.agent_toolkits import create_sql_agent
from langchain_openai import ChatOpenAI
# Use a read-only role (see the safety section)
db = SQLDatabase.from_uri(
"postgresql+psycopg2://readonly_agent:secret@localhost:5432/shop",
include_tables=["customers", "orders", "order_items"],
sample_rows_in_table_info=2,
)
llm = ChatOpenAI(model="gpt-4o", temperature=0)
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
agent = create_sql_agent(
llm=llm,
toolkit=toolkit,
agent_type="openai-tools", # or "tool-calling"
verbose=True,
top_k=10,
max_iterations=8,
agent_executor_kwargs={"handle_parsing_errors": True},
)
result = agent.invoke({"input": "Top 5 customers by total order value in 2024"})
print(result["output"])Why does the LangChain SQL agent OutputParserException happen with chat models?
The default zero-shot ReAct agent asks the model to write plain text in a strict template: Thought, Action, Action Input, then Observation, and finally 'Final Answer:'. The parser uses a regular expression on that text. If neither a valid Action block nor a Final Answer line is found, it raises OutputParserException and prints the raw reply.
Chat models are trained to be conversational. They often answer with a friendly sentence, wrap SQL in ```sql fences, skip the 'Action:' line, or put the answer in markdown. All of these are sensible to a person and fatal to a regex. Completion models such as text-davinci-003 followed few-shot formats more literally, which is why the same code worked before the switch.
The class matters too. gpt-3.5-turbo and gpt-4 are served by the chat completions endpoint, which takes a list of messages. The legacy OpenAI class targets the completions endpoint, so it is wrong for these models. ChatOpenAI sends messages correctly and supports tool calling. text-davinci-003 is retired, and it had roughly a 4k token window, which is part of why people moved to larger-context chat models.
Tool calling removes the fragile step. With agent_type='openai-tools', the API returns a structured tool call (a function name plus JSON arguments) instead of text that has to be scraped. The parser reads fields, not prose, so formatting habits of the model stop mattering. Parse errors then mostly appear only when the model emits invalid arguments.
How do I make the agent retry instead of crashing?
Set handle_parsing_errors through agent_executor_kwargs. With True, the executor sends a generic 'Invalid or incomplete response' observation back to the model and lets it try again. A custom string gives better guidance, and a function can build the message from the error.
This helps with temporary format slips but it does not fix a wrong agent type. Each retry costs tokens and one iteration, so a model that fails every time will just burn its budget.
agent = create_sql_agent(
llm=llm,
toolkit=toolkit,
agent_type="openai-tools",
verbose=True,
max_iterations=8,
max_execution_time=60,
agent_executor_kwargs={
"handle_parsing_errors": (
"Your last reply was not valid. Call a tool, or give the final "
"answer as plain text with no code fences."
)
},
)How do I keep token use under control on large schemas?
The agent lists tables, fetches schemas for the ones it picks, and sees sample rows and query results. On a large database, those tool outputs fill the context window, and a model near its limit gets sloppier about format. This is also the usual source of token limit and context length errors.
Reduce what the model sees first, and buy a bigger window second. gpt-4-turbo and gpt-4o offer 128k contexts, but a big prompt still costs money and slows every step.
| Setting | Where | Effect |
|---|---|---|
| include_tables=[...] | SQLDatabase.from_uri | Exposes only the listed tables; the biggest saving |
| ignore_tables=[...] | SQLDatabase.from_uri | Hides noisy tables such as logs or audit |
| sample_rows_in_table_info=2 | SQLDatabase.from_uri | Fewer example rows per table (default is 3); 0 drops them |
| custom_table_info={...} | SQLDatabase.from_uri | Replace auto-generated DDL with short hand-written descriptions |
| view_support=True | SQLDatabase.from_uri | Lets the agent see views, so you can expose a tidy reporting view instead of many raw tables |
| top_k=10 | create_sql_agent | Prompt tells the model to limit results, reducing returned rows |
| Longer-context model | ChatOpenAI(model=...) | Gives headroom, not a substitute for trimming |
How do I debug a remaining parse error, and run it safely?
The agent can execute any SQL its connection allows, including DROP and DELETE, whether from a model mistake or a prompt injection hidden in data. Create a read-only role before you test, and never point an experimental agent at a production database with write rights.
Run this as a superuser, replacing the names and password. It grants SELECT only and also sets a statement timeout so runaway queries stop.
- Turn on verbose=True, or call langchain.globals.set_debug(True), to see every prompt and tool call.
- Read the exception text: it contains the raw model reply, which shows whether it used fences, prose, or no Action line.
- Test with one table through include_tables to separate schema problems from format problems.
- Confirm the model name is valid for your account, and that OPENAI_API_KEY is set in the running process, since bad names or keys raise different errors that are easy to confuse.
- Verify agent_type is a tool-calling type and the llm is ChatOpenAI, not OpenAI.
- If gpt-3.5 still fails after these changes, try gpt-4o or another stronger model before adding more prompt text.
psql -U postgres -d shop <<'SQL'
CREATE ROLE readonly_agent LOGIN PASSWORD 'change-me';
GRANT CONNECT ON DATABASE shop TO readonly_agent;
GRANT USAGE ON SCHEMA public TO readonly_agent;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_agent;
ALTER ROLE readonly_agent SET default_transaction_read_only = on;
ALTER ROLE readonly_agent SET statement_timeout = '15s';
SQL Should I use create_sql_agent, a query chain, or LangGraph?
The agent is flexible because it can explore the schema, run a query, see an error and fix it. That flexibility costs extra model calls and more chances to go off format. If your questions follow a predictable shape, a fixed pipeline is cheaper and easier to test.
Most common mistakes come down to three habits: a wrong or retired model name, the legacy OpenAI class with a chat model, and old import paths mixed with new packages. A fourth is leaving big tables and sample rows exposed so tool outputs flood the context.
| Approach | Best for | Tradeoffs |
|---|---|---|
| create_sql_agent (tool-calling) | Exploratory questions, unknown schema, self-correcting queries | More tokens and calls; needs a read-only role and iteration limits |
| create_sql_query_chain plus manual execution | Predictable question types, one generated query per request | No self-repair; you validate and run the SQL yourself |
| LangGraph prebuilt or custom agent | Production flows needing control, retries, human approval before execution | More code, but explicit steps and state |
Common questions
Can I just set handle_parsing_errors=True and ignore the rest?
It stops the crash, but it hides the root cause. With a ReAct agent on a chat model, you may still get repeated retries, wasted tokens and iteration-limit stops. Use it as a fallback on top of a tool-calling agent.
What is the difference between 'openai-tools', 'openai-functions' and 'tool-calling'?
'openai-functions' uses the older function-calling API, which OpenAI has deprecated in favor of tools. 'openai-tools' uses the newer tools API, and 'tool-calling' is the provider-neutral version that works with any chat model that supports tool calls. For ChatOpenAI today, either of the last two is appropriate.
Does the SQL agent work with databases other than Postgres?
Yes. SQLDatabase uses SQLAlchemy, so any supported dialect works by changing the URI and installing its driver, such as pymysql for MySQL. SQL syntax differs per dialect, and the agent reads the dialect from the connection, so check generated queries for dialect-specific functions.
Why do I get a context length error on a database with many tables?
The table list, schemas and sample rows are all placed in the prompt, and big query results are added on each step. Limit tables with include_tables, drop sample rows, and keep top_k small. Only then consider a 128k-context model.
Will an upgrade fix the error by itself?
Often, because newer releases support tool-calling agent types and better chat model handling. Run pip show langchain langchain-community langchain-openai to see versions, upgrade them together, and update imports to the langchain_community and langchain_openai paths.