id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
074ec12427ee-4 | example_prompt=example_prompt,
)
final_prompt = ChatPromptTemplate.from_messages(
[
('system', 'You are a helpful AI Assistant'),
few_shot_prompt,
('human', '{input}'),
]
)
final_p... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
074ec12427ee-5 | example_prompt=(
HumanMessagePromptTemplate.from_template("{input}")
+ AIMessagePromptTemplate.from_template("{output}")
),
)
# Define the overall prompt.
final_prompt = (
SystemMessagePromptTemplate.from_templat... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
074ec12427ee-6 | """
# Get the examples to use.
examples = self._get_examples(**kwargs)
examples = [
{k: e[k] for k in self.example_prompt.input_variables} for e in examples
]
# Format the examples.
messages = [
message
for example in examples
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
c78460ade956-0 | Source code for langchain.prompts.example_selector.base
"""Interface for selecting examples to include in prompts."""
from abc import ABC, abstractmethod
from typing import Any, Dict, List
[docs]class BaseExampleSelector(ABC):
"""Interface for selecting examples to include in prompts."""
[docs] @abstractmethod
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/base.html |
96400aa8c408-0 | Source code for langchain.prompts.example_selector.semantic_similarity
"""Example selector that selects examples based on SemanticSimilarity."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
fr... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
96400aa8c408-1 | return ids[0]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use based on semantic similarity."""
# Get the docs with the highest similarity.
if self.input_keys:
input_variables = {key: input_variables[key] for key in s... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
96400aa8c408-2 | instead of all variables.
vectorstore_cls_kwargs: optional kwargs containing url for vector store
Returns:
The ExampleSelector instantiated, backed by a vector store.
"""
if input_keys:
string_examples = [
" ".join(sorted_values({k: eg[k] for k... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
96400aa8c408-3 | examples = [dict(e.metadata) for e in example_docs]
# If example keys are provided, filter examples to those keys.
if self.example_keys:
examples = [{k: eg[k] for k in self.example_keys} for eg in examples]
return examples
[docs] @classmethod
def from_examples(
cls,
... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
96400aa8c408-4 | )
return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys) | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
3c5b48c193e1-0 | Source code for langchain.prompts.example_selector.ngram_overlap
"""Select and order examples based on ngram overlap score (sentence_bleu score).
https://www.nltk.org/_modules/nltk/translate/bleu_score.html
https://aclanthology.org/P02-1040.pdf
"""
from typing import Dict, List
import numpy as np
from pydantic import B... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
3c5b48c193e1-1 | """
examples: List[dict]
"""A list of the examples that the prompt template expects."""
example_prompt: PromptTemplate
"""Prompt template used to format the examples."""
threshold: float = -1.0
"""Threshold at which algorithm stops. Set to -1.0 by default.
For negative threshold:
select_... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
3c5b48c193e1-2 | examples = []
k = len(self.examples)
score = [0.0] * k
first_prompt_template_key = self.example_prompt.input_variables[0]
for i in range(k):
score[i] = ngram_overlap_score(
inputs, [self.examples[i][first_prompt_template_key]]
)
while True:... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/ngram_overlap.html |
f60b172941fc-0 | Source code for langchain.prompts.example_selector.length_based
"""Select examples based on length."""
import re
from typing import Callable, Dict, List
from pydantic import BaseModel, validator
from langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.prompts.prompt import PromptTemplate
d... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
f60b172941fc-1 | get_text_length = values["get_text_length"]
string_examples = [example_prompt.format(**eg) for eg in values["examples"]]
return [get_text_length(eg) for eg in string_examples]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use base... | https://api.python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
564c5c651552-0 | Source code for langchain.embeddings.jina
import os
from typing import Any, Dict, List, Optional
import requests
from pydantic import BaseModel, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class JinaEmbeddings(BaseModel, Embeddings):
"""Jina... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html |
564c5c651552-1 | headers={"Authorization": jina_auth_token},
)
if resp.status_code == 401:
raise ValueError(
"The given Jina auth token is invalid. "
"Please check your Jina auth token."
)
elif resp.status_code == 404:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html |
564c5c651552-2 | Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
from docarray import Document, DocumentArray
embedding = self._post(docs=DocumentArray([Document(text=text)])).embeddings[0]
return list(map(float, embedding)) | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/jina.html |
9dde1c820add-0 | Source code for langchain.embeddings.elasticsearch
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
from langchain.utils import get_from_env
if TYPE_CHECKING:
from elasticsearch import Elasticsearch
from elasticsearch.client import MlClient
from langchain.embeddings.base impor... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html |
9dde1c820add-1 | es_user: Optional[str] = None,
es_password: Optional[str] = None,
input_field: str = "text_field",
) -> ElasticsearchEmbeddings:
"""Instantiate embeddings from Elasticsearch credentials.
Args:
model_id (str): The model_id of the model deployed in the Elasticsearch
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html |
9dde1c820add-2 | from elasticsearch.client import MlClient
except ImportError:
raise ImportError(
"elasticsearch package not found, please install with 'pip install "
"elasticsearch'"
)
es_cloud_id = es_cloud_id or get_from_env("es_cloud_id", "ES_CLOUD_ID")
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html |
9dde1c820add-3 | Example:
.. code-block:: python
from elasticsearch import Elasticsearch
from langchain.embeddings import ElasticsearchEmbeddings
# Define the model ID and input field name (if different from default)
model_id = "your_model_id"
#... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html |
9dde1c820add-4 | list.
"""
response = self.client.infer_trained_model(
model_id=self.model_id, docs=[{self.input_field: text} for text in texts]
)
embeddings = [doc["predicted_value"] for doc in response["inference_results"]]
return embeddings
[docs] def embed_documents(self, texts... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/elasticsearch.html |
d4dcacce1f41-0 | Source code for langchain.embeddings.edenai
from typing import Dict, List, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.embeddings.base import Embeddings
from langchain.requests import Requests
from langchain.utils import get_from_dict_or_env
[docs]class EdenAiEmbeddings(BaseMode... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html |
d4dcacce1f41-1 | if response.status_code >= 500:
raise Exception(f"EdenAI Server: Error {response.status_code}")
elif response.status_code >= 400:
raise ValueError(f"EdenAI received an invalid payload: {response.text}")
elif response.status_code != 200:
raise Exception(
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/edenai.html |
4a9cb5d3cb93-0 | Source code for langchain.embeddings.huggingface_hub
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
DEFAULT_REPO_ID = "sentence-transformers/all-mpnet-base-v2"
VALID_TASK... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
4a9cb5d3cb93-1 | """Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
try:
from huggingface_hub.inference_api import InferenceApi
repo_id = values... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
4a9cb5d3cb93-2 | responses = self.client(inputs=texts, params=_model_kwargs)
return responses
[docs] def embed_query(self, text: str) -> List[float]:
"""Call out to HuggingFaceHub's embedding endpoint for embedding query text.
Args:
text: The text to embed.
Returns:
Embeddings ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
21b1f8475b10-0 | Source code for langchain.embeddings.octoai_embeddings
from typing import Any, Dict, List, Mapping, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
DEFAULT_EMBED_INSTRUCTION = "Represent this input: "... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html |
21b1f8475b10-1 | )
values["endpoint_url"] = get_from_dict_or_env(
values, "endpoint_url", "ENDPOINT_URL"
)
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Return the identifying parameters."""
return {
"endpoint_url": self.endpoint_ur... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html |
21b1f8475b10-2 | text = text.replace("\n", " ")
return self._compute_embeddings([text], self.embed_instruction)[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/octoai_embeddings.html |
cd4654156ecd-0 | Source code for langchain.embeddings.base
from abc import ABC, abstractmethod
from typing import List
[docs]class Embeddings(ABC):
"""Interface for embedding models."""
[docs] @abstractmethod
def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Embed search docs."""
[docs] @abstrac... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/base.html |
53fb652e994e-0 | Source code for langchain.embeddings.xinference
"""Wrapper around Xinference embedding models."""
from typing import Any, List, Optional
from langchain.embeddings.base import Embeddings
[docs]class XinferenceEmbeddings(Embeddings):
"""Wrapper around xinference embedding models.
To use, you should have the xinfe... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html |
53fb652e994e-1 | server_url: Optional[str]
"""URL of the xinference server"""
model_uid: Optional[str]
"""UID of the launched model"""
[docs] def __init__(
self, server_url: Optional[str] = None, model_uid: Optional[str] = None
):
try:
from xinference.client import RESTfulClient
ex... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html |
53fb652e994e-2 | embedding_res = model.create_embedding(text)
embedding = embedding_res["data"][0]["embedding"]
return list(map(float, embedding)) | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/xinference.html |
272e4a93d182-0 | Source code for langchain.embeddings.awa
from typing import Any, Dict, List
from pydantic import BaseModel, root_validator
from langchain.embeddings.base import Embeddings
[docs]class AwaEmbeddings(BaseModel, Embeddings):
client: Any #: :meta private:
model: str = "all-mpnet-base-v2"
@root_validator()
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/awa.html |
272e4a93d182-1 | Returns:
Embeddings for the text.
"""
return self.client.Embedding(text) | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/awa.html |
ac0ceeb93219-0 | Source code for langchain.embeddings.modelscope_hub
from typing import Any, List, Optional
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
[docs]class ModelScopeEmbeddings(BaseModel, Embeddings):
"""ModelScopeHub embedding models.
To use, you should have the ``modelscope``... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html |
ac0ceeb93219-1 | Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
texts = list(map(lambda x: x.replace("\n", " "), texts))
inputs = {"source_sentence": texts}
embeddings = self.embed(input=inputs)["text_embedding"]
return... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html |
8e3cc427c02e-0 | Source code for langchain.embeddings.fake
import hashlib
from typing import List
import numpy as np
from pydantic import BaseModel
from langchain.embeddings.base import Embeddings
[docs]class FakeEmbeddings(Embeddings, BaseModel):
"""Fake embedding model."""
size: int
"""The size of the embedding vector."""... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html |
8fbe1bc6a299-0 | Source code for langchain.embeddings.google_palm
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
from pydantic import BaseModel, root_validator
from tenacity import (
before_sleep_log,
retry,
retry_if_exception_type,
stop_after_attempt,
wait_e... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/google_palm.html |
8fbe1bc6a299-1 | return _embed_with_retry(*args, **kwargs)
[docs]class GooglePalmEmbeddings(BaseModel, Embeddings):
"""Google's PaLM Embeddings APIs."""
client: Any
google_api_key: Optional[str]
model_name: str = "models/embedding-gecko-001"
"""Model name to use."""
@root_validator()
def validate_environment... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/google_palm.html |
8e2cd2d8ad9c-0 | Source code for langchain.embeddings.clarifai
import logging
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
logger = logging.getLogger(__name__)
[docs]class ClarifaiEmbed... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
8e2cd2d8ad9c-1 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
values["pat"] = get_from_dict_or_env(values, "pat", "CLARIFAI_PAT")
user_id = values.get("user_id")
app_id = values.ge... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
8e2cd2d8ad9c-2 | List of embeddings, one for each text.
"""
try:
from clarifai_grpc.grpc.api import (
resources_pb2,
service_pb2,
)
from clarifai_grpc.grpc.api.status import status_code_pb2
except ImportError:
raise ImportError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
8e2cd2d8ad9c-3 | Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
try:
from clarifai_grpc.grpc.api import (
resources_pb2,
service_pb2,
)
from clarifai_grpc.grpc.api.status import status_code_pb2
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/clarifai.html |
333bd69d1b98-0 | Source code for langchain.embeddings.localai
from __future__ import annotations
import logging
import warnings
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from pydantic import BaseModel, Extra, Field, root_validator
from tenac... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
333bd69d1b98-1 | import openai
min_seconds = 4
max_seconds = 10
# Wait 2^x * 1 second between each retry starting with
# 4 seconds, then up to 10 seconds, then 10 seconds afterwards
async_retrying = AsyncRetrying(
reraise=True,
stop=stop_after_attempt(embeddings.max_retries),
wait=wait_expone... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
333bd69d1b98-2 | retry_decorator = _create_retry_decorator(embeddings)
@retry_decorator
def _embed_with_retry(**kwargs: Any) -> Any:
response = embeddings.client.create(**kwargs)
return _check_response(response)
return _embed_with_retry(**kwargs)
[docs]async def async_embed_with_retry(embeddings: LocalAIEmbe... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
333bd69d1b98-3 | """The maximum number of tokens to embed at once."""
openai_api_key: Optional[str] = None
openai_organization: Optional[str] = None
allowed_special: Union[Literal["all"], Set[str]] = set()
disallowed_special: Union[Literal["all"], Set[str], Sequence[str]] = "all"
chunk_size: int = 1000
"""Maximu... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
333bd69d1b98-4 | Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
invalid_model_kwargs = all_required_field_names.intersection(extra.keys())
if invalid_model_kwargs:
raise ValueError(
f"Parameters {invalid_m... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
333bd69d1b98-5 | raise ImportError(
"Could not import openai python package. "
"Please install it with `pip install openai`."
)
return values
@property
def _invocation_params(self) -> Dict:
openai_args = {
"model": self.model,
"request_timeout":... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
333bd69d1b98-6 | # handle large input text
if self.model.endswith("001"):
# See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500
# replace newlines, which can negatively affect performance.
text = text.replace("\n", " ")
return (
await async_embe... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
333bd69d1b98-7 | embeddings.append(response)
return embeddings
[docs] def embed_query(self, text: str) -> List[float]:
"""Call out to LocalAI's embedding endpoint for embedding query text.
Args:
text: The text to embed.
Returns:
Embedding for the text.
"""
embed... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/localai.html |
df08c3d633f1-0 | Source code for langchain.embeddings.dashscope
from __future__ import annotations
import logging
from typing import (
Any,
Callable,
Dict,
List,
Optional,
)
from pydantic import BaseModel, Extra, root_validator
from requests.exceptions import HTTPError
from tenacity import (
before_sleep_log,
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
df08c3d633f1-1 | elif resp.status_code in [400, 401]:
raise ValueError(
f"status_code: {resp.status_code} \n "
f"code: {resp.code} \n message: {resp.message}"
)
else:
raise HTTPError(
f"HTTP error occurred: status_code: {resp.status_code} \n "
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
df08c3d633f1-2 | """Maximum number of retries to make when generating."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
import dashscope
"""Validate that api key and python package exists... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
df08c3d633f1-3 | Returns:
Embedding for the text.
"""
embedding = embed_with_retry(
self, input=text, text_type="query", model=self.model
)[0]["embedding"]
return embedding | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html |
8f0aa746719d-0 | Source code for langchain.embeddings.huggingface
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, Field
from langchain.embeddings.base import Embeddings
DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
DEFAULT_INSTRUCT_MODEL = "hkunlp/instructor-large"
DEFAULT_BGE_MODEL ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
8f0aa746719d-1 | model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Key word arguments to pass to the model."""
encode_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Key word arguments to pass when calling the `encode` method of the model."""
def __init__(self, **kwargs: Any):
"""Initialize t... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
8f0aa746719d-2 | embedding = self.client.encode(text, **self.encode_kwargs)
return embedding.tolist()
[docs]class HuggingFaceInstructEmbeddings(BaseModel, Embeddings):
"""Wrapper around sentence_transformers embedding models.
To use, you should have the ``sentence_transformers``
and ``InstructorEmbedding`` python pa... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
8f0aa746719d-3 | from InstructorEmbedding import INSTRUCTOR
self.client = INSTRUCTOR(
self.model_name, cache_folder=self.cache_folder, **self.model_kwargs
)
except ImportError as e:
raise ValueError("Dependencies for InstructorEmbedding not found.") from e
class Config:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
8f0aa746719d-4 | encode_kwargs = {'normalize_embeddings': True}
hf = HuggingFaceBgeEmbeddings(
model_name=model_name,
model_kwargs=model_kwargs,
encode_kwargs=encode_kwargs
)
"""
client: Any #: :meta private:
model_name: str = DEFAULT_BGE_MODEL
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
8f0aa746719d-5 | """Compute doc embeddings using a HuggingFace transformer model.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
texts = [t.replace("\n", " ") for t in texts]
embeddings = self.client.encode(texts, **self.encode... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
e53ce664eea6-0 | Source code for langchain.embeddings.self_hosted
from typing import Any, Callable, List
from pydantic import Extra
from langchain.embeddings.base import Embeddings
from langchain.llms import SelfHostedPipeline
def _embed_documents(pipeline: Any, *args: Any, **kwargs: Any) -> List[List[float]]:
"""Inference function... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
e53ce664eea6-1 | model_load_fn=get_pipeline,
hardware=gpu
model_reqs=["./", "torch", "transformers"],
)
Example passing in a pipeline path:
.. code-block:: python
from langchain.embeddings import SelfHostedHFEmbeddings
import runhouse as rh
from... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
e53ce664eea6-2 | [docs] def embed_query(self, text: str) -> List[float]:
"""Compute query embeddings using a HuggingFace transformer model.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
text = text.replace("\n", " ")
embeddings = self.clie... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
f4468a3ca135-0 | Source code for langchain.embeddings.mosaicml
from typing import Any, Dict, List, Mapping, Optional, Tuple
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class MosaicMLInstructorEmbeddings(Base... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
f4468a3ca135-1 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
mosaicml_api_token = get_from_dict_or_env(
values, "mosaicml_api_token", "MOSAICML_API_TOKEN"
)
values["mo... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
f4468a3ca135-2 | # The inference API has changed a couple of times, so we add some handling
# to be robust to multiple response formats.
if isinstance(parsed_response, dict):
if "data" in parsed_response:
output_item = parsed_response["data"]
elif "output" in p... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
f4468a3ca135-3 | Returns:
List of embeddings, one for each text.
"""
instruction_pairs = [(self.embed_instruction, text) for text in texts]
embeddings = self._embed(instruction_pairs)
return embeddings
[docs] def embed_query(self, text: str) -> List[float]:
"""Embed a query using a... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
6ccab17b937a-0 | Source code for langchain.embeddings.cohere
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class CohereEmbeddings(BaseModel, Embeddings):
"""Cohere embedding mo... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html |
6ccab17b937a-1 | )
try:
import cohere
values["client"] = cohere.Client(cohere_api_key)
values["async_client"] = cohere.AsyncClient(cohere_api_key)
except ImportError:
raise ValueError(
"Could not import cohere python package. "
"Please insta... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html |
6ccab17b937a-2 | [docs] async def aembed_query(self, text: str) -> List[float]:
"""Async call out to Cohere's embedding endpoint.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
embeddings = await self.aembed_documents([text])
return embeddi... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html |
d4cb9b380e73-0 | Source code for langchain.embeddings.vertexai
from typing import Dict, List
from pydantic import root_validator
from langchain.embeddings.base import Embeddings
from langchain.llms.vertexai import _VertexAICommon
from langchain.utilities.vertexai import raise_vertex_import_error
[docs]class VertexAIEmbeddings(_VertexAI... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/vertexai.html |
d4cb9b380e73-1 | """Embed a text.
Args:
text: The text to embed.
Returns:
Embedding for the text.
"""
embeddings = self.client.get_embeddings([text])
return embeddings[0].values | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/vertexai.html |
326180954b71-0 | Source code for langchain.embeddings.mlflow_gateway
from __future__ import annotations
from typing import Any, Iterator, List, Optional
from pydantic import BaseModel
from langchain.embeddings.base import Embeddings
def _chunk(texts: List[str], size: int) -> Iterator[List[str]]:
for i in range(0, len(texts), size):... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mlflow_gateway.html |
326180954b71-1 | if self.gateway_uri:
mlflow.gateway.set_gateway_uri(self.gateway_uri)
def _query(self, texts: List[str]) -> List[List[float]]:
try:
import mlflow.gateway
except ImportError as e:
raise ImportError(
"Could not import `mlflow.gateway` module. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mlflow_gateway.html |
d78ef15adf74-0 | Source code for langchain.embeddings.minimax
from __future__ import annotations
import logging
from typing import Any, Callable, Dict, List, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from tenacity import (
before_sleep_log,
retry,
stop_after_attempt,
wait_exponential... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html |
d78ef15adf74-1 | the constructor.
Example:
.. code-block:: python
from langchain.embeddings import MiniMaxEmbeddings
embeddings = MiniMaxEmbeddings()
query_text = "This is a test query."
query_result = embeddings.embed_query(query_text)
document_text = "This is a t... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html |
d78ef15adf74-2 | self,
texts: List[str],
embed_type: str,
) -> List[List[float]]:
payload = {
"model": self.model,
"type": embed_type,
"texts": texts,
}
# HTTP headers for authorization
headers = {
"Authorization": f"Bearer {self.minimax... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html |
1984fde0fcea-0 | Source code for langchain.embeddings.self_hosted_hugging_face
import importlib
import logging
from typing import Any, Callable, List, Optional
from langchain.embeddings.self_hosted import SelfHostedEmbeddings
DEFAULT_MODEL_NAME = "sentence-transformers/all-mpnet-base-v2"
DEFAULT_INSTRUCT_MODEL = "hkunlp/instructor-larg... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
1984fde0fcea-1 | logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer associated with CUDA device id.",
cuda_device_coun... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
1984fde0fcea-2 | """Function to load the model remotely on the server."""
load_fn_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model load function."""
inference_fn: Callable = _embed_documents
"""Inference function to extract the embeddings."""
def __init__(self, **kwargs: Any):
"""Init... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
1984fde0fcea-3 | """
model_id: str = DEFAULT_INSTRUCT_MODEL
"""Model name to use."""
embed_instruction: str = DEFAULT_EMBED_INSTRUCTION
"""Instruction to use for embedding documents."""
query_instruction: str = DEFAULT_QUERY_INSTRUCTION
"""Instruction to use for embedding query."""
model_reqs: List[str] = ["... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
1984fde0fcea-4 | Returns:
Embeddings for the text.
"""
instruction_pair = [self.query_instruction, text]
embedding = self.client(self.pipeline_ref, [instruction_pair])[0]
return embedding.tolist() | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
c141d7590258-0 | Source code for langchain.embeddings.embaas
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from typing_extensions import NotRequired, TypedDict
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
#... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html |
c141d7590258-1 | api_url: str = EMBAAS_API_URL
"""The URL for the embaas embeddings API."""
embaas_api_key: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html |
c141d7590258-2 | return embeddings
def _generate_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Generate embeddings using the Embaas API."""
payload = self._generate_payload(texts)
try:
return self._handle_request(payload)
except requests.exceptions.RequestException as e:
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/embaas.html |
6a76f28151bb-0 | Source code for langchain.embeddings.bedrock
import json
import os
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
[docs]class BedrockEmbeddings(BaseModel, Embeddings):
"""Bedrock embedding models.
To authenticat... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
6a76f28151bb-1 | has either access keys or role information specified.
If not specified, the default credential profile or, if on an EC2 instance,
credentials from IMDS will be used.
See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
"""
model_id: str = "amazon.titan-e1t-medium"
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
6a76f28151bb-2 | raise ModuleNotFoundError(
"Could not import boto3 python package. "
"Please install it with `pip install boto3`."
)
except Exception as e:
raise ValueError(
"Could not load credentials to authenticate with AWS client. "
"Pl... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
6a76f28151bb-3 | """
results = []
for text in texts:
response = self._embedding_func(text)
results.append(response)
return results
[docs] def embed_query(self, text: str) -> List[float]:
"""Compute query embeddings using a Bedrock model.
Args:
text: The text... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
826601fbe638-0 | Source code for langchain.embeddings.llamacpp
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, Field, root_validator
from langchain.embeddings.base import Embeddings
[docs]class LlamaCppEmbeddings(BaseModel, Embeddings):
"""llama.cpp embedding models.
To use, you should have t... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
826601fbe638-1 | """Force system to keep model in RAM."""
n_threads: Optional[int] = Field(None, alias="n_threads")
"""Number of threads to use. If None, the number
of threads is automatically determined."""
n_batch: Optional[int] = Field(8, alias="n_batch")
"""Number of tokens to process in parallel.
Should be... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
826601fbe638-2 | "Please install the llama-cpp-python library to "
"use this embedding model: pip install llama-cpp-python"
)
except Exception as e:
raise ValueError(
f"Could not load Llama model from path: {model_path}. "
f"Received error {e}"
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html |
ffa1375114ac-0 | Source code for langchain.embeddings.gpt4all
from typing import Any, Dict, List
from pydantic import BaseModel, root_validator
from langchain.embeddings.base import Embeddings
[docs]class GPT4AllEmbeddings(BaseModel, Embeddings):
"""GPT4All embedding models.
To use, you should have the gpt4all python package in... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gpt4all.html |
ffa1375114ac-1 | Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self.embed_documents([text])[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/gpt4all.html |
b15f82bf337c-0 | Source code for langchain.embeddings.tensorflow_hub
from typing import Any, List
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
DEFAULT_MODEL_URL = "https://tfhub.dev/google/universal-sentence-encoder-multilingual/3"
[docs]class TensorflowHubEmbeddings(BaseModel, Embeddings):
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html |
b15f82bf337c-1 | """Compute doc embeddings using a TensorflowHub embedding model.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
texts = list(map(lambda x: x.replace("\n", " "), texts))
embeddings = self.embed(texts).numpy()
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html |
8230019c2354-0 | Source code for langchain.embeddings.deepinfra
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
DEFAULT_MODEL_ID = "sentence-transformers/clip-ViT-... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.