2024-06-03 14:23:37 +00:00
|
|
|
import base64
|
|
|
|
from os.path import exists
|
2023-12-11 21:53:30 +00:00
|
|
|
from typing import Any, Dict, List, Optional
|
2024-06-03 14:23:37 +00:00
|
|
|
from urllib.parse import urlparse
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
import requests
|
|
|
|
from langchain_core.embeddings import Embeddings
|
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.
-->
2023-12-22 19:42:29 +00:00
|
|
|
from langchain_core.pydantic_v1 import BaseModel, SecretStr, root_validator
|
|
|
|
from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
|
2023-12-11 21:53:30 +00:00
|
|
|
|
|
|
|
JINA_API_URL: str = "https://api.jina.ai/v1/embeddings"
|
|
|
|
|
|
|
|
|
2024-06-03 14:23:37 +00:00
|
|
|
def is_local(url: str) -> bool:
|
|
|
|
url_parsed = urlparse(url)
|
|
|
|
if url_parsed.scheme in ("file", ""): # Possibly a local file
|
|
|
|
return exists(url_parsed.path)
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def get_bytes_str(file_path: str) -> str:
|
|
|
|
with open(file_path, "rb") as image_file:
|
|
|
|
return base64.b64encode(image_file.read()).decode("utf-8")
|
|
|
|
|
|
|
|
|
2023-12-11 21:53:30 +00:00
|
|
|
class JinaEmbeddings(BaseModel, Embeddings):
|
|
|
|
"""Jina embedding models."""
|
|
|
|
|
|
|
|
session: Any #: :meta private:
|
|
|
|
model_name: str = "jina-embeddings-v2-base-en"
|
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.
-->
2023-12-22 19:42:29 +00:00
|
|
|
jina_api_key: Optional[SecretStr] = None
|
2023-12-11 21:53:30 +00:00
|
|
|
|
community[patch]: Update root_validators embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub, Toolkits: Connery, ChatModels: PAI_EAS, (#22828)
This PR updates root validators for:
* Embeddings: llamacpp, jina, dashscope, mosaicml, huggingface_hub
* Toolkits: Connery
* ChatModels: PAI_EAS
Following this issue:
https://github.com/langchain-ai/langchain/issues/22819
2024-06-12 17:59:05 +00:00
|
|
|
@root_validator(pre=True)
|
2023-12-11 21:53:30 +00:00
|
|
|
def validate_environment(cls, values: Dict) -> Dict:
|
|
|
|
"""Validate that auth token exists in environment."""
|
|
|
|
try:
|
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.
-->
2023-12-22 19:42:29 +00:00
|
|
|
jina_api_key = convert_to_secret_str(
|
|
|
|
get_from_dict_or_env(values, "jina_api_key", "JINA_API_KEY")
|
|
|
|
)
|
2023-12-11 21:53:30 +00:00
|
|
|
except ValueError as original_exc:
|
|
|
|
try:
|
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.
-->
2023-12-22 19:42:29 +00:00
|
|
|
jina_api_key = convert_to_secret_str(
|
|
|
|
get_from_dict_or_env(values, "jina_auth_token", "JINA_AUTH_TOKEN")
|
2023-12-11 21:53:30 +00:00
|
|
|
)
|
|
|
|
except ValueError:
|
|
|
|
raise original_exc
|
|
|
|
session = requests.Session()
|
|
|
|
session.headers.update(
|
|
|
|
{
|
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.
-->
2023-12-22 19:42:29 +00:00
|
|
|
"Authorization": f"Bearer {jina_api_key.get_secret_value()}",
|
2023-12-11 21:53:30 +00:00
|
|
|
"Accept-Encoding": "identity",
|
|
|
|
"Content-type": "application/json",
|
|
|
|
}
|
|
|
|
)
|
|
|
|
values["session"] = session
|
|
|
|
return values
|
|
|
|
|
2024-06-03 14:23:37 +00:00
|
|
|
def _embed(self, input: Any) -> List[List[float]]:
|
2023-12-11 21:53:30 +00:00
|
|
|
# Call Jina AI Embedding API
|
|
|
|
resp = self.session.post( # type: ignore
|
2024-06-03 14:23:37 +00:00
|
|
|
JINA_API_URL, json={"input": input, "model": self.model_name}
|
2023-12-11 21:53:30 +00:00
|
|
|
).json()
|
|
|
|
if "data" not in resp:
|
|
|
|
raise RuntimeError(resp["detail"])
|
|
|
|
|
|
|
|
embeddings = resp["data"]
|
|
|
|
|
|
|
|
# Sort resulting embeddings by index
|
|
|
|
sorted_embeddings = sorted(embeddings, key=lambda e: e["index"]) # type: ignore
|
|
|
|
|
|
|
|
# Return just the embeddings
|
|
|
|
return [result["embedding"] for result in sorted_embeddings]
|
|
|
|
|
|
|
|
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
|
|
"""Call out to Jina's embedding endpoint.
|
|
|
|
Args:
|
|
|
|
texts: The list of texts to embed.
|
|
|
|
Returns:
|
|
|
|
List of embeddings, one for each text.
|
|
|
|
"""
|
|
|
|
return self._embed(texts)
|
|
|
|
|
|
|
|
def embed_query(self, text: str) -> List[float]:
|
|
|
|
"""Call out to Jina's embedding endpoint.
|
|
|
|
Args:
|
|
|
|
text: The text to embed.
|
|
|
|
Returns:
|
|
|
|
Embeddings for the text.
|
|
|
|
"""
|
|
|
|
return self._embed([text])[0]
|
2024-06-03 14:23:37 +00:00
|
|
|
|
|
|
|
def embed_images(self, uris: List[str]) -> List[List[float]]:
|
|
|
|
"""Call out to Jina's image embedding endpoint.
|
|
|
|
Args:
|
|
|
|
uris: The list of uris to embed.
|
|
|
|
Returns:
|
|
|
|
List of embeddings, one for each text.
|
|
|
|
"""
|
|
|
|
input = []
|
|
|
|
for uri in uris:
|
|
|
|
if is_local(uri):
|
|
|
|
input.append({"bytes": get_bytes_str(uri)})
|
|
|
|
else:
|
|
|
|
input.append({"url": uri})
|
|
|
|
return self._embed(input)
|