-
Notifications
You must be signed in to change notification settings - Fork 15.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mask API key for AI21 LLM #12418
Mask API key for AI21 LLM #12418
Changes from all commits
954a9a1
e0d7faa
9a1bba1
02b62af
6e2494e
88a2f38
6a997d1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,11 @@ | ||
from typing import Any, Dict, List, Optional | ||
from typing import Any, Dict, List, Optional, cast | ||
|
||
import requests | ||
|
||
from langchain.callbacks.manager import CallbackManagerForLLMRun | ||
from langchain.llms.base import LLM | ||
from langchain.pydantic_v1 import BaseModel, Extra, root_validator | ||
from langchain.utils import get_from_dict_or_env | ||
from langchain.pydantic_v1 import BaseModel, Extra, SecretStr, root_validator | ||
from langchain.utils import convert_to_secret_str, get_from_dict_or_env | ||
|
||
|
||
class AI21PenaltyData(BaseModel): | ||
|
@@ -23,13 +23,13 @@ class AI21(LLM): | |
"""AI21 large language models. | ||
|
||
To use, you should have the environment variable ``AI21_API_KEY`` | ||
set with your API key. | ||
set with your API key or pass it as a named parameter to the constructor. | ||
|
||
Example: | ||
.. code-block:: python | ||
|
||
from langchain.llms import AI21 | ||
ai21 = AI21(model="j2-jumbo-instruct") | ||
ai21 = AI21(ai21_api_key="my-api-key", model="j2-jumbo-instruct") | ||
""" | ||
|
||
model: str = "j2-jumbo-instruct" | ||
|
@@ -62,7 +62,7 @@ class AI21(LLM): | |
logitBias: Optional[Dict[str, float]] = None | ||
"""Adjust the probability of specific tokens being generated.""" | ||
|
||
ai21_api_key: Optional[str] = None | ||
ai21_api_key: Optional[SecretStr] = None | ||
|
||
stop: Optional[List[str]] = None | ||
|
||
|
@@ -77,7 +77,9 @@ class Config: | |
@root_validator() | ||
def validate_environment(cls, values: Dict) -> Dict: | ||
"""Validate that api key exists in environment.""" | ||
ai21_api_key = get_from_dict_or_env(values, "ai21_api_key", "AI21_API_KEY") | ||
ai21_api_key = convert_to_secret_str( | ||
get_from_dict_or_env(values, "ai21_api_key", "AI21_API_KEY") | ||
) | ||
values["ai21_api_key"] = ai21_api_key | ||
return values | ||
|
||
|
@@ -141,9 +143,10 @@ def _call( | |
else: | ||
base_url = "https://api.ai21.com/studio/v1" | ||
params = {**self._default_params, **kwargs} | ||
self.ai21_api_key = cast(SecretStr, self.ai21_api_key) | ||
response = requests.post( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Cast probably won't be needed if the attribute is no longer an Optional There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, used the cast to avoid type checking, I was encountering a mypy error without it. |
||
url=f"{base_url}/{self.model}/complete", | ||
headers={"Authorization": f"Bearer {self.ai21_api_key}"}, | ||
headers={"Authorization": f"Bearer {self.ai21_api_key.get_secret_value()}"}, | ||
json={"prompt": prompt, "stopSequences": stop, **params}, | ||
) | ||
if response.status_code != 200: | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
"""Test AI21 llm""" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Excellent! |
||
from typing import cast | ||
|
||
from pytest import CaptureFixture, MonkeyPatch | ||
|
||
from langchain.llms.ai21 import AI21 | ||
from langchain.pydantic_v1 import SecretStr | ||
|
||
|
||
def test_api_key_is_secret_string() -> None: | ||
llm = AI21(ai21_api_key="secret-api-key") | ||
assert isinstance(llm.ai21_api_key, SecretStr) | ||
|
||
|
||
def test_api_key_masked_when_passed_from_env( | ||
monkeypatch: MonkeyPatch, capsys: CaptureFixture | ||
) -> None: | ||
"""Test initialization with an API key provided via an env variable""" | ||
monkeypatch.setenv("AI21_API_KEY", "secret-api-key") | ||
llm = AI21() | ||
print(llm.ai21_api_key, end="") | ||
captured = capsys.readouterr() | ||
|
||
assert captured.out == "**********" | ||
|
||
|
||
def test_api_key_masked_when_passed_via_constructor( | ||
capsys: CaptureFixture, | ||
) -> None: | ||
"""Test initialization with an API key provided via the initializer""" | ||
llm = AI21(ai21_api_key="secret-api-key") | ||
print(llm.ai21_api_key, end="") | ||
captured = capsys.readouterr() | ||
|
||
assert captured.out == "**********" | ||
|
||
|
||
def test_uses_actual_secret_value_from_secretstr() -> None: | ||
"""Test that actual secret is retrieved using `.get_secret_value()`.""" | ||
llm = AI21(ai21_api_key="secret-api-key") | ||
assert cast(SecretStr, llm.ai21_api_key).get_secret_value() == "secret-api-key" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is it possible for the ai21_api_key to be None? It looks like after the root validator runs this always get set to a value?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, ai21_api_key can never be None.