Fix ValueError: Could not parse LLM output in LangChain
Error message
ValueError: Could not parse LLM output:This error occurs when LangChain's agent framework receives output from a language model that does not match the expected format for parsing an action and action input. The exact error message is: ValueError: Could not parse LLM output: "...". The most common cause is using a model that does not produce output in the structured format required by the agent type, particularly with open-source models like Hugging Face models.
What Causes This Error
The error arises from LangChain's output parser, which expects the LLM to return a string that can be parsed into an action (tool name) and action input (arguments for that tool). The parser uses a regular expression to extract these components. When the LLM output does not match this pattern, the parser raises a ValueError.
1. Model Incompatibility with Agent Type
This is the most frequently reported cause. LangChain agents are designed to work with models that can follow specific output formatting instructions. OpenAI models (like GPT-3.5 and GPT-4) are trained to follow these instructions reliably. However, many open-source models, such as those from Hugging Face (e.g., google/flan-t5-xl, bigscience/bloom), often fail to produce output in the required format. As noted in the GitHub issue discussion, "Agent only with OpenAI is only working well." The model may respond with a generic greeting like "Assistant, how can I help you today?" instead of the expected structured output.
2. Incorrect Agent Configuration
The agent type determines the expected output format. For example, the "conversational-react-description" agent expects the model to output a specific pattern like Action: <tool_name>\nAction Input: <input>. If the agent is misconfigured or the model is not prompted correctly, the output may not match.
3. Model Output Truncation or Hallucination
Some models may produce incomplete or malformed output, especially when the context window is exceeded or when the model is not fine-tuned for structured tasks. The output might be cut off mid-sentence, or the model might generate irrelevant text.
4. Verbose Mode Interference
Setting verbose=False in the agent initialization (as seen in the GitHub issue) does not cause the error, but it can hide the underlying model output that would help diagnose the issue. The error itself is not caused by verbosity settings.
How to Fix It
Solution 1: Use a Compatible Model (Recommended)
Source: GitHub issue discussion (community consensus)
The most reliable fix is to use a model that is known to work well with LangChain agents. OpenAI models are the safest choice. If you are using a Hugging Face model, consider switching to an OpenAI model or a model fine-tuned for instruction following.
Steps:
-
Install the OpenAI integration if not already installed:
pip install langchain-openai -
Replace your Hugging Face model with an OpenAI model:
from langchain_openai import ChatOpenAI from langchain.agents import initialize_agent, AgentType from langchain.memory import ConversationBufferMemory llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0) memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) agent_chain = initialize_agent( tools=tools, llm=llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, memory=memory, verbose=True ) response = agent_chain.run("Hi") print(response)
Expected outcome: The agent should now correctly parse the LLM output and execute the appropriate action.
Solution 2: Catch and Extract the Raw Output (Workaround)
Source: Stack Overflow accepted answer (ZKS) and GitHub comment by franciscoescher (75 reactions)
This is a temporary workaround that catches the ValueError, extracts the raw LLM output from the error message, and uses it as the response. It is useful when you cannot change the model but still need the application to function.
Steps:
-
Wrap your agent call in a try-except block:
try: response = agent_chain.run(input=query_str) except ValueError as e: response = str(e) if not response.startswith("Could not parse LLM output: `"): raise e response = response.removeprefix("Could not parse LLM output: `").removesuffix("`") -
The variable
responsenow contains the raw text that the LLM generated, which you can display or process further.
When to use this fix: This is ideal for prototyping, debugging, or when you have no control over the model selection. However, it bypasses the agent's tool-calling mechanism, so the agent will not actually use any tools. The output will be the model's raw response, which may not be the intended action.
Caveat: The Stack Overflow answer uses removeprefix and removesuffix, which are Python 3.9+ methods. If you are on an older Python version, use string slicing instead:
if response.startswith("Could not parse LLM output: `"):
response = response[len("Could not parse LLM output: `"):-1]
Solution 3: Adjust the Agent Prompt
Source: Official LangChain documentation (inferred from prompt engineering guidance)
You can customize the agent's prompt template to give the model clearer instructions on how to format its output. This is more advanced but can improve compatibility with certain models.
Steps:
-
Import the necessary classes:
from langchain.agents import AgentExecutor, create_react_agent from langchain.prompts import PromptTemplate from langchain.tools import Tool -
Define a custom prompt that explicitly states the expected output format:
custom_prompt = PromptTemplate( input_variables=["input", "chat_history", "agent_scratchpad"], template="""You are a helpful assistant. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original input question
Begin!
Chat History: {chat_history}
Question: {input} {agent_scratchpad}""" )
3. Create the agent with the custom prompt:
```python
agent = create_react_agent(llm, tools, custom_prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
response = agent_executor.invoke({"input": "Hi"})
Expected outcome: The model may now produce output that matches the expected format, reducing parsing errors.
Solution 4: Use a Different Agent Type
Source: LangChain documentation (community recommendation)
Some agent types are more forgiving with output formatting. For example, the "zero-shot-react-description" agent has a simpler expected format compared to "conversational-react-description".
Steps:
-
Change the agent type:
agent_chain = initialize_agent( tools=tools, llm=llm, agent="zero-shot-react-description", memory=memory, verbose=True ) -
Test with a simple input.
When to use this fix: If your use case does not require conversational memory, this simpler agent type may work better with non-OpenAI models.
If Nothing Works
If none of the above solutions resolve the issue, consider the following escalation paths:
- Switch to OpenAI models: As confirmed by the GitHub issue discussion, OpenAI models are the most compatible with LangChain agents. If your application can use them, this is the most reliable path.
- Use a different framework: Consider using a framework designed for open-source models, such as
transformerswith custom agent logic, orllama_indexwhich may have better support for non-OpenAI models. - File a GitHub issue: If you believe this is a bug in LangChain, open an issue at https://github.com/langchain-ai/langchain/issues with a minimal reproducible example. Include the exact model, agent type, and full error traceback.
- Community forums: Post on Stack Overflow with the
langchaintag, or ask in the LangChain Discord community for real-time help.
How to Prevent It
- Test model compatibility early: Before building a full application, test your chosen model with a simple agent call to ensure it can produce parsable output.
- Use OpenAI models for agents: If your project allows, prefer OpenAI models for agent-based workflows. They are the most tested and supported.
- Set verbose=True during development: This will print the full LLM output, making it easier to diagnose formatting issues.
- Keep LangChain updated: Newer versions may include better error handling or support for additional models. Run
pip install --upgrade langchainregularly. - Consider fine-tuning: If you must use a specific open-source model, consider fine-tuning it to produce output in the required format. The OpenAI documentation notes that fine-tuning can help models "consistently format responses in a certain way." While this is specific to OpenAI, the principle applies to any model.
The #1 Chatgpt Newsletter
The most important chatgpt updates, guides, and fixes — one weekly email.
No spam, unsubscribe anytime. Privacy policy
Sources & References
This page was researched from 4 independent sources, combined and verified for completeness.
- 1.OpenAI Documentation — Fine TuningOfficial documentation · primary source
- 2.Answer by ZKS (score 1, accepted)Stack Overflow
- 3.ValueError: Could not parse LLM output:GitHub issue
- 4.
Related Error Solutions
Keep exploring ChatGPT
ChatGPT resources
Latest AI answers
Skip the manual work
Ready-made AI workflows and automation templates — import and run instead of building from scratch.