Refactor: use SecretStr for jina embeddings (#15068)

<!-- Thank you for contributing to LangChain!

Please title your PR "<package>: <description>", where <package> is
whichever of langchain, community, core, experimental, etc. is being
modified.

Replace this entire comment with:
  - **Description:** a description of the change, 
  - **Issue:** the issue # it fixes if applicable,
  - **Dependencies:** any dependencies required for this change,
- **Twitter handle:** we announce bigger features on Twitter. If your PR
gets announced, and you'd like a mention, we'll gladly shout you out!

Please make sure your PR is passing linting and testing before
submitting. Run `make format`, `make lint` and `make test` from the root
of the package you've modified to check this locally.

See contribution guidelines for more information on how to write/run
tests, lint, etc: https://python.langchain.com/docs/contributing/

If you're adding a new integration, please include:
1. a test for the integration, preferably unit tests that do not rely on
network access,
2. an example notebook showing its use. It lives in
`docs/docs/integrations` directory.

If no one reviews your PR within a few days, please @-mention one of
@baskaryan, @eyurtsev, @hwchase17.
 -->
This commit is contained in:
chyroc 2023-12-23 03:42:29 +08:00 committed by GitHub
parent f9230e005b
commit aa19ca9723
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,8 +2,8 @@ from typing import Any, Dict, List, Optional
import requests import requests
from langchain_core.embeddings import Embeddings from langchain_core.embeddings import Embeddings
from langchain_core.pydantic_v1 import BaseModel, root_validator from langchain_core.pydantic_v1 import BaseModel, SecretStr, root_validator
from langchain_core.utils import get_from_dict_or_env from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
JINA_API_URL: str = "https://api.jina.ai/v1/embeddings" JINA_API_URL: str = "https://api.jina.ai/v1/embeddings"
@ -13,24 +13,26 @@ class JinaEmbeddings(BaseModel, Embeddings):
session: Any #: :meta private: session: Any #: :meta private:
model_name: str = "jina-embeddings-v2-base-en" model_name: str = "jina-embeddings-v2-base-en"
jina_api_key: Optional[str] = None jina_api_key: Optional[SecretStr] = None
@root_validator() @root_validator()
def validate_environment(cls, values: Dict) -> Dict: def validate_environment(cls, values: Dict) -> Dict:
"""Validate that auth token exists in environment.""" """Validate that auth token exists in environment."""
try: try:
jina_api_key = get_from_dict_or_env(values, "jina_api_key", "JINA_API_KEY") jina_api_key = convert_to_secret_str(
get_from_dict_or_env(values, "jina_api_key", "JINA_API_KEY")
)
except ValueError as original_exc: except ValueError as original_exc:
try: try:
jina_api_key = get_from_dict_or_env( jina_api_key = convert_to_secret_str(
values, "jina_auth_token", "JINA_AUTH_TOKEN" get_from_dict_or_env(values, "jina_auth_token", "JINA_AUTH_TOKEN")
) )
except ValueError: except ValueError:
raise original_exc raise original_exc
session = requests.Session() session = requests.Session()
session.headers.update( session.headers.update(
{ {
"Authorization": f"Bearer {jina_api_key}", "Authorization": f"Bearer {jina_api_key.get_secret_value()}",
"Accept-Encoding": "identity", "Accept-Encoding": "identity",
"Content-type": "application/json", "Content-type": "application/json",
} }