id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
0526c91229e3-2 | response_time: The response time of the query.
answer: The answer to the query.
images: A list of images.
results: A list of dictionaries containing the results:
title: The title of the result.
url: The url of the result.
content: The c... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html |
0526c91229e3-3 | "include_domains": include_domains,
"exclude_domains": exclude_domains,
"include_answer": include_answer,
"include_raw_content": include_raw_content,
"include_images": include_images,
}
async with aiohttp.ClientSession() as session:... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html |
0526c91229e3-4 | for result in results:
clean_results.append(
{
"url": result["url"],
"content": result["content"],
}
)
return clean_results | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html |
3dcc8af29e2c-0 | Source code for langchain.document_transformers.embeddings_redundant_filter
"""Transform documents"""
from typing import Any, Callable, List, Sequence
import numpy as np
from langchain.pydantic_v1 import BaseModel, Field
from langchain.schema import BaseDocumentTransformer, Document
from langchain.schema.embeddings imp... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html |
3dcc8af29e2c-1 | redundant_stacked = np.column_stack(redundant)
redundant_sorted = np.argsort(similarity[redundant])[::-1]
included_idxs = set(range(len(embedded_documents)))
for first_idx, second_idx in redundant_stacked[redundant_sorted]:
if first_idx in included_idxs and second_idx in included_idxs:
#... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html |
3dcc8af29e2c-2 | )
closest_indices = []
# Loop through the number of clusters you have
for i in range(num_clusters):
# Get the list of distances from that particular cluster center
distances = np.linalg.norm(
embedded_documents - kmeans.cluster_centers_[i], axis=1
)
# Find the ind... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html |
3dcc8af29e2c-3 | ) -> Sequence[Document]:
"""Filter down documents."""
stateful_documents = get_stateful_documents(documents)
embedded_documents = _get_embeddings_from_stateful_docs(
self.embeddings, stateful_documents
)
included_idxs = _filter_similar_embeddings(
embedded... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html |
3dcc8af29e2c-4 | clusters.
"""
class Config:
"""Configuration for this pydantic object."""
arbitrary_types_allowed = True
[docs] def transform_documents(
self, documents: Sequence[Document], **kwargs: Any
) -> Sequence[Document]:
"""Filter down documents."""
stateful_documents = ge... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/embeddings_redundant_filter.html |
7953eeb3e7b6-0 | Source code for langchain.document_transformers.nuclia_text_transform
import asyncio
import json
import uuid
from typing import Any, Sequence
from langchain.schema.document import BaseDocumentTransformer, Document
from langchain.tools.nuclia.tool import NucliaUnderstandingAPI
[docs]class NucliaTextTransformer(BaseDocum... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/nuclia_text_transform.html |
8ad6eadd5cbe-0 | Source code for langchain.document_transformers.long_context_reorder
"""Reorder documents"""
from typing import Any, List, Sequence
from langchain.pydantic_v1 import BaseModel
from langchain.schema import BaseDocumentTransformer, Document
def _litm_reordering(documents: List[Document]) -> List[Document]:
"""Lost in... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/long_context_reorder.html |
fada79180ef4-0 | Source code for langchain.document_transformers.beautiful_soup_transformer
from typing import Any, Iterator, List, Sequence, cast
from langchain.schema import BaseDocumentTransformer, Document
[docs]class BeautifulSoupTransformer(BaseDocumentTransformer):
"""Transform HTML content by extracting specific tags and re... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html |
fada79180ef4-1 | Returns:
A sequence of Document objects with transformed content.
"""
for doc in documents:
cleaned_content = doc.page_content
cleaned_content = self.remove_unwanted_tags(cleaned_content, unwanted_tags)
cleaned_content = self.extract_tags(cleaned_content, ... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html |
fada79180ef4-2 | text_parts += get_navigable_strings(element)
# To avoid duplicate text, remove all descendants from the soup.
element.decompose()
return " ".join(text_parts)
[docs] @staticmethod
def remove_unnecessary_lines(content: str) -> str:
"""
Clean up the content by... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/beautiful_soup_transformer.html |
cd232c47fbb9-0 | Source code for langchain.document_transformers.doctran_text_extract
from typing import Any, List, Optional, Sequence
from langchain.schema import BaseDocumentTransformer, Document
from langchain.utils import get_from_env
[docs]class DoctranPropertyExtractor(BaseDocumentTransformer):
"""Extract properties from text... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_extract.html |
cd232c47fbb9-1 | transformed_document = await qa_transformer.atransform_documents(documents)
""" # noqa: E501
[docs] def __init__(
self,
properties: List[dict],
openai_api_key: Optional[str] = None,
openai_api_model: Optional[str] = None,
) -> None:
self.properties = properties
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_extract.html |
0d189c0a99a1-0 | Source code for langchain.document_transformers.google_translate
from typing import Any, Optional, Sequence
from langchain.schema import BaseDocumentTransformer, Document
from langchain.utilities.vertexai import get_client_info
[docs]class GoogleTranslateTransformer(BaseDocumentTransformer):
"""Translate text docum... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/google_translate.html |
0d189c0a99a1-1 | self._model_path = (
f"{self._parent_path}/models/{model_id}" if model_id else None
)
self._glossary_path = (
self._client.glossary_path(project_id, location, glossary_id)
if glossary_id
else None
)
[docs] def transform_documents(
self, ... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/google_translate.html |
0d189c0a99a1-2 | translations = response.glossary_translations or response.translations
return [
Document(
page_content=translation.translated_text,
metadata={
**doc.metadata,
"model": translation.model,
"detected_language_co... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/google_translate.html |
7769ffb5208b-0 | Source code for langchain.document_transformers.html2text
from typing import Any, Sequence
from langchain.schema import BaseDocumentTransformer, Document
[docs]class Html2TextTransformer(BaseDocumentTransformer):
"""Replace occurrences of a particular search pattern with a replacement string
Arguments:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/html2text.html |
fc7869759580-0 | Source code for langchain.document_transformers.doctran_text_qa
from typing import Any, Optional, Sequence
from langchain.schema import BaseDocumentTransformer, Document
from langchain.utils import get_from_env
[docs]class DoctranQATransformer(BaseDocumentTransformer):
"""Extract QA from text documents using doctra... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_qa.html |
fc7869759580-1 | from doctran import Doctran
doctran = Doctran(
openai_api_key=self.openai_api_key, openai_model=self.openai_api_model
)
except ImportError:
raise ImportError(
"Install doctran to use this parser. (pip install doctran)"
)
for... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_qa.html |
331b42cec089-0 | Source code for langchain.document_transformers.openai_functions
"""Document transformers that use OpenAI Functions models"""
from typing import Any, Dict, Optional, Sequence, Type, Union
from langchain.chains.llm import LLMChain
from langchain.chains.openai_functions import create_tagging_chain
from langchain.prompts ... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html |
331b42cec089-1 | original_documents = [
Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\nThis is the greatest movie ever made. 4 out of 5 stars."),
Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html |
331b42cec089-2 | """Create a DocumentTransformer that uses an OpenAI function chain to automatically
tag documents with metadata based on their content and an input schema.
Args:
metadata_schema: Either a dictionary or pydantic.BaseModel class. If a dictionary
is passed in, it's assumed to already be a v... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html |
331b42cec089-3 | original_documents = [
Document(page_content="Review of The Bee Movie\nBy Roger Ebert\n\nThis is the greatest movie ever made. 4 out of 5 stars."),
Document(page_content="Review of The Godfather\nBy Anonymous\n\nThis movie was super boring. 1 out of 5 stars.", metadata={"reliable... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/openai_functions.html |
7c0758e80d18-0 | Source code for langchain.document_transformers.doctran_text_translate
from typing import Any, Optional, Sequence
from langchain.schema import BaseDocumentTransformer, Document
from langchain.utils import get_from_env
[docs]class DoctranTextTranslator(BaseDocumentTransformer):
"""Translate text documents using doct... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_translate.html |
7c0758e80d18-1 | """Translates text documents using doctran."""
try:
from doctran import Doctran
doctran = Doctran(
openai_api_key=self.openai_api_key, openai_model=self.openai_api_model
)
except ImportError:
raise ImportError(
"Install doct... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_transformers/doctran_text_translate.html |
8d069e10b077-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
8d069e10b077-1 | """Save context from this conversation to buffer. Pruned."""
super().save_context(inputs, outputs)
# Prune buffer if it exceeds max token limit
buffer = self.chat_memory.messages
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)
if curr_buffer_length > self.max_t... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html |
bd3551500197-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 langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.prompt import (
ENTIT... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-2 | self.redis_client = Redis(url=url, token=token)
except Exception:
logger.error("Upstash Redis instance could not be initiated.")
self.session_id = session_id
self.key_prefix = key_prefix
self.ttl = ttl
self.recall_ttl = recall_ttl or ttl
@property
def full_key... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-3 | cursor, f"{self.full_key_prefix}:*"
)
self.redis_client.delete(*keys_to_delete)
return cursor
cursor = scan_and_delete(0)
while cursor != 0:
scan_and_delete(cursor)
[docs]class RedisEntityStore(BaseEntityStore):
"""Redis-backed Entity store.
Entiti... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-4 | 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.session_id}"
[docs] def get(self, key: str, default: Optional[str] = None) -> Optional[str]:
res = (
self.re... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-5 | ):
self.redis_client.delete(*keybatch)
[docs]class SQLiteEntityStore(BaseEntityStore):
"""SQLite-backed Entity store"""
session_id: str = "default"
table_name: str = "memory_store"
def __init__(
self,
session_id: str = "default",
db_file: str = "entities.db",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-6 | 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:
return self.delete(key)
query = f"""
INSERT OR REPLACE INTO {self.full_table_name} (key, value)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-7 | ai_prefix: str = "AI"
llm: BaseLanguageModel
entity_extraction_prompt: BasePromptTemplate = ENTITY_EXTRACTION_PROMPT
entity_summarization_prompt: BasePromptTemplate = ENTITY_SUMMARIZATION_PROMPT
# Cache of recently detected entity names, if any
# It is updated when load_memory_variables is called:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-8 | 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 message pairs:
buffer_string = get_buffer_string(
self.buffer[-self.k * 2 :],
human_p... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
bd3551500197-9 | "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.
Generates a summary for each entity in the entity cache by prompting
the model, and save... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html |
8a5b247e50d6-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/simple.html |
7c80949d99b0-0 | Source code for langchain.memory.chat_memory
from abc import ABC
from typing import Any, Dict, Optional, Tuple
from langchain.memory.chat_message_histories.in_memory import ChatMessageHistory
from langchain.memory.utils import get_prompt_input_key
from langchain.pydantic_v1 import Field
from langchain.schema import Bas... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_memory.html |
797e9345f538-0 | Source code for langchain.memory.vectorstore
"""Class for a VectorStore-backed memory object."""
from typing import Any, Dict, List, Optional, Sequence, Union
from langchain.memory.chat_memory import BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.pydantic_v1 import Field
from langchai... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
797e9345f538-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])... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/vectorstore.html |
f56858e40ec3-0 | Source code for langchain.memory.utils
from typing import Any, Dict, List
[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_variables: List[str]
Returns:
A prompt input key... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/utils.html |
348e0ddcc6d9-0 | Source code for langchain.memory.kg
from typing import Any, Dict, List, Type, Union
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_memory import BaseChatMemory
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
348e0ddcc6d9-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:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
348e0ddcc6d9-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
348e0ddcc6d9-3 | [docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.kg.clear() | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/kg.html |
9370a9f990a1-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]:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/readonly.html |
37df16887c52-0 | Source code for langchain.memory.buffer_window
from typing import Any, Dict, List, Union
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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/buffer_window.html |
7290b1c538ce-0 | Source code for langchain.memory.summary
from __future__ import annotations
from typing import Any, Dict, List, Type
from langchain.chains.llm import LLMChain
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.prompt import SUMMARY_PROMPT
from langchain.pydantic_v1 import BaseModel, root_vali... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
7290b1c538ce-1 | *,
summarize_step: int = 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.message... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
7290b1c538ce-2 | self.chat_memory.messages[-2:], self.buffer
)
[docs] def clear(self) -> None:
"""Clear memory contents."""
super().clear()
self.buffer = "" | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary.html |
974a2cd11658-0 | Source code for langchain.memory.buffer
from typing import Any, Dict, List, Optional
from langchain.memory.chat_memory import BaseChatMemory, BaseMemory
from langchain.memory.utils import get_prompt_input_key
from langchain.pydantic_v1 import root_validator
from langchain.schema.messages import BaseMessage, get_buffer_... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
974a2cd11658-1 | human_prefix: str = "Human"
ai_prefix: str = "AI"
"""Prefix to use for AI generated responses."""
buffer: str = ""
output_key: Optional[str] = None
input_key: Optional[str] = None
memory_key: str = "history" #: :meta private:
@root_validator()
def validate_chains(cls, values: Dict) -> D... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
974a2cd11658-2 | ai = f"{self.ai_prefix}: " + outputs[output_key]
self.buffer += "\n" + "\n".join([human, ai])
[docs] def clear(self) -> None:
"""Clear memory contents."""
self.buffer = "" | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html |
c2fd94bd440f-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html |
c2fd94bd440f-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html |
c2fd94bd440f-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,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/zep_memory.html |
cdd748b87c56-0 | Source code for langchain.memory.summary_buffer
from typing import Any, Dict, List
from langchain.memory.chat_memory import BaseChatMemory
from langchain.memory.summary import SummarizerMixin
from langchain.pydantic_v1 import root_validator
from langchain.schema.messages import BaseMessage, get_buffer_string
[docs]clas... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
cdd748b87c56-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html |
93e8c77f073e-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]... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
93e8c77f073e-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"])
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/motorhead_memory.html |
42da3b86b934-0 | Source code for langchain.memory.combined
import warnings
from typing import Any, Dict, List, Set
from langchain.memory.chat_memory import BaseChatMemory
from langchain.pydantic_v1 import validator
from langchain.schema import BaseMemory
[docs]class CombinedMemory(BaseMemory):
"""Combining multiple memories' data t... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
42da3b86b934-1 | 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] = {}
# Collect vars fr... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html |
268b210710cb-0 | Source code for langchain.memory.chat_message_histories.xata
import json
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict
[docs]class XataChatMessageHistory(BaseChatMessageHistory):
"""Chat me... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html |
268b210710cb-1 | if r.status_code > 299:
raise Exception(f"Error creating table in Xata: {r.status_code} {r}")
r = self._client.table().set_schema(
self._table_name,
payload={
"columns": [
{"name": "sessionId", "type": "string"},
{"name"... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html |
268b210710cb-2 | self._table_name,
payload={
"filter": {
"sessionId": self._session_id,
},
"sort": {"xata.createdAt": "asc"},
},
)
if r.status_code != 200:
raise Exception(f"Error running query: {r.status_code} {r}")
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html |
fc5cffa32f70-0 | Source code for langchain.memory.chat_message_histories.dynamodb
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Dict, List, Optional
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import (
BaseMessage,
_message_to_dict,
messag... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
fc5cffa32f70-1 | [docs] def __init__(
self,
table_name: str,
session_id: str,
endpoint_url: Optional[str] = None,
primary_key_name: str = "SessionId",
key: Optional[Dict[str, str]] = None,
boto3_session: Optional[Session] = None,
kms_key_id: Optional[str] = None,
):... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
fc5cffa32f70-2 | attribute_actions={"History": CryptoAction.ENCRYPT_AND_SIGN},
)
aws_kms_cmp = AwsKmsCryptographicMaterialsProvider(key_id=kms_key_id)
self.table = EncryptedTable(
table=self.table,
materials_provider=aws_kms_cmp,
attribute_actions=actio... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
fc5cffa32f70-3 | messages.append(_message)
try:
self.table.put_item(Item={**self.key, "History": messages})
except ClientError as err:
logger.error(err)
[docs] def clear(self) -> None:
"""Clear session memory from DynamoDB"""
try:
from botocore.exceptions import Cli... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
6c5c4b3270de-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
6c5c4b3270de-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
42a95f78e2df-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,... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
42a95f78e2df-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-... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
42a95f78e2df-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
42a95f78e2df-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
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/zep.html |
4a0fb584adea-0 | Source code for langchain.memory.chat_message_histories.neo4j
from typing import List, Optional, Union
from langchain.schema import BaseChatMessageHistory
from langchain.schema.messages import BaseMessage, messages_from_dict
from langchain.utils import get_from_env
[docs]class Neo4jChatMessageHistory(BaseChatMessageHis... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/neo4j.html |
4a0fb584adea-1 | # Verify connection
try:
self._driver.verify_connectivity()
except neo4j.exceptions.ServiceUnavailable:
raise ValueError(
"Could not connect to Neo4j database. "
"Please ensure that the url is correct"
)
except neo4j.exceptions.... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/neo4j.html |
4a0fb584adea-2 | """Append the message to the record in Neo4j"""
query = (
f"MATCH (s:`{self._node_label}`) WHERE s.id = $session_id "
"OPTIONAL MATCH (s)-[lm:LAST_MESSAGE]->(last_message) "
"CREATE (s)-[:LAST_MESSAGE]->(new:Message) "
"SET new += {type:$type, content:$content} "
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/neo4j.html |
6f9ce0f02c0a-0 | Source code for langchain.memory.chat_message_histories.postgres
import json
import logging
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict
logger = logging.getLogger(__name__)
DEFAULT_CONNECTION... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
6f9ce0f02c0a-1 | items = [record["message"] for record in self.cursor.fetchall()]
messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message: BaseMessage) -> None:
"""Append the message to the record in PostgreSQL"""
from psycopg import sql
query = sql.SQL("INSER... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
896bd78b095f-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,
)
from langchain.schema.messages import BaseMessage, messages_from_dict, messages_to_dict
logger = logging.getLogger(__name_... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
56393c1a38d8-0 | Source code for langchain.memory.chat_message_histories.singlestoredb
import json
import logging
import re
from typing import (
Any,
List,
)
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict
logger = logging.getLo... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html |
56393c1a38d8-1 | max_overflow (int, optional): Determines the maximum number of connections
allowed beyond the pool_size. Defaults to 10.
timeout (float, optional): Specifies the maximum wait time in seconds for
establishing a connection. Defaults to 30.
Following arguments pertai... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html |
56393c1a38d8-2 | conv (dict[int, Callable], optional): A dictionary of data conversion
functions.
credential_type (str, optional): Specifies the type of authentication to
use: auth.PASSWORD, auth.JWT, or auth.BROWSER_SSO.
autocommit (bool, optional): Enables autocommits.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html |
56393c1a38d8-3 | message_history = SingleStoreDBChatMessageHistory("my-session")
"""
self.table_name = self._sanitize_input(table_name)
self.session_id = self._sanitize_input(session_id)
self.id_field = self._sanitize_input(id_field)
self.session_id_field = self._sanitize_input(session_id_field)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html |
56393c1a38d8-4 | "Please install it with `pip install singlestoredb`."
)
return s2.connect(**self.connection_kwargs)
def _create_table_if_not_exists(self) -> None:
"""Create table if it doesn't exist."""
if self.table_created:
return
conn = self.connection_pool.connect()
... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html |
56393c1a38d8-5 | self._create_table_if_not_exists()
conn = self.connection_pool.connect()
try:
cur = conn.cursor()
try:
cur.execute(
"""INSERT INTO {} ({}, {}) VALUES (%s, %s)""".format(
self.table_name,
self.sess... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/singlestoredb.html |
b5295fc1031b-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/firestore.html |
b5295fc1031b-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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/firestore.html |
a6e7c4ceddd3-0 | Source code for langchain.memory.chat_message_histories.sql
import json
import logging
from abc import ABC, abstractmethod
from typing import Any, List, Optional
from sqlalchemy import Column, Integer, Text, create_engine
try:
from sqlalchemy.orm import declarative_base
except ImportError:
from sqlalchemy.ext.d... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
a6e7c4ceddd3-1 | id = Column(Integer, primary_key=True)
session_id = Column(Text)
message = Column(Text)
return Message
[docs]class DefaultMessageConverter(BaseMessageConverter):
"""The default message converter for SQLChatMessageHistory."""
[docs] def __init__(self, table_name: str):
self.model_class... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
a6e7c4ceddd3-2 | self._create_table_if_not_exists()
self.session_id = session_id
self.Session = sessionmaker(self.engine)
def _create_table_if_not_exists(self) -> None:
self.sql_model_class.metadata.create_all(self.engine)
@property
def messages(self) -> List[BaseMessage]: # type: ignore
"""... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
97c711df09c0-0 | Source code for langchain.memory.chat_message_histories.mongodb
import json
import logging
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
)
from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict
logger = logging.getLogger(__name__)
DEFAULT_DBNAME = "c... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
97c711df09c0-1 | except errors.OperationFailure as error:
logger.error(error)
if cursor:
items = [json.loads(document["History"]) for document in cursor]
else:
items = []
messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message: Base... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
b5faf7a4c7c5-0 | Source code for langchain.memory.chat_message_histories.upstash_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
logger = logging.getLogger(__name__)
[do... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/upstash_redis.html |
b5faf7a4c7c5-1 | _items = self.redis_client.lrange(self.key, 0, -1)
items = [json.loads(m) for m in _items[::-1]]
messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message: BaseMessage) -> None:
"""Append the message to the record in Upstash Redis"""
self.redis_... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/upstash_redis.html |
5aeb50531ce9-0 | Source code for langchain.memory.chat_message_histories.rocksetdb
from datetime import datetime
from time import sleep
from typing import Any, Callable, List, Union
from uuid import uuid4
from langchain.schema import BaseChatMessageHistory
from langchain.schema.messages import BaseMessage, _message_to_dict, messages_fr... | lang/api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.