Fix anthropic secret key when passed in via init (#11185)

Fixes anthropic secret key when passed via init

https://github.com/langchain-ai/langchain/issues/11182
This commit is contained in:
Eugene Yurtsev 2023-09-28 14:21:41 -04:00 committed by GitHub
parent f201d80d40
commit fd96878c4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 2 deletions

View File

@ -1,6 +1,16 @@
import re import re
import warnings import warnings
from typing import Any, AsyncIterator, Callable, Dict, Iterator, List, Mapping, Optional from typing import (
Any,
AsyncIterator,
Callable,
Dict,
Iterator,
List,
Mapping,
Optional,
Union,
)
from langchain.callbacks.manager import ( from langchain.callbacks.manager import (
AsyncCallbackManagerForLLMRun, AsyncCallbackManagerForLLMRun,
@ -19,6 +29,13 @@ from langchain.utils import (
from langchain.utils.utils import build_extra_kwargs from langchain.utils.utils import build_extra_kwargs
def _to_secret(value: Union[SecretStr, str]) -> SecretStr:
"""Convert a string to a SecretStr if needed."""
if isinstance(value, SecretStr):
return value
return SecretStr(value)
class _AnthropicCommon(BaseLanguageModel): class _AnthropicCommon(BaseLanguageModel):
client: Any = None #: :meta private: client: Any = None #: :meta private:
async_client: Any = None #: :meta private: async_client: Any = None #: :meta private:
@ -64,7 +81,7 @@ class _AnthropicCommon(BaseLanguageModel):
@root_validator() @root_validator()
def validate_environment(cls, values: Dict) -> Dict: def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment.""" """Validate that api key and python package exists in environment."""
values["anthropic_api_key"] = SecretStr( values["anthropic_api_key"] = _to_secret(
get_from_dict_or_env(values, "anthropic_api_key", "ANTHROPIC_API_KEY") get_from_dict_or_env(values, "anthropic_api_key", "ANTHROPIC_API_KEY")
) )
# Get custom api url from environment. # Get custom api url from environment.

View File

@ -22,6 +22,13 @@ def test_anthropic_call() -> None:
assert isinstance(response.content, str) assert isinstance(response.content, str)
def test_anthropic_initialization() -> None:
"""Test anthropic initialization."""
# Verify that chat anthropic can be initialized using a secret key provided
# as a parameter rather than an environment variable.
ChatAnthropic(model="test", anthropic_api_key="test")
def test_anthropic_generate() -> None: def test_anthropic_generate() -> None:
"""Test generate method of anthropic.""" """Test generate method of anthropic."""
chat = ChatAnthropic(model="test") chat = ChatAnthropic(model="test")