AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Memory Leak In LangChain OpenAI Plain LLM Calls Causes OOM In Long-Running Containers

LangChain's OpenAI integration leaks memory per invocation, eventually causing OOM after a few hundred calls. Memray indicates retention of response objects and Pydantic schemas, affecting both OpenAI and Google Gemini backends.

highConfidence 55%Langchainlangchain-coreEmbeddingsAffected Vlangchain-Core 1.2.7Affected Vlangchain-Openai 1.1.7Affected Vlangchain-Google-Genai 4.2.0Affected Vpydantic 2.12.5Affected Vopenai 2.16.0

Origin Analysis

LangChain does not close the underlying httpx response returned by the OpenAI Python SDK after parsing, and Pydantic's TypeAdapter cache retains model schemas. The combination prevents garbage collection of transient response objects and leads to monotonically increasing memory usage.
1. Create ChatOpenAI instance with use_responses_api=True. 2. Invoke a simple prompt in a loop. 3. Profile with memray using PYTHONMALLOC=malloc. 4. Observe leaked allocations from response and Pydantic objects.

Fixing Code Block

Edge Case Audit

Closing the response too early may break streaming calls that rely on lazy reading; ensure this patch is only applied to non-streaming paths or after the response is fully consumed. The patch monkeypatches internals and may need adjustment across LangChain versions; test thoroughly before deploying. Rollback is straightforward by removing the patch, but upgrading LangChain or Pydantic may resolve the issue upstream and should be preferred.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state