id
stringlengths
14
15
text
stringlengths
44
2.47k
source
stringlengths
61
181
b8bbb36efad6-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
b9c9ea6ce6f4-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/summary_buffer.html
b9c9ea6ce6f4-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
78b0f8e4d17b-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
78b0f8e4d17b-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
78b0f8e4d17b-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
623a9a456fb3-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_memory.html
87662a4dfbb2-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html
87662a4dfbb2-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/combined.html
b9afd16718e6-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_...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
b9afd16718e6-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
b9afd16718e6-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 = ""
https://api.python.langchain.com/en/latest/_modules/langchain/memory/buffer.html
0a57a17d2f5c-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
0a57a17d2f5c-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/token_buffer.html
d2166fe3b8b1-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
d2166fe3b8b1-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
5a798d71ec0e-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/entity.html
5a798d71ec0e-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
5a798d71ec0e-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
5a798d71ec0e-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
5a798d71ec0e-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
5a798d71ec0e-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
5a798d71ec0e-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
5a798d71ec0e-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
5a798d71ec0e-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
ce8276672557-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
08cd8cd34b60-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
08cd8cd34b60-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
08cd8cd34b60-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
08cd8cd34b60-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
4a336a56d1f0-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
4a336a56d1f0-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
0f309697e27c-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
0f309697e27c-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, ):...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
0f309697e27c-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
0f309697e27c-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html
dbc206458d68-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html
dbc206458d68-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"...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html
dbc206458d68-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}") ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/xata.html
74ef6458997a-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_...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html
951d47398325-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
951d47398325-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
951d47398325-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
951d47398325-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
5abab1f958c2-0
Source code for langchain.memory.chat_message_histories.in_memory from typing import List from langchain.pydantic_v1 import BaseModel, Field from langchain.schema import ( BaseChatMessageHistory, ) from langchain.schema.messages import BaseMessage [docs]class ChatMessageHistory(BaseChatMessageHistory, BaseModel): ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/in_memory.html
271ec30800c9-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
271ec30800c9-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
76b6c52bcf5a-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
76b6c52bcf5a-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
76b6c52bcf5a-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
76b6c52bcf5a-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
4ebae76a1255-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
4ebae76a1255-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
d2b14a43c994-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
d2b14a43c994-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
91fe2f6182a2-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
91fe2f6182a2-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
335770302d75-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
335770302d75-1
if (curr - start).total_seconds() * 1000 > timeout: raise TimeoutError(f"{method} timed out at {timeout} ms") sleep(RocksetChatMessageHistory.SLEEP_INTERVAL_MS / 1000) def _query(self, query: str, **query_params: Any) -> List[Any]: """Executes an SQL statement and returns the res...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
335770302d75-2
"""Sleeps until the collection for this message history is ready to be queried """ self._wait_until( lambda: self._collection_is_ready(), RocksetChatMessageHistory.CREATE_TIMEOUT_MS, ) def _wait_until_message_added(self, message_id: str) -> None: """Sl...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
335770302d75-3
"""Constructs a new RocksetChatMessageHistory. Args: - session_id: The ID of the chat session - client: The RocksetClient object to use to query - collection: The name of the collection to use to store chat messages. If a collection with the given na...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
335770302d75-4
self.location = f'"{self.workspace}"."{self.collection}"' self.rockset = rockset self.messages_key = messages_key self.message_uuid_method = message_uuid_method self.sync = sync try: self.client.set_application("langchain") except AttributeError: #...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
335770302d75-5
value=_message_to_dict(message), ) ], ) ], ) if self.sync: self._wait_until_message_added(message.additional_kwargs["id"]) [docs] def clear(self) -> None: """Removes all messages from the chat history""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
cd09fb6ff4bd-0
Source code for langchain.memory.chat_message_histories.streamlit from typing import List from langchain.schema import ( BaseChatMessageHistory, ) from langchain.schema.messages import BaseMessage [docs]class StreamlitChatMessageHistory(BaseChatMessageHistory): """ Chat message history that stores messages ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/streamlit.html
9d499f2a21e3-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html
9d499f2a21e3-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...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html
9d499f2a21e3-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 """...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html
25bb86821cd0-0
Source code for langchain.chains.example_generator from typing import List from langchain.chains.llm import LLMChain from langchain.prompts.few_shot import FewShotPromptTemplate from langchain.prompts.prompt import PromptTemplate from langchain.schema.language_model import BaseLanguageModel TEST_GEN_TEMPLATE_SUFFIX = "...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/example_generator.html
286330753705-0
Source code for langchain.chains.sequential """Chain pipeline where the outputs of one step feed directly into next.""" from typing import Any, Dict, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.chains.base import Chain fr...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
286330753705-1
overlapping_keys = set(input_variables) & set(memory_keys) raise ValueError( f"The the input key(s) {''.join(overlapping_keys)} are found " f"in the Memory keys ({memory_keys}) - please use input and " f"memory keys that don't overlap." ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
286330753705-2
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() for i, chain in enumerate(self.chains): callbacks = _run_manager.get_child() outputs = chain(known_values, return_only_outputs=True, callbacks=callbacks) known_values.update(outputs) return {k...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
286330753705-3
"""Return output key. :meta private: """ return [self.output_key] @root_validator() def validate_chains(cls, values: Dict) -> Dict: """Validate that chains are all single input/output.""" for chain in values["chains"]: if len(chain.input_keys) != 1: ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
286330753705-4
run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Dict[str, Any]: _run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager() _input = inputs[self.input_key] color_mapping = get_color_mapping([str(i) for i in range(len(self.chains))]) for i, cha...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/sequential.html
ffe7ddd31003-0
Source code for langchain.chains.mapreduce """Map-reduce chain. Splits up a document, sends the smaller parts to the LLM with one prompt, then combines the results with another one. """ from __future__ import annotations from typing import Any, Dict, List, Mapping, Optional from langchain.callbacks.manager import Callb...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
ffe7ddd31003-1
**kwargs: Any, ) -> MapReduceChain: """Construct a map-reduce chain that uses the chain for map and reduce.""" llm_chain = LLMChain(llm=llm, prompt=prompt, callbacks=callbacks) stuff_chain = StuffDocumentsChain( llm_chain=llm_chain, callbacks=callbacks, **...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
ffe7ddd31003-2
# Split the larger text into smaller chunks. doc_text = inputs.pop(self.input_key) texts = self.text_splitter.split_text(doc_text) docs = [Document(page_content=text) for text in texts] _inputs: Dict[str, Any] = { **inputs, self.combine_documents_chain.input_key: ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/mapreduce.html
2f8b542e2393-0
Source code for langchain.chains.transform """Chain that runs an arbitrary python function.""" import functools import logging from typing import Any, Awaitable, Callable, Dict, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/transform.html
2f8b542e2393-1
"""Return output keys. :meta private: """ return self.output_variables def _call( self, inputs: Dict[str, str], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: return self.transform_cb(inputs) async def _acall( se...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/transform.html
86aa1fb083c2-0
Source code for langchain.chains.llm """Chain that just formats a prompt and calls an LLM.""" from __future__ import annotations import warnings from typing import Any, Dict, List, Optional, Sequence, Tuple, Union from langchain.callbacks.manager import ( AsyncCallbackManager, AsyncCallbackManagerForChainRun, ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html
86aa1fb083c2-1
output_key: str = "text" #: :meta private: output_parser: BaseLLMOutputParser = Field(default_factory=StrOutputParser) """Output parser to use. Defaults to one that takes the most likely string but does not change it otherwise.""" return_final_only: bool = True """Whether to return only the fi...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html
86aa1fb083c2-2
) -> LLMResult: """Generate LLM result from inputs.""" prompts, stop = self.prep_prompts(input_list, run_manager=run_manager) return self.llm.generate_prompt( prompts, stop, callbacks=run_manager.get_child() if run_manager else None, **self.llm_kwa...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html
86aa1fb083c2-3
_text = "Prompt after formatting:\n" + _colored_text if run_manager: run_manager.on_text(_text, end="\n", verbose=self.verbose) if "stop" in inputs and inputs["stop"] != stop: raise ValueError( "If `stop` is present in any inputs, should be pre...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html
86aa1fb083c2-4
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None ) -> List[Dict[str, str]]: """Utilize the LLM generate method for speed gains.""" callback_manager = CallbackManager.configure( callbacks, self.callbacks, self.verbose ) run_manager = callback_manager.on_...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html
86aa1fb083c2-5
"""Create outputs from response.""" result = [ # Get the text of the top generated string. { self.output_key: self.output_parser.parse_result(generation), "full_generation": generation, } for generation in llm_result.generations ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html
86aa1fb083c2-6
completion = llm.predict(adjective="funny") """ return (await self.acall(kwargs, callbacks=callbacks))[self.output_key] [docs] def predict_and_parse( self, callbacks: Callbacks = None, **kwargs: Any ) -> Union[str, List[str], Dict[str, Any]]: """Call predict and then parse the res...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html
86aa1fb083c2-7
"instead pass an output parser directly to LLMChain." ) result = self.apply(input_list, callbacks=callbacks) return self._parse_generation(result) def _parse_generation( self, generation: List[Dict[str, str]] ) -> Sequence[Union[str, List[str], Dict[str, str]]]: if self.p...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html
37232718fcd2-0
Source code for langchain.chains.moderation """Pass input through a moderation endpoint.""" from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.pydantic_v1 import root_validator from langchain.utils import...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
37232718fcd2-1
values, "openai_organization", "OPENAI_ORGANIZATION", default="", ) try: import openai openai.api_key = openai_api_key if openai_organization: openai.organization = openai_organization values["client"] = ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html
0c3ea932b161-0
Source code for langchain.chains.base """Base interface that all chains should implement.""" import asyncio import inspect import json import logging import warnings from abc import ABC, abstractmethod from functools import partial from pathlib import Path from typing import Any, Dict, List, Optional, Type, Union impor...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-1
Chains with other components, including other Chains. The main methods exposed by chains are: - `__call__`: Chains are callable. The `__call__` method is the primary way to execute a Chain. This takes inputs as a dictionary and returns a dictionary output. - `run`: A convenie...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-2
) [docs] async def ainvoke( self, input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any, ) -> Dict[str, Any]: if type(self)._acall == Chain._acall: # If the chain does not implement async, fall back to default implementation ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-3
verbose: bool = Field(default_factory=_get_verbosity) """Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to `langchain.verbose` value.""" tags: Optional[List[str]] = None """Optional list of tags associated with the chain. Defaults to ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-4
DeprecationWarning, ) values["callbacks"] = values.pop("callback_manager", None) return values @validator("verbose", pre=True, always=True) def set_verbose(cls, verbose: Optional[bool]) -> bool: """Set the chain verbosity. Defaults to the global setting if not spe...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-5
callbacks configuration and some input/output processing. Args: inputs: A dict of named inputs to the chain. Assumed to contain all inputs specified in `Chain.input_keys`, including any inputs added by memory. run_manager: The callbacks manager that contains the callback ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-6
include_run_info: bool = False, ) -> Dict[str, Any]: """Execute the chain. Args: inputs: Dictionary of inputs, or single input if chain expects only one param. Should contain all inputs specified in `Chain.input_keys` except for inputs that will be set by ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-7
name=run_name, ) try: outputs = ( self._call(inputs, run_manager=run_manager) if new_arg_supported else self._call(inputs) ) except BaseException as e: run_manager.on_chain_error(e) raise e ru...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-8
addition to callbacks passed to the chain during construction, but only these runtime callbacks will propagate to calls to other objects. tags: List of string tags to pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-9
self, inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False, ) -> Dict[str, str]: """Validate and prepare chain outputs, and save info about this run to memory. Args: inputs: Dictionary of chain inputs, including any inputs added by ch...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-10
_input_keys = _input_keys.difference(self.memory.memory_variables) if len(_input_keys) != 1: raise ValueError( f"A single string input was passed in, but this chain expects " f"multiple inputs ({_input_keys}). When a chain expects " ...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html
0c3ea932b161-11
sole positional argument. callbacks: Callbacks to use for this chain run. These will be called in addition to callbacks passed to the chain during construction, but only these runtime callbacks will propagate to calls to other objects. tags: List of string tags to...
https://api.python.langchain.com/en/latest/_modules/langchain/chains/base.html