id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
7a73cff8e807-0 | Source code for langchain.retrievers.chaindesk
from typing import Any, List, Optional
import aiohttp
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForRetrieverRun,
CallbackManagerForRetrieverRun,
)
from langchain.schema import BaseRetriever, Document
[docs]class ChaindeskRetrieve... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chaindesk.html |
7a73cff8e807-1 | )
for r in data["results"]
]
async def _aget_relevant_documents(
self,
query: str,
*,
run_manager: AsyncCallbackManagerForRetrieverRun,
**kwargs: Any,
) -> List[Document]:
async with aiohttp.ClientSession() as session:
async with se... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/chaindesk.html |
ba7b488118f3-0 | Source code for langchain.retrievers.weaviate_hybrid_search
from __future__ import annotations
from typing import Any, Dict, List, Optional, cast
from uuid import uuid4
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForRetrieverRun
from langchain.docstore.document import Docu... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
ba7b488118f3-1 | )
if values.get("attributes") is None:
values["attributes"] = []
cast(List, values["attributes"]).append(values["text_key"])
if values.get("create_schema_if_missing", True):
class_obj = {
"class": values["index_name"],
"properties": [{"name... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
ba7b488118f3-2 | where_filter: Optional[Dict[str, object]] = None,
score: bool = False,
) -> List[Document]:
"""Look up similar documents in Weaviate."""
query_obj = self.client.query.get(self.index_name, self.attributes)
if where_filter:
query_obj = query_obj.with_where(where_filter)
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/weaviate_hybrid_search.html |
1a8cb305da3e-0 | Source code for langchain.retrievers.document_compressors.base
"""Interface for retrieved document compressors."""
from abc import ABC, abstractmethod
from inspect import signature
from typing import List, Optional, Sequence, Union
from pydantic import BaseModel
from langchain.callbacks.manager import Callbacks
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
1a8cb305da3e-1 | if isinstance(_transformer, BaseDocumentCompressor):
accepts_callbacks = (
signature(_transformer.compress_documents).parameters.get(
"callbacks"
)
is not None
)
if accepts_callbacks:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html |
fff5f05887b0-0 | Source code for langchain.retrievers.document_compressors.chain_filter
"""Filter that uses an LLM to drop documents that aren't relevant to the query."""
from typing import Any, Callable, Dict, Optional, Sequence
from langchain import LLMChain, PromptTemplate
from langchain.callbacks.manager import Callbacks
from langc... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
fff5f05887b0-1 | """Filter down documents based on their relevance to the query."""
filtered_docs = []
for doc in documents:
_input = self.get_input(query, doc)
include_doc = self.llm_chain.predict_and_parse(
**_input, callbacks=callbacks
)
if include_doc:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html |
5d928532a55f-0 | Source code for langchain.retrievers.document_compressors.cohere_rerank
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Optional, Sequence
from pydantic import Extra, root_validator
from langchain.callbacks.manager import Callbacks
from langchain.retrievers.document_compressors.base import Ba... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
5d928532a55f-1 | raise ImportError(
"Could not import cohere python package. "
"Please install it with `pip install cohere`."
)
return values
[docs] def compress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Optional[Callback... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html |
4496f26b1bf1-0 | Source code for langchain.retrievers.document_compressors.chain_extract
"""DocumentFilter that uses an LLM chain to extract the relevant parts of documents."""
from __future__ import annotations
import asyncio
from typing import Any, Callable, Dict, Optional, Sequence
from langchain import LLMChain, PromptTemplate
from... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
4496f26b1bf1-1 | """LLM wrapper to use for compressing documents."""
get_input: Callable[[str, Document], dict] = default_get_input
"""Callable for constructing the chain input from the query and a Document."""
[docs] def compress_documents(
self,
documents: Sequence[Document],
query: str,
cal... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
4496f26b1bf1-2 | prompt: Optional[PromptTemplate] = None,
get_input: Optional[Callable[[str, Document], str]] = None,
llm_chain_kwargs: Optional[dict] = None,
) -> LLMChainExtractor:
"""Initialize from LLM."""
_prompt = prompt if prompt is not None else _get_default_chain_prompt()
_get_input ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html |
06f5610bf15d-0 | Source code for langchain.retrievers.document_compressors.embeddings_filter
from typing import Callable, Dict, Optional, Sequence
import numpy as np
from pydantic import root_validator
from langchain.callbacks.manager import Callbacks
from langchain.document_transformers.embeddings_redundant_filter import (
_get_em... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
06f5610bf15d-1 | if values["k"] is None and values["similarity_threshold"] is None:
raise ValueError("Must specify one of `k` or `similarity_threshold`.")
return values
[docs] def compress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Optional[Callbacks] = ... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html |
fe9124fab753-0 | Source code for langchain.retrievers.self_query.base
"""Retriever that generates and executes structured queries over its own data source."""
from typing import Any, Dict, List, Optional, Type, cast
from pydantic import BaseModel, Field, root_validator
from langchain import LLMChain
from langchain.callbacks.manager imp... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
fe9124fab753-1 | Qdrant: QdrantTranslator,
MyScale: MyScaleTranslator,
DeepLake: DeepLakeTranslator,
}
if vectorstore_cls not in BUILTIN_TRANSLATORS:
raise ValueError(
f"Self query retriever with Vector Store type {vectorstore_cls}"
f" not supported."
)
if isinstance(v... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
fe9124fab753-2 | """Validate translator."""
if "structured_query_translator" not in values:
values["structured_query_translator"] = _get_builtin_translator(
values["vectorstore"]
)
return values
def _get_relevant_documents(
self, query: str, *, run_manager: CallbackMan... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
fe9124fab753-3 | use_original_query: bool = False,
**kwargs: Any,
) -> "SelfQueryRetriever":
if structured_query_translator is None:
structured_query_translator = _get_builtin_translator(vectorstore)
chain_kwargs = chain_kwargs or {}
if "allowed_comparators" not in chain_kwargs:
... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html |
0fdf9b0588a4-0 | Source code for langchain.retrievers.self_query.pinecone
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class PineconeTranslator(Visitor):
"""Translate the internal query... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/pinecone.html |
de3e1b246ae2-0 | Source code for langchain.retrievers.self_query.weaviate
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class WeaviateTranslator(Visitor):
"""Translate the internal query... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/weaviate.html |
83b1161ced17-0 | Source code for langchain.retrievers.self_query.qdrant
from __future__ import annotations
from typing import TYPE_CHECKING, Tuple
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
if TYPE_CHECKING:
from qdrant_client.... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html |
83b1161ced17-1 | "qdrant-client`."
) from e
self._validate_func(comparison.comparator)
attribute = self.metadata_key + "." + comparison.attribute
if comparison.comparator == Comparator.EQ:
return rest.FieldCondition(
key=attribute, match=rest.MatchValue(value=comparison.va... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/qdrant.html |
f368979a9403-0 | Source code for langchain.retrievers.self_query.chroma
from typing import Dict, Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]class ChromaTranslator(Visitor):
"""Translate internal query languag... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/chroma.html |
c18b240f8f6a-0 | Source code for langchain.retrievers.self_query.myscale
import datetime
import re
from typing import Any, Callable, Dict, Tuple
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
[docs]def DEFAULT_COMPOSER(op_name: str) ->... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
c18b240f8f6a-1 | map_dict = {
Operator.AND: DEFAULT_COMPOSER("AND"),
Operator.OR: DEFAULT_COMPOSER("OR"),
Operator.NOT: DEFAULT_COMPOSER("NOT"),
Comparator.EQ: DEFAULT_COMPOSER("="),
Comparator.GT: DEFAULT_COMPOSER(">"),
Comparator.GTE: DEFAULT_COMPOSER(">="),
Comparator.LT: DEFAU... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
c18b240f8f6a-2 | # convert timestamp for datetime objects
if type(value) is datetime.date:
attr = f"parseDateTime32BestEffort({attr})"
value = f"parseDateTime32BestEffort('{value.strftime('%Y-%m-%d')}')"
# string pattern match
if comp is Comparator.LIKE:
value = f"'%{value[1:-... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/myscale.html |
b488df002a3d-0 | Source code for langchain.retrievers.self_query.deeplake
"""Logic for converting internal query language to a valid Chroma query."""
from typing import Tuple, Union
from langchain.chains.query_constructor.ir import (
Comparator,
Comparison,
Operation,
Operator,
StructuredQuery,
Visitor,
)
COMPAR... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/deeplake.html |
b488df002a3d-1 | return f"{value}"
[docs] def visit_operation(self, operation: Operation) -> str:
args = [arg.accept(self) for arg in operation.arguments]
operator = self._format_func(operation.operator)
return "(" + (" " + operator + " ").join(args) + ")"
[docs] def visit_comparison(self, comparison: Comp... | https://api.python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/deeplake.html |
e4d0dfbdce90-0 | Source code for langchain.utils.formatting
"""Utilities for formatting strings."""
from string import Formatter
from typing import Any, List, Mapping, Sequence, Union
[docs]class StrictFormatter(Formatter):
"""A subclass of formatter that checks for extra keys."""
[docs] def check_unused_args(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/formatting.html |
8cf800698030-0 | Source code for langchain.utils.env
import os
from typing import Any, Dict, Optional
[docs]def get_from_dict_or_env(
data: Dict[str, Any], key: str, env_key: str, default: Optional[str] = None
) -> str:
"""Get a value from a dictionary or an environment variable."""
if key in data and data[key]:
ret... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/env.html |
cb554fd25d55-0 | Source code for langchain.utils.math
"""Math utils."""
from typing import List, Optional, Tuple, Union
import numpy as np
Matrix = Union[List[List[float]], List[np.ndarray], np.ndarray]
[docs]def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
"""Row-wise cosine similarity between two equal-width matrices.""... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/math.html |
cb554fd25d55-1 | second contains corresponding cosine similarities.
"""
if len(X) == 0 or len(Y) == 0:
return [], []
score_array = cosine_similarity(X, Y)
score_threshold = score_threshold or -1.0
score_array[score_array < score_threshold] = 0
top_k = min(top_k or len(score_array), np.count_nonzero(score... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/math.html |
6adf1b667048-0 | Source code for langchain.utils.input
"""Handle chained inputs."""
from typing import Dict, List, Optional, TextIO
_TEXT_COLOR_MAPPING = {
"blue": "36;1",
"yellow": "33;1",
"pink": "38;5;200",
"green": "32;1",
"red": "31;1",
}
[docs]def get_color_mapping(
items: List[str], excluded_colors: Optio... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/input.html |
6adf1b667048-1 | print(text_to_print, end=end, file=file)
if file:
file.flush() # ensure all printed content are written to file | https://api.python.langchain.com/en/latest/_modules/langchain/utils/input.html |
6a0aef296a81-0 | Source code for langchain.utils.strings
from typing import Any, List
[docs]def stringify_value(val: Any) -> str:
"""Stringify a value.
Args:
val: The value to stringify.
Returns:
str: The stringified value.
"""
if isinstance(val, str):
return val
elif isinstance(val, dict... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/strings.html |
4961abdcfc9d-0 | Source code for langchain.utils.utils
"""Generic utility functions."""
import contextlib
import datetime
import importlib
import warnings
from importlib.metadata import version
from typing import Any, Callable, Dict, Optional, Set, Tuple
from packaging.version import parse
from requests import HTTPError, Response
[docs... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
4961abdcfc9d-1 | assert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11)
"""
class MockDateTime(datetime.datetime):
"""Mock datetime.datetime.now() with a fixed datetime."""
@classmethod
def now(cls): # type: ignore
# Create a copy of dt_value.
return datetime.dat... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
4961abdcfc9d-2 | if lt_version is not None and imported_version >= parse(lt_version):
raise ValueError(
f"Expected {package} version to be < {lt_version}. Received "
f"{imported_version}."
)
if lte_version is not None and imported_version > parse(lte_version):
raise ValueError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
4961abdcfc9d-3 | for field_name in list(values):
if field_name in extra_kwargs:
raise ValueError(f"Found {field_name} supplied twice.")
if field_name not in all_required_field_names:
warnings.warn(
f"""WARNING! {field_name} is not default parameter.
{field_name} wa... | https://api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
3df1bcd0c29e-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.messages import get_buffer_string
MANAGED_URL = "https://api.getmetal.io/v1/motorhead"
# LOCAL_URL = "http://localhost:8080"
[docs]... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
3df1bcd0c29e-1 | res_data = res_data.get("data", res_data) # Handle Managed Version
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"])
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
b9d042637f2e-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 |
38fad0fa410e-0 | Source code for langchain.memory.buffer_window
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema.messages import BaseMessage, get_buffer_string
[docs]class ConversationBufferWindowMemory(BaseChatMemory):
"""Buffer for storing conversation memory inside ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html |
56f31371be28-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 |
7d7e2b57e127-0 | Source code for langchain.memory.zep_memory
from __future__ import annotations
from typing import Any, Dict, Optional
from langchain.memory import ConversationBufferMemory
from langchain.memory.chat_message_histories import ZepChatMessageHistory
[docs]class ZepMemory(ConversationBufferMemory):
"""Persist your chain... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html |
7d7e2b57e127-1 | https://docs.getzep.com/deployment/quickstart/
For more information on the zep-python package, see:
https://github.com/getzep/zep-python
"""
chat_memory: ZepChatMessageHistory
def __init__(
self,
session_id: str,
url: str = "http://localhost:8000",
api_key: Optional[s... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html |
7d7e2b57e127-2 | Defaults to "history".
Ensure that this matches the key used in
chain's prompt template.
"""
chat_message_history = ZepChatMessageHistory(
session_id=session_id,
url=url,
api_key=api_key,
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html |
ba7e048d3cbd-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.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from lang... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ba7e048d3cbd-1 | """In-memory Entity store."""
store: Dict[str, Optional[str]] = {}
[docs] def get(self, key: str, default: Optional[str] = None) -> Optional[str]:
return self.store.get(key, default)
[docs] def set(self, key: str, value: Optional[str]) -> None:
self.store[key] = value
[docs] def delete(self... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ba7e048d3cbd-2 | raise ImportError(
"Could not import redis python package. "
"Please install it with `pip install redis`."
)
super().__init__(*args, **kwargs)
try:
self.redis_client = get_client(redis_url=url, decode_responses=True)
except redis.exceptions... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ba7e048d3cbd-3 | [docs] def clear(self) -> None:
# iterate a list in batches of size batch_size
def batched(iterable: Iterable[Any], batch_size: int) -> Iterable[Any]:
iterator = iter(iterable)
while batch := list(islice(iterator, batch_size)):
yield batch
for keybatch ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ba7e048d3cbd-4 | value TEXT
)
"""
with self.conn:
self.conn.execute(create_table_query)
[docs] def get(self, key: str, default: Optional[str] = None) -> Optional[str]:
query = f"""
SELECT value
FROM {self.full_table_name}
WHERE key = ?
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ba7e048d3cbd-5 | self.conn.execute(query)
[docs]class ConversationEntityMemory(BaseChatMemory):
"""Entity extractor & summarizer memory.
Extracts named entities from the recent chat history and generates summaries.
With a swappable entity store, persisting entities across conversations.
Defaults to an in-memory entity s... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ba7e048d3cbd-6 | New entity name can be found when calling this method, before the entity
summaries are generated, so the entity cache values may be empty if no entity
descriptions are generated yet.
"""
# Create an LLMChain for predicting entity names from the recent chat history:
chain = LLMCha... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ba7e048d3cbd-7 | self.entity_cache = entities
# Should we return as message objects or as a string?
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_str... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
ba7e048d3cbd-8 | existing_summary = self.entity_store.get(entity, "")
output = chain.predict(
summary=existing_summary,
entity=entity,
history=buffer_string,
input=input_data,
)
# Save the updated summary to the entity store
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
a7430fa3722b-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.messages import BaseMessage, get_buffer_string
[docs]class Conversatio... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
a7430fa3722b-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 |
5e07f50c2238-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 information that shouldn't
ever change between prompts.
"""
memories: Dict[str, Any] = dict()
@proper... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/simple.html |
9fe6dff01326-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.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.prompt import SUMMARY_PROMPT
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
9fe6dff01326-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 |
9fe6dff01326-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 |
69a714c7656b-0 | Source code for langchain.memory.vectorstore
"""Class for a VectorStore-backed memory object."""
from typing import Any, Dict, List, Optional, Sequence, Union
from pydantic import Field
from langchain.memory.chat_memory import BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.schema impo... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
69a714c7656b-1 | """Return history buffer."""
input_key = self._get_prompt_input_key(inputs)
query = inputs[input_key]
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])... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
d14a36e2290b-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.messages import get_buffer_string
[docs]class Convers... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
d14a36e2290b-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 |
702da19f2e6e-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
from pydantic import Field
from langchain.chains.llm import LLMChain
from langchain.graphs import NetworkxEntityGraph
from langchain.graphs.networkx_graph import KnowledgeTriple, get_entities, parse_triples
from langchain.memory.chat_me... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
702da19f2e6e-1 | 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 |
702da19f2e6e-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 |
702da19f2e6e-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 |
f8ff61dff44a-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):
"""Combining multiple memories' data together."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
f8ff61dff44a-1 | 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 |
82e45ba18243-0 | Source code for langchain.memory.token_buffer
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.schema.language_model import BaseLanguageModel
from langchain.schema.messages import BaseMessage, get_buffer_string
[docs]class ConversationTokenBufferMemory(BaseChatMe... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
82e45ba18243-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 |
56fe617953ca-0 | Source code for langchain.memory.utils
from typing import Any, Dict, List
from langchain.schema.messages 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]
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/utils.html |
4f870f69dd4d-0 | Source code for langchain.memory.chat_message_histories.zep
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import (
AIMessage,
BaseMessage,
HumanMessage,... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
4f870f69dd4d-1 | """
[docs] def __init__(
self,
session_id: str,
url: str = "http://localhost:8000",
api_key: Optional[str] = None,
) -> None:
try:
from zep_python import ZepClient
except ImportError:
raise ImportError(
"Could not import zep-... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
4f870f69dd4d-2 | @property
def zep_messages(self) -> List[Message]:
"""Retrieve summary from Zep memory"""
zep_memory: Optional[Memory] = self._get_memory()
if not zep_memory:
return []
return zep_memory.messages
@property
def zep_summary(self) -> Optional[str]:
"""Retriev... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
4f870f69dd4d-3 | Args:
message: The string contents of an AI message.
metadata: Optional metadata to attach to the message.
"""
self.add_message(AIMessage(content=message), metadata=metadata)
[docs] def add_message(
self, message: BaseMessage, metadata: Optional[Dict[str, Any]] = None
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
fcd79fd9eed8-0 | Source code for langchain.memory.chat_message_histories.in_memory
from typing import List
from pydantic import BaseModel
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage
[docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel):
"""In memory impl... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html |
3a15187817a8-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 |
3a15187817a8-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 |
c1ccce97a786-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,
)
from langchain.schema.messages import BaseMessage, messa... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/firestore.html |
c1ccce97a786-1 | self._document: Optional[DocumentReference] = None
self.messages: List[BaseMessage] = []
self.firestore_client = firestore_client or _get_firestore_client()
self.prepare_firestore()
[docs] def prepare_firestore(self) -> None:
"""Prepare the Firestore client.
Use this function ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/firestore.html |
b71ecb086f8d-0 | Source code for langchain.memory.chat_message_histories.dynamodb
import logging
from typing import List, Optional
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import (
BaseMessage,
_message_to_dict,
messages_from_dict,
messages_to_dict,
)
logger = logging.g... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
b71ecb086f8d-1 | response = self.table.get_item(Key={"SessionId": self.session_id})
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(err... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
3801fe2aae1f-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,
)
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
3801fe2aae1f-1 | :param credential: The credential to use to authenticate to Azure Cosmos DB.
: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 Cosm... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
3801fe2aae1f-2 | """Prepare the CosmosDB client.
Use this function or the context manager to make sure your database is ready.
"""
try:
from azure.cosmos import ( # pylint: disable=import-outside-toplevel # noqa: E501
PartitionKey,
)
except ImportError as exc:
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
3801fe2aae1f-3 | CosmosHttpResponseError,
)
except ImportError as exc:
raise ImportError(
"You must install the azure-cosmos package to use the CosmosDBChatMessageHistory." # noqa: E501
"Please install it with `pip install azure-cosmos`."
) from exc
tr... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cosmos_db.html |
cc39a4cfd37b-0 | Source code for langchain.memory.chat_message_histories.cassandra
"""Cassandra-based chat message history, based on cassIO."""
from __future__ import annotations
import json
import typing
from typing import List
if typing.TYPE_CHECKING:
from cassandra.cluster import Session
from langchain.schema import (
BaseCh... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
cc39a4cfd37b-1 | @property
def messages(self) -> List[BaseMessage]: # type: ignore
"""Retrieve all session messages from DB"""
message_blobs = self.blob_history.retrieve(
self.session_id,
)
items = [json.loads(message_blob) for message_blob in message_blobs]
messages = messages_f... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
ed817ab14480-0 | Source code for langchain.memory.chat_message_histories.momento
from __future__ import annotations
import json
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Optional
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage, _message_to_dict, ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
ed817ab14480-1 | Note: to instantiate the cache client passed to MomentoChatMessageHistory,
you must have a Momento account at https://gomomento.com/.
Args:
session_id (str): The session ID to use for this chat session.
cache_client (CacheClient): The Momento cache client.
cache_name ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
ed817ab14480-2 | def from_client_params(
cls,
session_id: str,
cache_name: str,
ttl: timedelta,
*,
configuration: Optional[momento.config.Configuration] = None,
auth_token: Optional[str] = None,
**kwargs: Any,
) -> MomentoChatMessageHistory:
"""Construct cache ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
ed817ab14480-3 | return []
elif isinstance(fetch_response, CacheListFetch.Error):
raise fetch_response.inner_exception
else:
raise Exception(f"Unexpected response: {fetch_response}")
[docs] def add_message(self, message: BaseMessage) -> None:
"""Store a message in the cache.
Ar... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
85bf5d002edb-0 | Source code for langchain.memory.chat_message_histories.redis
import json
import logging
from typing import List, Optional
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict
from langchain.utilities.redis import get_client... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
85bf5d002edb-1 | [docs] def add_message(self, message: BaseMessage) -> None:
"""Append the message to the record in Redis"""
self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message)))
if self.ttl:
self.redis_client.expire(self.key, self.ttl)
[docs] def clear(self) -> None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.