Skip to content

Commit

Permalink
langchain: support api key argument with OpenAI moderation chain (#29140
Browse files Browse the repository at this point in the history
)

**Description:** Makes it possible to instantiate
`OpenAIModerationChain` with an `openai_api_key` argument only and no
`OPENAI_API_KEY` environment variable defined.

**Issue:** #25176

**Dependencies:** `openai`

---------

Co-authored-by: ccurme <[email protected]>
  • Loading branch information
varjas and ccurme authored Jan 13, 2025
1 parent 335ca3a commit e156b37
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 2 additions & 2 deletions libs/langchain/langchain/chains/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ def validate_environment(cls, values: Dict) -> Any:
if values["openai_pre_1_0"]:
values["client"] = openai.Moderation
else:
values["client"] = openai.OpenAI()
values["async_client"] = openai.AsyncOpenAI()
values["client"] = openai.OpenAI(api_key=openai_api_key)
values["async_client"] = openai.AsyncOpenAI(api_key=openai_api_key)

except ImportError:
raise ImportError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import pytest

from langchain.chains import OpenAIModerationChain
from langchain.chains.openai_functions.openapi import get_openapi_chain

api_spec = {
Expand Down Expand Up @@ -36,3 +37,13 @@ def test_openai_openapi_chain() -> None:
chain = get_openapi_chain(json.dumps(api_spec), llm)
output = chain.invoke({"query": "Fetch the top two posts."})
assert len(output["response"]) == 2


@pytest.mark.requires("openai")
def test_openai_moderation_chain_instantiation() -> None:
"""Test OpenAIModerationChain."""
api_key = "foo"

moderation = OpenAIModerationChain(openai_api_key=api_key)

assert isinstance(moderation, OpenAIModerationChain)

0 comments on commit e156b37

Please sign in to comment.