id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
a962634a24e5-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
a962634a24e5-1
If a specific credential profile should be used, you must pass the name of the profile from the ~/.aws/credentials file that is to be used. Make sure the credentials / roles used have the required policies to access the Sagemaker endpoint. See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_pol...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
a962634a24e5-2
) """ 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 is deployed, eg. `us-west-2`.""" credentials_profile_name:...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
a962634a24e5-3
output transform functions to handle formats between LLM and the endpoint. """ """ Example: .. code-block:: python from langchain.embeddings.sagemaker_endpoint import EmbeddingsContentHandler class ContentHandler(EmbeddingsContentHandler): content_type = "applica...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
a962634a24e5-4
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/api/latest/index.html> """ class Config: """Configuration for this pydantic object.""" extr...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
a962634a24e5-5
session = boto3.Session() values["client"] = session.client( "sagemaker-runtime", region_name=values["region_name"] ) except Exception as e: raise ValueError( "Could not load credentials to authenticate with AWS client. ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
a962634a24e5-6
_model_kwargs = self.model_kwargs or {} _endpoint_kwargs = self.endpoint_kwargs or {} body = self.content_handler.transform_input(texts, _model_kwargs) content_type = self.content_handler.content_type accepts = self.content_handler.accepts # send request try: ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
a962634a24e5-7
Args: texts: The list of texts to embed. chunk_size: The chunk size defines how many input texts will be grouped together as request. If None, will use the chunk size specified by the class. Returns: List of embeddings, one for each text. ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
a962634a24e5-8
""" return self._embedding_func([text])[0]
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/sagemaker_endpoint.html
c95d8a95089f-0
Source code for langchain.embeddings.llamacpp """Wrapper around llama.cpp embedding models.""" 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): """Wrapper ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
c95d8a95089f-1
model_path: str n_ctx: int = Field(512, alias="n_ctx") """Token context window.""" n_parts: int = Field(-1, alias="n_parts") """Number of parts to split the model into. If -1, the number of parts is automatically determined.""" seed: int = Field(-1, alias="seed") """Seed. If -1, a random se...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
c95d8a95089f-2
use_mlock: bool = Field(False, alias="use_mlock") """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") """...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
c95d8a95089f-3
"""Validate that llama-cpp-python library is installed.""" model_path = values["model_path"] model_param_names = [ "n_ctx", "n_parts", "seed", "f16_kv", "logits_all", "vocab_only", "use_mlock", "n_threads", ...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
c95d8a95089f-4
raise ModuleNotFoundError( "Could not import llama-cpp-python library. " "Please install the llama-cpp-python library to " "use this embedding model: pip install llama-cpp-python" ) except Exception as e: raise ValueError( f...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
c95d8a95089f-5
[docs] def embed_query(self, text: str) -> List[float]: """Embed a query using the Llama model. Args: text: The text to embed. Returns: Embeddings for the text. """ embedding = self.client.embed(text) return list(map(float, embedding))
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/llamacpp.html
68d044c6d286-0
Source code for langchain.embeddings.dashscope """Wrapper around DashScope embedding models.""" 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 HTTPErro...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
68d044c6d286-1
# 1 seconds, then up to 4 seconds, then 4 seconds afterwards return retry( reraise=True, stop=stop_after_attempt(embeddings.max_retries), wait=wait_exponential(multiplier, min=min_seconds, max=max_seconds), retry=(retry_if_exception_type(HTTPError)), before_sleep=before_sleep...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
68d044c6d286-2
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 " f"code: {resp.code} \n message: {r...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
68d044c6d286-3
embeddings = DashScopeEmbeddings(dashscope_api_key="my-api-key") Example: .. code-block:: python import os os.environ["DASHSCOPE_API_KEY"] = "your DashScope API KEY" from langchain.embeddings.dashscope import DashScopeEmbeddings embeddings = DashScopeEmbedding...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
68d044c6d286-4
extra = Extra.forbid @root_validator() def validate_environment(cls, values: Dict) -> Dict: import dashscope """Validate that api key and python package exists in environment.""" values["dashscope_api_key"] = get_from_dict_or_env( values, "dashscope_api_key", "DASHSCOPE_API_K...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
68d044c6d286-5
Args: texts: The list of texts to embed. chunk_size: The chunk size of embeddings. If None, will use the chunk size specified by the class. Returns: List of embeddings, one for each text. """ embeddings = embed_with_retry( self, inp...
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
68d044c6d286-6
)[0]["embedding"] return embedding
https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/dashscope.html
f05d60bb5daf-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
f05d60bb5daf-1
} if is_managed and not (self.api_key and self.client_id): raise ValueError( """ You must provide an API key or a client ID to use the managed version of Motorhead. Visit https://getmetal.io for more information. """ ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html
f05d60bb5daf-2
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["content"]) if context and context != "NONE...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html
f05d60bb5daf-3
input_str, output_str = self._get_input_output(inputs, outputs) requests.post( f"{self.url}/sessions/{self.session_id}/memory", timeout=self.timeout, json={ "messages": [ {"role": "Human", "content": f"{input_str}"}, {"r...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html
c6e353beb67b-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
c6e353beb67b-1
pass @abstractmethod def set(self, key: str, value: Optional[str]) -> None: """Set entity value in store.""" pass @abstractmethod def delete(self, key: str) -> None: """Delete entity value from store.""" pass @abstractmethod def exists(self, key: str) -> bool: ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-2
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
c6e353beb67b-3
recall_ttl: Optional[int] = 60 * 60 * 24 * 3 def __init__( self, session_id: str = "default", url: str = "redis://localhost:6379/0", key_prefix: str = "memory_store", ttl: Optional[int] = 60 * 60 * 24, recall_ttl: Optional[int] = 60 * 60 * 24 * 3, *args: Any, ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-4
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 def full_key_prefix(self) -> str: return f"{self.key_prefix}:{self.sess...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-5
if not value: return self.delete(key) self.redis_client.set(f"{self.full_key_prefix}:{key}", value, ex=self.ttl) logger.debug( f"REDIS MEM set '{self.full_key_prefix}:{key}': '{value}' EX {self.ttl}" ) [docs] def delete(self, key: str) -> None: self.redis_clien...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-6
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(BaseEntityStore): """SQLite-backed Entity store""" session_id: str = "default" table_name: str = "me...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-7
) super().__init__(*args, **kwargs) self.conn = sqlite3.connect(db_file) self.session_id = session_id self.table_name = table_name self._create_table_if_not_exists() @property def full_table_name(self) -> str: return f"{self.table_name}_{self.session_id}" def ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-8
WHERE key = ? """ cursor = self.conn.execute(query, (key,)) result = cursor.fetchone() if result is not None: value = result[0] return value return default [docs] def set(self, key: str, value: Optional[str]) -> None: if not value: r...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-9
[docs] def exists(self, key: str) -> bool: query = f""" SELECT 1 FROM {self.full_table_name} WHERE key = ? LIMIT 1 """ cursor = self.conn.execute(query, (key,)) result = cursor.fetchone() return result is not None [docs] def c...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-10
SQLite, or other entity store. """ human_prefix: str = "Human" ai_prefix: str = "AI" llm: BaseLanguageModel entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT entity_summarization_prompt: BasePromptTemplate = ENTITY_SUMMARIZATION_PROMPT # Cache of recently detected entit...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-11
return self.chat_memory.messages @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: """ return ["entities", self.chat_history_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-12
if self.input_key is None: prompt_input_key = get_prompt_input_key(inputs, self.memory_variables) else: prompt_input_key = self.input_key # Extract an arbitrary window of the last message pairs from # the chat history, where the hyperparameter k is the # number of...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-13
if output.strip() == "NONE": entities = [] else: # Make a list of the extracted entities: entities = [w.strip() for w in output.split(",")] # Make a dictionary of entities with summary if exists: entity_summaries = {} for entity in entities: ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-14
buffer = buffer_string return { self.chat_history_key: buffer, "entities": entity_summaries, } [docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """ Save context from this conversation history to the entity store. G...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-15
buffer_string = get_buffer_string( self.buffer[-self.k * 2 :], human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) input_data = inputs[prompt_input_key] # Create an LLMChain for predicting entity summarization from the context chain = LLMChain(...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
c6e353beb67b-16
[docs] def clear(self) -> None: """Clear memory contents.""" self.chat_memory.clear() self.entity_cache.clear() self.entity_store.clear()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
f2ab7e5b01eb-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
f2ab7e5b01eb-1
) @property def memory_variables(self) -> List[str]: """Will always return list of memory variables. :meta private: """ return [self.memory_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Return history buffer.""" retur...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
f2ab7e5b01eb-2
@root_validator() 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 va...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
f2ab7e5b01eb-3
if self.input_key is None: prompt_input_key = get_prompt_input_key(inputs, self.memory_variables) else: prompt_input_key = self.input_key if self.output_key is None: if len(outputs) != 1: raise ValueError(f"One output key expected, got {outputs.keys()}...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
970ced87c4e8-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
970ced87c4e8-1
return_docs: bool = False """Whether or not to return the result of querying the database directly.""" @property def memory_variables(self) -> List[str]: """The list of keys emitted from the load_memory_variables method.""" return [self.memory_key] def _get_prompt_input_key(self, inputs:...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
970ced87c4e8-2
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, inputs: Dict[str, Any], outputs: Dict[str, str] ) -> List[Doc...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
970ced87c4e8-3
[docs] def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: """Save context from this conversation to buffer.""" documents = self._form_documents(inputs, outputs) self.retriever.add_documents(documents) [docs] def clear(self) -> None: """Nothing to clear...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html
747ec64fba7b-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
747ec64fba7b-1
return [self.memory_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]: """Return history buffer.""" buffer: Any = self.buffer[-self.k * 2 :] if self.k > 0 else [] if not self.return_messages: buffer = get_buffer_string( buffer, ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html
7be18352fe16-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
7be18352fe16-1
def predict_new_summary( self, messages: List[BaseMessage], existing_summary: str ) -> str: new_lines = get_buffer_string( messages, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) chain = LLMChain(llm=self.llm, prompt=self.prompt) ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html
7be18352fe16-2
**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
7be18352fe16-3
else: buffer = self.buffer return {self.memory_key: buffer} @root_validator() def validate_prompt_input_variables(cls, values: Dict) -> Dict: """Validate that prompt input variables are consistent.""" prompt_variables = values["prompt"].input_variables expected_keys =...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html
7be18352fe16-4
) [docs] def clear(self) -> None: """Clear memory contents.""" super().clear() self.buffer = ""
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html
e7a7c1799aea-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
e7a7c1799aea-1
) all_variables |= set(val.memory_variables) return value @validator("memories") def check_input_key(cls, value: List[BaseMemory]) -> List[BaseMemory]: """Check that if memories are of type BaseChatMemory that input keys exist.""" for val in value: if isinstance(v...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html
e7a7c1799aea-2
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] = {} # Collect vars from all sub-memories for memory in...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html
e7a7c1799aea-3
"""Clear context from this session for every memory.""" for memory in self.memories: memory.clear()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html
41a692094270-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
b27c9c00671e-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
b27c9c00671e-1
pass
https://api.python.langchain.com/en/latest/_modules/langchain/memory/simple.html
63252e705c9e-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
63252e705c9e-1
return [self.memory_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Return history buffer.""" buffer: Any = self.buffer if self.return_messages: final_buffer: Any = buffer else: final_buffer = get_buffer_string( ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
63252e705c9e-2
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
9e340c3c9858-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
9e340c3c9858-1
return [self.memory_key] [docs] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Return history buffer.""" buffer = self.buffer if self.moving_summary_buffer != "": first_messages: List[BaseMessage] = [ self.summary_message_cls(content=...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
9e340c3c9858-2
expected_keys = {"summary", "new_lines"} 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] ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
9e340c3c9858-3
pruned_memory.append(buffer.pop(0)) curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer) self.moving_summary_buffer = self.predict_new_summary( pruned_memory, self.moving_summary_buffer ) [docs] def clear(self) -> None: """Clear memory con...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
2302e4359a9e-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
2302e4359a9e-1
Integrates with external knowledge graph to store and retrieve information about knowledge triples in the conversation. """ k: int = 2 human_prefix: str = "Human" ai_prefix: str = "AI" kg: NetworkxEntityGraph = Field(default_factory=NetworkxEntityGraph) knowledge_extraction_prompt: BasePromp...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
2302e4359a9e-2
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) context: Union[str, List] if not summary_strings: ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
2302e4359a9e-3
"""Get the input key for the prompt.""" if self.input_key is None: return get_prompt_input_key(inputs, self.memory_variables) return self.input_key def _get_prompt_output_key(self, outputs: Dict[str, Any]) -> str: """Get the output key for the prompt.""" if self.output_ke...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
2302e4359a9e-4
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 current entities in the conversation.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
2302e4359a9e-5
history=buffer_string, input=input_string, verbose=True, ) knowledge = parse_triples(output) return knowledge def _get_and_update_kg(self, inputs: Dict[str, Any]) -> None: """Get and update knowledge graph from the conversation history.""" prompt_input...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
2302e4359a9e-6
super().clear() self.kg.clear()
https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html
1b7aadb01908-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
1b7aadb01908-1
memory = ConversationBufferMemory( memory_key="chat_history", chat_memory=zep_chat_history ) Zep provides long-term conversation storage for LLM apps. The server stores, summarizes, embeds, indexes, and enriches conversational AI chat histories, and exposes them via simple, low-latency A...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
1b7aadb01908-2
) -> None: try: from zep_python import ZepClient except ImportError: raise ValueError( "Could not import zep-python package. " "Please install it with `pip install zep-python`." ) self.zep_client = ZepClient(base_url=url) ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
1b7aadb01908-3
if zep_memory.messages: msg: Message for msg in zep_memory.messages: if msg.role == "ai": messages.append(AIMessage(content=msg.content)) else: messages.append(HumanMessage(content=msg.content)) return messages @...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
1b7aadb01908-4
return zep_memory.summary.content def _get_memory(self) -> Optional[Memory]: """Retrieve memory from Zep""" from zep_python import NotFoundError try: zep_memory: Memory = self.zep_client.get_memory(self.session_id) except NotFoundError: logger.warning( ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
1b7aadb01908-5
zep_memory = Memory(messages=[zep_message]) self.zep_client.add_memory(self.session_id, zep_memory) [docs] def search( self, query: str, metadata: Optional[Dict] = None, limit: Optional[int] = None ) -> List[MemorySearchResult]: """Search Zep memory for messages matching the query""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
1b7aadb01908-6
""" try: self.zep_client.delete_memory(self.session_id) except NotFoundError: logger.warning( f"Session {self.session_id} not found in Zep. Skipping delete." )
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html
785dc7e0a3ee-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
785dc7e0a3ee-1
ttl: Optional[int] = None, cosmos_client_kwargs: Optional[dict] = None, ): """ Initializes a new instance of the CosmosDBChatMessageHistory class. Make sure to call prepare_cosmos or use the context manager to make sure your database is ready. Either a credential or a...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
785dc7e0a3ee-2
: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.cosmos_database = cosmos_database self.cosmos_container = cosmos_container ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
785dc7e0a3ee-3
) from exc if self.credential: self._client = CosmosClient( url=self.cosmos_endpoint, credential=self.credential, **cosmos_client_kwargs or {}, ) elif self.conn_string: self._client = CosmosClient.from_connection_string(...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
785dc7e0a3ee-4
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
785dc7e0a3ee-5
exc_val: Optional[BaseException], traceback: Optional[TracebackType], ) -> None: """Context manager exit""" self.upsert_messages() self._client.__exit__(exc_type, exc_val, traceback) [docs] def load_messages(self) -> None: """Retrieve the messages from Cosmos""" if...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
785dc7e0a3ee-6
item = self._container.read_item( item=self.session_id, partition_key=self.user_id ) except CosmosHttpResponseError: logger.info("no session found") return if "messages" in item and len(item["messages"]) > 0: self.messages = messages_from_d...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
785dc7e0a3ee-7
"user_id": self.user_id, "messages": messages_to_dict(self.messages), } ) [docs] def clear(self) -> None: """Clear session memory from this memory and cosmos.""" self.messages = [] if self._container: self._container.delete_item( ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html
e9b9d1f8684e-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
bd137fe8f7c0-0
Source code for langchain.memory.chat_message_histories.cassandra import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, BaseMessage, _message_to_dict, messages_from_dict, ) logger = logging.getLogger(__name__) DEFAULT_KEYSPACE_NAME = "chat_history" DEF...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
bd137fe8f7c0-1
username: username to connect to Cassandra cluster password: password to connect to Cassandra cluster keyspace_name: name of the keyspace to use table_name: name of the table to use """ def __init__( self, contact_points: List[str], session_id: str, port: ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
bd137fe8f7c0-2
AuthenticationFailed, OperationTimedOut, UnresolvableContactPoints, ) from cassandra.cluster import Cluster, PlainTextAuthProvider except ImportError: raise ValueError( "Could not import cassandra-driver python package. " ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
bd137fe8f7c0-3
self._prepare_cassandra() def _prepare_cassandra(self) -> None: """Create the keyspace and table if they don't exist yet""" from cassandra import OperationTimedOut, Unavailable try: self.session.execute( f"""CREATE KEYSPACE IF NOT EXISTS {self.key...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html
bd137fe8f7c0-4
f"""CREATE TABLE IF NOT EXISTS {self.table_name} (id UUID, session_id varchar, history text, PRIMARY KEY ((session_id), id) );""" ) except (OperationTimedOut, Unavailable) as error: logger.error( f"Unable to create cassandra \ ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html