langchain-ai/langchain · error · OutputParserException

Could not parse function call: {exc}

Error message

Could not parse function call: {exc}

What it means

The OpenAI-functions output parser reads `message.additional_kwargs["function_call"]`; if the key is absent, the KeyError is caught and re-raised as OutputParserException with `Could not parse function call: 'function_call'`. This means the model did not emit a (legacy) function call at all — the message is plain content or uses modern `tool_calls` instead — so there is nothing for this parser to extract.

Source

Thrown at libs/core/langchain_core/output_parsers/openai_functions.py:51

            result: The result of the LLM call.
            partial: Whether to parse partial JSON objects.

        Returns:
            The parsed JSON object.

        Raises:
            OutputParserException: If the output is not valid JSON.
        """
        generation = result[0]
        if not isinstance(generation, ChatGeneration):
            msg = "This output parser can only be used with a chat generation."
            raise OutputParserException(msg)
        message = generation.message
        try:
            func_call = copy.deepcopy(message.additional_kwargs["function_call"])
        except KeyError as exc:
            msg = f"Could not parse function call: {exc}"
            raise OutputParserException(msg) from exc

        if self.args_only:
            return func_call["arguments"]
        return func_call


class JsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]):
    """Parse an output as the JSON object."""

    strict: bool = False
    """Whether to allow non-JSON-compliant strings.

    See: https://docs.python.org/3/library/json.html#encoders-and-decoders

    Useful when the parsed output may include unicode characters or new lines.
    """

    args_only: bool = True

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Force the call: bind the function with `tool_choice`/`function_call` set to the required function so the model must emit it.
  2. If the model uses modern tool calling, switch to reading `message.tool_calls` or `JsonOutputFunctionsParser`-era helpers replaced by `with_structured_output` — do not use this legacy parser.
  3. Catch OutputParserException and handle the no-call case (e.g. surface the model's text answer or retry with stronger instructions).
  4. Verify the model/endpoint supports function calling at all (e.g. some local/OSS endpoints return text).

Example fix

// before
llm = ChatOpenAI(model="gpt-4o")
chain = prompt | llm | OpenAIFunctionCallerOutputParser()

// after (modern tool calling)
from pydantic import BaseModel
class Sentiment(BaseModel):
    label: str
chain = prompt | llm.with_structured_output(Sentiment, method="function_calling")
Defensive patterns

Strategy: try-catch

Validate before calling

def has_function_call(message) -> bool:
    return "function_call" in getattr(message, "additional_kwargs", {})

# before parsing
if not has_function_call(result[0].message):
    raise ValueError("model returned no function call; inspect message.content")

Type guard

def has_legacy_function_call(msg) -> bool:
    return isinstance(getattr(msg, "additional_kwargs", {}).get("function_call"), dict)

Try / catch

from langchain_core.exceptions import OutputParserException

try:
    out = parser.parse_result(result)
except OutputParserException as e:
    if "function_call" in str(e):
        msg = result[0].message
        if msg.tool_calls:  # modern API responded
            out = msg.tool_calls[0]["args"]
        else:
            out = retry_with_forced_tool_choice(chain)  # bind tool_choice='required'

Prevention

When it happens

Trigger: The model answered in plain text instead of invoking the bound function; the chain bound `tools` (modern tool calling, which populates `tool_calls`) while the parser expects legacy `function_call`; function calling not enabled on the endpoint/model.

Common situations: Using newer models/endpoints that only support the `tools` API with the older `create_openai_fn_chain`/function_call parser; prompts that let the model answer directly instead of forcing a call (`function_call={"name": ...}` / `tool_choice` not set); models that hallucinate an answer instead of calling.

Related errors


AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14). Data as JSON: /api/errors/f0eece03eb18df5b. Report an issue: GitHub.