Skip to content

fix: mask API keys in ChatOpenAI __repr__ to prevent secret leakage #535

@MrEchoFi

Description

Checked other resources

  • This is a bug, not a usage question.
  • I added a clear and descriptive title that summarizes this issue.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain Community rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain Community.
  • I read what a minimal reproducible example is (https://stackoverflow.com/help/minimal-reproducible-example).
  • I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.

Reproduction:

from langchain_community.chat_models import ChatOpenAI

llm = ChatOpenAI(api_key="FAKEKEY123", model="gpt-4o")
print(llm)

Before(current behave) :

ChatOpenAI(model_name='gpt-4o', openai_api_key='FAKEKEY123', openai_proxy='')

with this PR change:

ChatOpenAI(model_name='gpt-4o', openai_api_key='***', openai_proxy='')

Description

This PR addresses a security concern where API keys are exposed in plaintext in the repr of ChatOpenAI (and potentially other clients). When developers log or print these objects, the API key is revealed in logs or stack traces, which can lead to credential leakage in production environments.

The fix overrides the repr method to mask the API key with *** instead of displaying the full secret. This ensures that sensitive information is not accidentally exposed while still providing useful context (e.g., model name, proxy settings).

Impact:

  • Prevents accidental leakage of API keys in logs, monitoring systems, and error traces.

  • Aligns LangChain with best practices for handling secrets.

  • Improves security posture for developers using LangChain in production environments.

Notes:
This change is backward‑compatible and does not affect functionality.

Other clients that expose secrets in repr may benefit from similar masking in future PRs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions