id stringlengths 14 15 | text stringlengths 35 2.51k | source stringlengths 61 154 |
|---|---|---|
dfe36cf2d9a1-2 | """Wrapper around sentence_transformers embedding models.
To use, you should have the ``sentence_transformers``
and ``InstructorEmbedding`` python packages installed.
Example:
.. code-block:: python
from langchain.embeddings import HuggingFaceInstructEmbeddings
model_name = "... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
dfe36cf2d9a1-3 | )
except ImportError as e:
raise ValueError("Dependencies for InstructorEmbedding not found.") from e
[docs] class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
[docs] def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Comp... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface.html |
029089106e37-0 | Source code for langchain.embeddings.sagemaker_endpoint
"""Wrapper around Sagemaker InvokeEndpoint API."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
from langchain.llms.sagemaker_endpoint import ContentHandlerBase
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
029089106e37-1 | credentials_profile_name=credentials_profile_name
)
"""
client: Any #: :meta private:
endpoint_name: str = ""
"""The name of the endpoint from the deployed Sagemaker model.
Must be unique within an AWS Region."""
region_name: str = ""
"""The aws region where the Sagemaker model ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
029089106e37-2 | """ # noqa: E501
model_kwargs: Optional[Dict] = None
"""Key word arguments to pass to the model."""
endpoint_kwargs: Optional[Dict] = None
"""Optional attributes passed to the invoke_endpoint
function. See `boto3`_. docs for more info.
.. _boto3: <https://boto3.amazonaws.com/v1/documentation/ap... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
029089106e37-3 | # replace newlines, which can negatively affect performance.
texts = list(map(lambda x: x.replace("\n", " "), texts))
_model_kwargs = self.model_kwargs or {}
_endpoint_kwargs = self.endpoint_kwargs or {}
body = self.content_handler.transform_input(texts, _model_kwargs)
content_ty... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
029089106e37-4 | """Compute query embeddings using a SageMaker inference endpoint.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self._embedding_func([text])[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html |
c19417d0fcb7-0 | Source code for langchain.embeddings.tensorflow_hub
"""Wrapper around TensorflowHub embedding models."""
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]clas... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/tensorflow_hub.html |
c19417d0fcb7-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 |
32b3956ba176-0 | Source code for langchain.embeddings.huggingface_hub
"""Wrapper around HuggingFace Hub embedding models."""
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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
32b3956ba176-1 | extra = Extra.forbid
[docs] @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""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"
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
32b3956ba176-2 | """
# replace newlines, which can negatively affect performance.
texts = [text.replace("\n", " ") for text in texts]
_model_kwargs = self.model_kwargs or {}
responses = self.client(inputs=texts, params=_model_kwargs)
return responses
[docs] def embed_query(self, text: str) -> ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/huggingface_hub.html |
6a10cecb1ce4-0 | Source code for langchain.embeddings.cohere
"""Wrapper around Cohere embedding models."""
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(Base... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html |
6a10cecb1ce4-1 | values["client"] = cohere.Client(cohere_api_key)
except ImportError:
raise ValueError(
"Could not import cohere python package. "
"Please install it with `pip install cohere`."
)
return values
[docs] def embed_documents(self, texts: List[str]) -... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/cohere.html |
39f05955bdbe-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):
"""Embeddings provider to invoke Bedrock embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
39f05955bdbe-1 | 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"
"""Id of the model to call, e.g., amazon.titan-e1t-medium,... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
39f05955bdbe-2 | "Please check that credentials in the specified "
"profile name are valid."
) from e
return values
def _embedding_func(self, text: str) -> List[float]:
"""Call out to Bedrock embedding endpoint."""
# replace newlines, which can negatively affect performance.
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
39f05955bdbe-3 | 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 to embed.
Returns:
Embeddings for the text.... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
cb2e790a1a77-0 | Source code for langchain.embeddings.self_hosted_hugging_face
"""Wrapper around HuggingFace embedding models for self-hosted remote hardware."""
import importlib
import logging
from typing import Any, Callable, List, Optional
from langchain.embeddings.self_hosted import SelfHostedEmbeddings
DEFAULT_MODEL_NAME = "senten... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
cb2e790a1a77-1 | )
if device < 0 and cuda_device_count > 0:
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 ass... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
cb2e790a1a77-2 | model_load_fn: Callable = load_embedding_model
"""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."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
cb2e790a1a77-3 | model_name=model_name, hardware=gpu)
"""
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... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted_hugging_face.html |
cb2e790a1a77-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 |
ab30e82cde86-0 | Source code for langchain.embeddings.mosaicml
"""Wrapper around MosaicML APIs."""
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]cla... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
ab30e82cde86-1 | [docs] class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
[docs] @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(... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
ab30e82cde86-2 | return self._embed(input, is_retry=True)
raise ValueError(
f"Error raised by inference API: {parsed_response['error']}"
)
# The inference API has changed a couple of times, so we add some handling
# to be robust to multiple response formats.
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
ab30e82cde86-3 | """Embed documents using a MosaicML deployed instructor embedding model.
Args:
texts: The list of texts to embed.
Returns:
List of embeddings, one for each text.
"""
instruction_pairs = [(self.embed_instruction, text) for text in texts]
embeddings = self._... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/mosaicml.html |
03edac8217c2-0 | Source code for langchain.embeddings.modelscope_hub
"""Wrapper around ModelScopeHub embedding models."""
from typing import Any, List
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
[docs]class ModelScopeEmbeddings(BaseModel, Embeddings):
"""Wrapper around modelscope_hub embed... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html |
03edac8217c2-1 | 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 embeddings.tolist()
[docs] def embed_query(self, text: st... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/modelscope_hub.html |
094de39724ab-0 | Source code for langchain.embeddings.vertexai
"""Wrapper around Google VertexAI embedding models."""
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_verte... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/vertexai.html |
094de39724ab-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 |
0ff3b7871b07-0 | Source code for langchain.embeddings.base
"""Interface for embedding models."""
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]]:
"""Em... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/base.html |
e7125c238635-0 | Source code for langchain.embeddings.fake
from typing import List
import numpy as np
from pydantic import BaseModel
from langchain.embeddings.base import Embeddings
[docs]class FakeEmbeddings(Embeddings, BaseModel):
size: int
def _get_embedding(self) -> List[float]:
return list(np.random.normal(size=sel... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/fake.html |
88c315a71ba3-0 | Source code for langchain.embeddings.minimax
"""Wrapper around MiniMax APIs."""
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_... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html |
88c315a71ba3-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 |
88c315a71ba3-2 | [docs] def embed(
self,
texts: List[str],
embed_type: str,
) -> List[List[float]]:
payload = {
"model": self.model,
"type": embed_type,
"texts": texts,
}
# HTTP headers for authorization
headers = {
"Authoriza... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html |
88c315a71ba3-3 | self, texts=[text], embed_type=self.embed_type_query
)
return embeddings[0] | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/minimax.html |
f950f8838f41-0 | Source code for langchain.embeddings.openai
"""Wrapper around OpenAI embedding models."""
from __future__ import annotations
import logging
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import numpy as np
from pydantic import Ba... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-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/openai.html |
f950f8838f41-2 | @_async_retry_decorator(embeddings)
async def _async_embed_with_retry(**kwargs: Any) -> Any:
return await embeddings.client.acreate(**kwargs)
return await _async_embed_with_retry(**kwargs)
[docs]class OpenAIEmbeddings(BaseModel, Embeddings):
"""Wrapper around OpenAI embedding models.
To use, you... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-3 | deployment="your-embeddings-deployment-name",
model="your-embeddings-model-name",
openai_api_base="https://your-endpoint.openai.azure.com/",
openai_api_type="azure",
)
text = "This is a test query."
query_result = embeddings.embed_query... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-4 | Tiktoken is used to count the number of tokens in documents to constrain
them to be under a certain limit. By default, when set to None, this will
be the same as the embedding model name. However, there are some cases
where you may want to use this Embedding class with a model name not
supported by ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-5 | default_api_version = "2022-12-01"
else:
default_api_version = ""
values["openai_api_version"] = get_from_dict_or_env(
values,
"openai_api_version",
"OPENAI_API_VERSION",
default=default_api_version,
)
values["openai_organizatio... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-6 | def _get_len_safe_embeddings(
self, texts: List[str], *, engine: str, chunk_size: Optional[int] = None
) -> List[List[float]]:
embeddings: List[List[float]] = [[] for _ in range(len(texts))]
try:
import tiktoken
except ImportError:
raise ImportError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-7 | response = embed_with_retry(
self,
input=tokens[i : i + _chunk_size],
**self._invocation_params,
)
batched_embeddings += [r["embedding"] for r in response["data"]]
results: List[List[List[float]]] = [[] for _ in range(len(texts))]
n... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-8 | "Please install it with `pip install tiktoken`."
)
tokens = []
indices = []
model_name = self.tiktoken_model_name or self.model
try:
encoding = tiktoken.encoding_for_model(model_name)
except KeyError:
logger.warning("Warning: model not found. U... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-9 | results[indices[i]].append(batched_embeddings[i])
num_tokens_in_batch[indices[i]].append(len(tokens[i]))
for i in range(len(texts)):
_result = results[i]
if len(_result) == 0:
average = (
await async_embed_with_retry(
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-10 | else:
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_... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
f950f8838f41-11 | # NOTE: to keep things simple, we assume the list may contain texts longer
# than the maximum context and use length-safe embedding function.
return await self._aget_len_safe_embeddings(texts, engine=self.deployment)
[docs] def embed_query(self, text: str) -> List[float]:
"""Call out to... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/openai.html |
7b00ff31d114-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 |
7b00ff31d114-1 | model_kwargs: Optional[dict] = None
"""Other model keyword args"""
deepinfra_api_token: Optional[str] = None
[docs] class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
[docs] @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html |
7b00ff31d114-2 | )
try:
t = res.json()
embeddings = t["embeddings"]
except requests.exceptions.JSONDecodeError as e:
raise ValueError(
f"Error raised by inference API: {e}.\nResponse: {res.text}"
)
return embeddings
[docs] def embed_documents(sel... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/deepinfra.html |
bf4beff084a7-0 | Source code for langchain.memory.token_buffer
from typing import Any, Dict, List
from langchain.base_language import BaseLanguageModel
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationTokenBufferMemory(BaseChatMemory):
"""Buf... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
bf4beff084a7-1 | if curr_buffer_length > self.max_token_limit:
pruned_memory = []
while curr_buffer_length > self.max_token_limit:
pruned_memory.append(buffer.pop(0))
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) | https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
7e95e5dfa03d-0 | Source code for langchain.memory.utils
from typing import Any, Dict, List
from langchain.schema import get_buffer_string # noqa: 401
[docs]def get_prompt_input_key(inputs: Dict[str, Any], memory_variables: List[str]) -> str:
"""
Get the prompt input key.
Args:
inputs: Dict[str, Any]
memory_... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/utils.html |
fbf5eaaf7946-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from pydantic import Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
fbf5eaaf7946-1 | entities = self._get_current_entities(inputs)
summary_strings = []
for entity in entities:
knowledge = self.kg.get_entity_knowledge(entity)
if knowledge:
summary = f"On {entity}: {'. '.join(knowledge)}."
summary_strings.append(summary)
cont... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
fbf5eaaf7946-2 | human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
output = chain.predict(
history=buffer_string,
input=input_string,
)
return get_entities(output)
def _get_current_entities(self, inputs: Dict[str, Any]) -> List[str]:
"""Get the cu... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
fbf5eaaf7946-3 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.kg.clear() | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
619ef2503ecd-0 | Source code for langchain.memory.vectorstore
"""Class for a VectorStore-backed memory object."""
from typing import Any, Dict, List, Optional, Union
from pydantic import Field
from langchain.memory.chat_memory import BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import Documen... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
619ef2503ecd-1 | docs = self.retriever.get_relevant_documents(query)
result: Union[List[Document], str]
if not self.return_docs:
result = "\n".join([doc.page_content for doc in docs])
else:
result = docs
return {self.memory_key: result}
def _form_documents(
self, input... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
8ff0dcd8ac33-0 | Source code for langchain.memory.buffer_window
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationBufferWindowMemory(BaseChatMemory):
"""Buffer for storing conversation memory."""
human_pr... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html |
95126a7ffd6c-0 | Source code for langchain.memory.readonly
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class ReadOnlySharedMemory(BaseMemory):
"""A memory wrapper that is read-only and cannot be changed."""
memory: BaseMemory
@property
def memory_variables(self) -> List[str]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/readonly.html |
3342730a0381-0 | Source code for langchain.memory.summary
from __future__ import annotations
from typing import Any, Dict, List, Type
from pydantic import BaseModel, root_validator
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
3342730a0381-1 | **kwargs: Any,
) -> ConversationSummaryMemory:
obj = cls(llm=llm, chat_memory=chat_memory, **kwargs)
for i in range(0, len(obj.chat_memory.messages), summarize_step):
obj.buffer = obj.predict_new_summary(
obj.chat_memory.messages[i : i + summarize_step], obj.buffer
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
3342730a0381-2 | )
[docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = "" | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
3fc3e29f076b-0 | Source code for langchain.memory.entity
import logging
from abc import ABC, abstractmethod
from itertools import islice
from typing import Any, Dict, Iterable, List, Optional
from pydantic import BaseModel, Field
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3fc3e29f076b-1 | return self.store.get(key, default)
[docs] def set(self, key: str, value: Optional[str]) -> None:
self.store[key] = value
[docs] def delete(self, key: str) -> None:
del self.store[key]
[docs] def exists(self, key: str) -> bool:
return key in self.store
[docs] def clear(self) -> None:... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3fc3e29f076b-2 | self.redis_client = redis.Redis.from_url(url=url, decode_responses=True)
except redis.exceptions.ConnectionError as error:
logger.error(error)
self.session_id = session_id
self.key_prefix = key_prefix
self.ttl = ttl
self.recall_ttl = recall_ttl or ttl
@property
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3fc3e29f076b-3 | iterator = iter(iterable)
while batch := list(islice(iterator, batch_size)):
yield batch
for keybatch in batched(
self.redis_client.scan_iter(f"{self.full_key_prefix}:*"), 500
):
self.redis_client.delete(*keybatch)
[docs]class SQLiteEntityStore(BaseEnt... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3fc3e29f076b-4 | query = f"""
SELECT value
FROM {self.full_table_name}
WHERE key = ?
"""
cursor = self.conn.execute(query, (key,))
result = cursor.fetchone()
if result is not None:
value = result[0]
return value
return default
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3fc3e29f076b-5 | With a swapable entity store, persisting entities across conversations.
Defaults to an in-memory entity store, and can be swapped out for a Redis,
SQLite, or other entity store.
"""
human_prefix: str = "Human"
ai_prefix: str = "AI"
llm: BaseLanguageModel
entity_extraction_prompt: BasePromptT... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3fc3e29f076b-6 | # Create an LLMChain for predicting entity names from the recent chat history:
chain = LLMChain(llm=self.llm, prompt=self.entity_extraction_prompt)
if self.input_key is None:
prompt_input_key = get_prompt_input_key(inputs, self.memory_variables)
else:
prompt_input_key = s... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3fc3e29f076b-7 | if self.return_messages:
# Get last `k` pair of chat messages:
buffer: Any = self.buffer[-self.k * 2 :]
else:
# Reuse the string we made earlier:
buffer = buffer_string
return {
self.chat_history_key: buffer,
"entities": entity_summ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
3fc3e29f076b-8 | summary=existing_summary,
entity=entity,
history=buffer_string,
input=input_data,
)
# Save the updated summary to the entity store
self.entity_store.set(entity, output.strip())
[docs] def clear(self) -> None:
"""Clear memory ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
7d21cac494e6-0 | Source code for langchain.memory.combined
import warnings
from typing import Any, Dict, List, Set
from pydantic import validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import BaseMemory
[docs]class CombinedMemory(BaseMemory):
"""Class for combining multiple memories' data toge... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
7d21cac494e6-1 | memory_variables = []
for memory in self.memories:
memory_variables.extend(memory.memory_variables)
return memory_variables
[docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
"""Load all vars from sub-memories."""
memory_data: Dict[str, Any] ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
8298e24ffa52-0 | Source code for langchain.memory.chat_memory
from abc import ABC
from typing import Any, Dict, Optional, Tuple
from pydantic import Field
from langchain.memory.chat_message_histories.in_memory import ChatMessageHistory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import BaseChatMessageH... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_memory.html |
81daa7ac24e5-0 | Source code for langchain.memory.buffer
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory, BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema import get_buffer_string
[docs]class ConversationBuff... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
81daa7ac24e5-1 | def validate_chains(cls, values: Dict) -> Dict:
"""Validate that return messages is not True."""
if values.get("return_messages", False):
raise ValueError(
"return_messages must be False for ConversationStringBufferMemory"
)
return values
@property
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
3da74169c441-0 | Source code for langchain.memory.simple
from typing import Any, Dict, List
from langchain.schema import BaseMemory
[docs]class SimpleMemory(BaseMemory):
"""Simple memory for storing context or other bits of information that shouldn't
ever change between prompts.
"""
memories: Dict[str, Any] = dict()
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/simple.html |
302bc32b3cf8-0 | Source code for langchain.memory.motorhead_memory
from typing import Any, Dict, List, Optional
import requests
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema import get_buffer_string
MANAGED_URL = "https://api.getmetal.io/v1/motorhead"
# LOCAL_URL = "http://localhost:8080"
[docs]class Mot... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
302bc32b3cf8-1 | messages = res_data.get("messages", [])
context = res_data.get("context", "NONE")
for message in reversed(messages):
if message["role"] == "AI":
self.chat_memory.add_ai_message(message["content"])
else:
self.chat_memory.add_user_message(message["co... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
ee985eb740d1-0 | Source code for langchain.memory.summary_buffer
from typing import Any, Dict, List
from pydantic import root_validator
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.summary import SummarizerMixin
from langchain.schema import BaseMessage, get_buffer_string
[docs]class ConversationSummaryB... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
ee985eb740d1-1 | if expected_keys != set(prompt_variables):
raise ValueError(
"Got unexpected prompt input variables. The prompt expects "
f"{prompt_variables}, but it should have {expected_keys}."
)
return values
[docs] def save_context(self, inputs: Dict[str, Any], ou... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
1cfdff909e36-0 | Source code for langchain.memory.chat_message_histories.file
import json
import logging
from pathlib import Path
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
[docs]class FileChatMe... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
d4bef4283b4a-0 | Source code for langchain.memory.chat_message_histories.firestore
"""Firestore Chat Message History."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, List, Optional
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
messages_from_dict,
messages_to_d... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/firestore.html |
d4bef4283b4a-1 | try:
firebase_admin.get_app()
except ValueError as e:
logger.debug("Initializing Firebase app: %s", e)
firebase_admin.initialize_app()
self.firestore_client = firestore.client()
self._document = self.firestore_client.collection(
self.collection_nam... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/firestore.html |
2b3dd4a37190-0 | Source code for langchain.memory.chat_message_histories.cosmos_db
"""Azure CosmosDB Memory History."""
from __future__ import annotations
import logging
from types import TracebackType
from typing import TYPE_CHECKING, Any, List, Optional, Type
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
2b3dd4a37190-1 | :param connection_string: The connection string to use to authenticate.
:param ttl: The time to live (in seconds) to use for documents in the container.
:param cosmos_client_kwargs: Additional kwargs to pass to the CosmosClient.
"""
self.cosmos_endpoint = cosmos_endpoint
self.cos... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
2b3dd4a37190-2 | PartitionKey,
)
except ImportError as exc:
raise ImportError(
"You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501
) from exc
database = self._client.create_database_if_not_exists(self.cosmos_database)
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
2b3dd4a37190-3 | )
except CosmosHttpResponseError:
logger.info("no session found")
return
if "messages" in item and len(item["messages"]) > 0:
self.messages = messages_from_dict(item["messages"])
[docs] def add_message(self, message: BaseMessage) -> None:
"""Add a self-crea... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
ac9f76ee6754-0 | Source code for langchain.memory.chat_message_histories.in_memory
from typing import List
from pydantic import BaseModel
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
)
[docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel):
messages: List[BaseMessage] = []
[docs] def add... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html |
8b553c52c223-0 | Source code for langchain.memory.chat_message_histories.sql
import json
import logging
from typing import List
from sqlalchemy import Column, Integer, Text, create_engine
try:
from sqlalchemy.orm import declarative_base
except ImportError:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
8b553c52c223-1 | DynamicBase = declarative_base()
self.Message = create_message_model(self.table_name, DynamicBase)
# Create all does the check for us in case the table exists.
DynamicBase.metadata.create_all(self.engine)
@property
def messages(self) -> List[BaseMessage]: # type: ignore
"""Retri... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
dd8002e18135-0 | Source code for langchain.memory.chat_message_histories.dynamodb
import logging
from typing import List, Optional
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
[docs]class DynamoDBCha... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
dd8002e18135-1 | except ClientError as error:
if error.response["Error"]["Code"] == "ResourceNotFoundException":
logger.warning("No record found with session id: %s", self.session_id)
else:
logger.error(error)
if response and "Item" in response:
items = respons... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
a947e9d153c6-0 | Source code for langchain.memory.chat_message_histories.zep
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Dict, List, Optional
from langchain.schema import (
AIMessage,
BaseChatMessageHistory,
BaseMessage,
HumanMessage,
)
if TYPE_CHECKING:
from zep_python import... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
a947e9d153c6-1 | url: str = "http://localhost:8000",
api_key: Optional[str] = None,
) -> None:
try:
from zep_python import ZepClient
except ImportError:
raise ValueError(
"Could not import zep-python package. "
"Please install it with `pip install zep-p... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
a947e9d153c6-2 | zep_memory: Optional[Memory] = self._get_memory()
if not zep_memory or not zep_memory.summary:
return None
return zep_memory.summary.content
def _get_memory(self) -> Optional[Memory]:
"""Retrieve memory from Zep"""
from zep_python import NotFoundError
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.