id
stringlengths
14
15
text
stringlengths
13
2.7k
source
stringlengths
60
181
49296d880c7b-3
updated_at field is at least this time. Raises ValueError – If the length of keys doesn’t match the length of group_ids.
https://api.python.langchain.com/en/latest/indexes/langchain_community.indexes.base.RecordManager.html
9397ccbf9bee-0
langchain.indexes.graph.GraphIndexCreator¶ class langchain.indexes.graph.GraphIndexCreator[source]¶ Bases: BaseModel Functionality to create graph index. Create a new model by parsing and validating input data from keyword arguments. Raises ValidationError if the input data cannot be parsed to form a valid model. param graph_type: Type[langchain_community.graphs.networkx_graph.NetworkxEntityGraph] = <class 'langchain_community.graphs.networkx_graph.NetworkxEntityGraph'>¶ param llm: Optional[langchain_core.language_models.base.BaseLanguageModel] = None¶
https://api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html
9397ccbf9bee-1
param llm: Optional[langchain_core.language_models.base.BaseLanguageModel] = None¶ async afrom_text(text: str, prompt: BasePromptTemplate = PromptTemplate(input_variables=['text'], template="You are a networked intelligence helping a human track knowledge triples about all relevant people, things, concepts, etc. and integrating them with your knowledge stored within your weights as well as that stored in a knowledge graph. Extract all of the knowledge triples from the text. A knowledge triple is a clause that contains a subject, a predicate, and an object. The subject is the entity being described, the predicate is the property of the subject that is being described, and the object is the value of the property.\n\nEXAMPLE\nIt's a state in the US. It's also the number 1 producer of gold in the US.\n\nOutput: (Nevada, is a, state)<|>(Nevada, is in, US)<|>(Nevada, is the number 1 producer of, gold)\nEND OF EXAMPLE\n\nEXAMPLE\nI'm going to the store.\n\nOutput: NONE\nEND OF EXAMPLE\n\nEXAMPLE\nOh huh. I know Descartes likes to drive antique scooters and play the mandolin.\nOutput: (Descartes, likes to drive, antique scooters)<|>(Descartes, plays, mandolin)\nEND OF EXAMPLE\n\nEXAMPLE\n{text}Output:")) → NetworkxEntityGraph[source]¶ Create graph index from text asynchronously. classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values
https://api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html
9397ccbf9bee-2
Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html
9397ccbf9bee-3
classmethod from_orm(obj: Any) → Model¶ from_text(text: str, prompt: BasePromptTemplate = PromptTemplate(input_variables=['text'], template="You are a networked intelligence helping a human track knowledge triples about all relevant people, things, concepts, etc. and integrating them with your knowledge stored within your weights as well as that stored in a knowledge graph. Extract all of the knowledge triples from the text. A knowledge triple is a clause that contains a subject, a predicate, and an object. The subject is the entity being described, the predicate is the property of the subject that is being described, and the object is the value of the property.\n\nEXAMPLE\nIt's a state in the US. It's also the number 1 producer of gold in the US.\n\nOutput: (Nevada, is a, state)<|>(Nevada, is in, US)<|>(Nevada, is the number 1 producer of, gold)\nEND OF EXAMPLE\n\nEXAMPLE\nI'm going to the store.\n\nOutput: NONE\nEND OF EXAMPLE\n\nEXAMPLE\nOh huh. I know Descartes likes to drive antique scooters and play the mandolin.\nOutput: (Descartes, likes to drive, antique scooters)<|>(Descartes, plays, mandolin)\nEND OF EXAMPLE\n\nEXAMPLE\n{text}Output:")) → NetworkxEntityGraph[source]¶ Create graph index from text.
https://api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html
9397ccbf9bee-4
Create graph index from text. json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using GraphIndexCreator¶ Graph QA
https://api.python.langchain.com/en/latest/indexes/langchain.indexes.graph.GraphIndexCreator.html
114fe4d5008e-0
langchain.indexes.vectorstore.VectorStoreIndexWrapper¶ class langchain.indexes.vectorstore.VectorStoreIndexWrapper[source]¶ Bases: BaseModel Wrapper around a vectorstore for easy access. Create a new model by parsing and validating input data from keyword arguments. Raises ValidationError if the input data cannot be parsed to form a valid model. param vectorstore: langchain_core.vectorstores.VectorStore [Required]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance
https://api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorStoreIndexWrapper.html
114fe4d5008e-1
deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
https://api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorStoreIndexWrapper.html
114fe4d5008e-2
query(question: str, llm: Optional[BaseLanguageModel] = None, retriever_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) → str[source]¶ Query the vectorstore. query_with_sources(question: str, llm: Optional[BaseLanguageModel] = None, retriever_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any) → dict[source]¶ Query the vectorstore and get back sources. classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶
https://api.python.langchain.com/en/latest/indexes/langchain.indexes.vectorstore.VectorStoreIndexWrapper.html
82040ac9ae8d-0
langchain_core.caches.BaseCache¶ class langchain_core.caches.BaseCache[source]¶ Base interface for cache. Methods __init__() clear(**kwargs) Clear cache that can take additional keyword arguments. lookup(prompt, llm_string) Look up based on prompt and llm_string. update(prompt, llm_string, return_val) Update cache based on prompt and llm_string. __init__()¶ abstract clear(**kwargs: Any) → None[source]¶ Clear cache that can take additional keyword arguments. abstract lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶ Look up based on prompt and llm_string. abstract update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶ Update cache based on prompt and llm_string.
https://api.python.langchain.com/en/latest/caches/langchain_core.caches.BaseCache.html
71392697cf89-0
langchain_community.chat_message_histories.sql.SQLChatMessageHistory¶ class langchain_community.chat_message_histories.sql.SQLChatMessageHistory(session_id: str, connection_string: str, table_name: str = 'message_store', session_id_field_name: str = 'session_id', custom_message_converter: Optional[BaseMessageConverter] = None)[source]¶ Chat message history stored in an SQL database. Attributes messages Retrieve all messages from db Methods __init__(session_id, connection_string[, ...]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in db add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from db __init__(session_id: str, connection_string: str, table_name: str = 'message_store', session_id_field_name: str = 'session_id', custom_message_converter: Optional[BaseMessageConverter] = None)[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in db add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from db Examples using SQLChatMessageHistory¶ SQL Chat Message History
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.sql.SQLChatMessageHistory.html
3b2c0ab2adf3-0
langchain_community.chat_message_histories.sql.BaseMessageConverter¶ class langchain_community.chat_message_histories.sql.BaseMessageConverter[source]¶ The class responsible for converting BaseMessage to your SQLAlchemy model. Methods __init__() from_sql_model(sql_message) Convert a SQLAlchemy model to a BaseMessage instance. get_sql_model_class() Get the SQLAlchemy model class. to_sql_model(message, session_id) Convert a BaseMessage instance to a SQLAlchemy model. __init__()¶ abstract from_sql_model(sql_message: Any) → BaseMessage[source]¶ Convert a SQLAlchemy model to a BaseMessage instance. abstract get_sql_model_class() → Any[source]¶ Get the SQLAlchemy model class. abstract to_sql_model(message: BaseMessage, session_id: str) → Any[source]¶ Convert a BaseMessage instance to a SQLAlchemy model. Examples using BaseMessageConverter¶ SQL Chat Message History
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.sql.BaseMessageConverter.html
aba64062dd13-0
langchain_community.chat_message_histories.file.FileChatMessageHistory¶ class langchain_community.chat_message_histories.file.FileChatMessageHistory(file_path: str)[source]¶ Chat message history that stores history in a local file. Parameters file_path – path of the local file to store the messages. Attributes messages Retrieve the messages from the local file Methods __init__(file_path) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in the local file add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from the local file __init__(file_path: str)[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in the local file add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from the local file Examples using FileChatMessageHistory¶ AutoGPT
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.file.FileChatMessageHistory.html
a56246fc509a-0
langchain_community.chat_message_histories.postgres.PostgresChatMessageHistory¶ class langchain_community.chat_message_histories.postgres.PostgresChatMessageHistory(session_id: str, connection_string: str = 'postgresql://postgres:mypassword@localhost/chat_history', table_name: str = 'message_store')[source]¶ Chat message history stored in a Postgres database. Attributes messages Retrieve the messages from PostgreSQL Methods __init__(session_id[, connection_string, ...]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in PostgreSQL add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from PostgreSQL __init__(session_id: str, connection_string: str = 'postgresql://postgres:mypassword@localhost/chat_history', table_name: str = 'message_store')[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in PostgreSQL add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from PostgreSQL Examples using PostgresChatMessageHistory¶ Postgres Chat Message History
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.postgres.PostgresChatMessageHistory.html
0ef3f02ef1f3-0
langchain_community.chat_message_histories.neo4j.Neo4jChatMessageHistory¶ class langchain_community.chat_message_histories.neo4j.Neo4jChatMessageHistory(session_id: Union[str, int], url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, database: str = 'neo4j', node_label: str = 'Session', window: int = 3)[source]¶ Chat message history stored in a Neo4j database. Attributes messages Retrieve the messages from Neo4j Methods __init__(session_id[, url, username, ...]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in Neo4j add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from Neo4j __init__(session_id: Union[str, int], url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, database: str = 'neo4j', node_label: str = 'Session', window: int = 3)[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in Neo4j add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from Neo4j
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.neo4j.Neo4jChatMessageHistory.html
8c65ca8b9e7c-0
langchain_community.chat_message_histories.rocksetdb.RocksetChatMessageHistory¶ class langchain_community.chat_message_histories.rocksetdb.RocksetChatMessageHistory(session_id: str, client: ~typing.Any, collection: str, workspace: str = 'commons', messages_key: str = 'messages', sync: bool = False, message_uuid_method: ~typing.Callable[[], ~typing.Union[str, int]] = <function RocksetChatMessageHistory.<lambda>>)[source]¶ Uses Rockset to store chat messages. To use, ensure that the rockset python package installed. Example from langchain_community.chat_message_histories import ( RocksetChatMessageHistory ) from rockset import RocksetClient history = RocksetChatMessageHistory( session_id="MySession", client=RocksetClient(), collection="langchain_demo", sync=True ) history.add_user_message("hi!") history.add_ai_message("whats up?") print(history.messages) Constructs a new RocksetChatMessageHistory. Parameters 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 name does not exist in the workspace, it is created. workspace (-) – The workspace containing collection. Defaults to “commons” messages_key (-) – The DB column containing message history. Defaults to “messages” sync (-) – Whether to wait for messages to be added. Defaults to False. NOTE: setting this to True will slow down performance. message_uuid_method (-) – The method that generates message IDs. If set, all messages will have an id field within the
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.rocksetdb.RocksetChatMessageHistory.html
8c65ca8b9e7c-1
If set, all messages will have an id field within the additional_kwargs property. If this param is not set and sync is False, message IDs will not be created. If this param is not set and sync is True, the uuid.uuid4 method will be used to create message IDs. Attributes ADD_TIMEOUT_MS CREATE_TIMEOUT_MS SLEEP_INTERVAL_MS messages Messages in this chat history. Methods __init__(session_id, client, collection[, ...]) Constructs a new RocksetChatMessageHistory. add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Add a Message object to the history. add_user_message(message) Convenience method for adding a human message string to the store. clear() Removes all messages from the chat history __init__(session_id: str, client: ~typing.Any, collection: str, workspace: str = 'commons', messages_key: str = 'messages', sync: bool = False, message_uuid_method: ~typing.Callable[[], ~typing.Union[str, int]] = <function RocksetChatMessageHistory.<lambda>>) → None[source]¶ Constructs a new RocksetChatMessageHistory. Parameters 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 name does not exist in the workspace, it is created. workspace (-) – The workspace containing collection. Defaults to “commons” messages_key (-) – The DB column containing message history. Defaults to “messages” sync (-) – Whether to wait for messages to be added. Defaults to False. NOTE: setting this to True will slow down performance.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.rocksetdb.RocksetChatMessageHistory.html
8c65ca8b9e7c-2
to False. NOTE: setting this to True will slow down performance. message_uuid_method (-) – The method that generates message IDs. If set, all messages will have an id field within the additional_kwargs property. If this param is not set and sync is False, message IDs will not be created. If this param is not set and sync is True, the uuid.uuid4 method will be used to create message IDs. add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Add a Message object to the history. Parameters message – A BaseMessage object to store. add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Removes all messages from the chat history Examples using RocksetChatMessageHistory¶ Rockset Chat Message History
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.rocksetdb.RocksetChatMessageHistory.html
0b5c4d91e42c-0
langchain_community.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory¶ class langchain_community.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory(cosmos_endpoint: str, cosmos_database: str, cosmos_container: str, session_id: str, user_id: str, credential: Any = None, connection_string: Optional[str] = None, ttl: Optional[int] = None, cosmos_client_kwargs: Optional[dict] = None)[source]¶ Chat message history backed by Azure CosmosDB. Initializes a new instance of the CosmosDBChatMessageHistory class. Make sure to call prepare_cosmos or use the context manager to make sure your database is ready. Either a credential or a connection string must be provided. Parameters cosmos_endpoint – The connection endpoint for the Azure Cosmos DB account. cosmos_database – The name of the database to use. cosmos_container – The name of the container to use. session_id – The session ID to use, can be overwritten while loading. user_id – The user ID to use, can be overwritten while loading. credential – The credential to use to authenticate to Azure Cosmos DB. connection_string – The connection string to use to authenticate. ttl – The time to live (in seconds) to use for documents in the container. cosmos_client_kwargs – Additional kwargs to pass to the CosmosClient. Attributes messages A list of Messages stored in-memory. Methods __init__(cosmos_endpoint, cosmos_database, ...) Initializes a new instance of the CosmosDBChatMessageHistory class. add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Add a self-created message to the store add_user_message(message) Convenience method for adding a human message string to the store. clear()
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory.html
0b5c4d91e42c-1
Convenience method for adding a human message string to the store. clear() Clear session memory from this memory and cosmos. load_messages() Retrieve the messages from Cosmos prepare_cosmos() Prepare the CosmosDB client. upsert_messages() Update the cosmosdb item. __init__(cosmos_endpoint: str, cosmos_database: str, cosmos_container: str, session_id: str, user_id: str, credential: Any = None, connection_string: Optional[str] = None, ttl: Optional[int] = None, cosmos_client_kwargs: Optional[dict] = None)[source]¶ Initializes a new instance of the CosmosDBChatMessageHistory class. Make sure to call prepare_cosmos or use the context manager to make sure your database is ready. Either a credential or a connection string must be provided. Parameters cosmos_endpoint – The connection endpoint for the Azure Cosmos DB account. cosmos_database – The name of the database to use. cosmos_container – The name of the container to use. session_id – The session ID to use, can be overwritten while loading. user_id – The user ID to use, can be overwritten while loading. credential – The credential to use to authenticate to Azure Cosmos DB. connection_string – The connection string to use to authenticate. ttl – The time to live (in seconds) to use for documents in the container. cosmos_client_kwargs – Additional kwargs to pass to the CosmosClient. add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Add a self-created message to the store add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory.html
0b5c4d91e42c-2
Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from this memory and cosmos. load_messages() → None[source]¶ Retrieve the messages from Cosmos prepare_cosmos() → None[source]¶ Prepare the CosmosDB client. Use this function or the context manager to make sure your database is ready. upsert_messages() → None[source]¶ Update the cosmosdb item.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.cosmos_db.CosmosDBChatMessageHistory.html
742f84c58215-0
langchain_community.chat_message_histories.zep.ZepChatMessageHistory¶ class langchain_community.chat_message_histories.zep.ZepChatMessageHistory(session_id: str, url: str = 'http://localhost:8000', api_key: Optional[str] = None)[source]¶ Chat message history that uses Zep as a backend. Recommended usage: # Set up Zep Chat History zep_chat_history = ZepChatMessageHistory( session_id=session_id, url=ZEP_API_URL, api_key=<your_api_key>, ) # Use a standard ConversationBufferMemory to encapsulate the Zep chat history memory = ConversationBufferMemory( memory_key="chat_history", chat_memory=zep_chat_history ) Zep provides long-term conversation storage for LLM apps. The server stores, summarizes, embeds, indexes, and enriches conversational AI chat histories, and exposes them via simple, low-latency APIs. For server installation instructions and more, see: https://docs.getzep.com/deployment/quickstart/ This class is a thin wrapper around the zep-python package. Additional Zep functionality is exposed via the zep_summary and zep_messages properties. For more information on the zep-python package, see: https://github.com/getzep/zep-python Attributes messages Retrieve messages from Zep memory zep_messages Retrieve summary from Zep memory zep_summary Retrieve summary from Zep memory Methods __init__(session_id[, url, api_key]) add_ai_message(message[, metadata]) Convenience method for adding an AI message string to the store. add_message(message[, metadata]) Append the message to the Zep memory history add_user_message(message[, metadata])
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.zep.ZepChatMessageHistory.html
742f84c58215-1
Append the message to the Zep memory history add_user_message(message[, metadata]) Convenience method for adding a human message string to the store. clear() Clear session memory from Zep. search(query[, metadata, limit]) Search Zep memory for messages matching the query __init__(session_id: str, url: str = 'http://localhost:8000', api_key: Optional[str] = None) → None[source]¶ add_ai_message(message: str, metadata: Optional[Dict[str, Any]] = None) → None[source]¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. metadata – Optional metadata to attach to the message. add_message(message: BaseMessage, metadata: Optional[Dict[str, Any]] = None) → None[source]¶ Append the message to the Zep memory history add_user_message(message: str, metadata: Optional[Dict[str, Any]] = None) → None[source]¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. metadata – Optional metadata to attach to the message. clear() → None[source]¶ Clear session memory from Zep. Note that Zep is long-term storage for memory and this is not advised unless you have specific data retention requirements. search(query: str, metadata: Optional[Dict] = None, limit: Optional[int] = None) → List[MemorySearchResult][source]¶ Search Zep memory for messages matching the query
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.zep.ZepChatMessageHistory.html
4db3c4276b9d-0
langchain_community.chat_message_histories.in_memory.ChatMessageHistory¶ class langchain_community.chat_message_histories.in_memory.ChatMessageHistory[source]¶ Bases: BaseChatMessageHistory, BaseModel In memory implementation of chat message history. Stores messages in an in memory list. Create a new model by parsing and validating input data from keyword arguments. Raises ValidationError if the input data cannot be parsed to form a valid model. param messages: List[langchain_core.messages.base.BaseMessage] [Optional]¶ A list of Messages stored in-memory. add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Add a self-created message to the store add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Remove all messages from the store classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.in_memory.ChatMessageHistory.html
4db3c4276b9d-1
Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) → DictStrAny¶ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. classmethod from_orm(obj: Any) → Model¶ json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.in_memory.ChatMessageHistory.html
4db3c4276b9d-2
classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ Examples using ChatMessageHistory¶ Message Memory in Agent backed by a database
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.in_memory.ChatMessageHistory.html
6b1347999af3-0
langchain_community.chat_message_histories.redis.RedisChatMessageHistory¶ class langchain_community.chat_message_histories.redis.RedisChatMessageHistory(session_id: str, url: str = 'redis://localhost:6379/0', key_prefix: str = 'message_store:', ttl: Optional[int] = None)[source]¶ Chat message history stored in a Redis database. Attributes key Construct the record key to use messages Retrieve the messages from Redis Methods __init__(session_id[, url, key_prefix, ttl]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in Redis add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from Redis __init__(session_id: str, url: str = 'redis://localhost:6379/0', key_prefix: str = 'message_store:', ttl: Optional[int] = None)[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in Redis add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from Redis Examples using RedisChatMessageHistory¶ Redis Chat Message History Message Memory in Agent backed by a database
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.redis.RedisChatMessageHistory.html
5d010c539536-0
langchain_community.chat_message_histories.dynamodb.DynamoDBChatMessageHistory¶ class langchain_community.chat_message_histories.dynamodb.DynamoDBChatMessageHistory(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)[source]¶ Chat message history that stores history in AWS DynamoDB. This class expects that a DynamoDB table exists with name table_name Parameters table_name – name of the DynamoDB table session_id – arbitrary key that is used to store the messages of a single chat session. endpoint_url – URL of the AWS endpoint to connect to. This argument is optional and useful for test purposes, like using Localstack. If you plan to use AWS cloud service, you normally don’t have to worry about setting the endpoint_url. primary_key_name – name of the primary key of the DynamoDB table. This argument is optional, defaulting to “SessionId”. key – an optional dictionary with a custom primary and secondary key. This argument is optional, but useful when using composite dynamodb keys, or isolating records based off of application details such as a user id. This may also contain global and local secondary index keys. kms_key_id – an optional AWS KMS Key ID, AWS KMS Key ARN, or AWS KMS Alias for client-side encryption Attributes messages Retrieve the messages from DynamoDB Methods __init__(table_name, session_id[, ...]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in DynamoDB add_user_message(message)
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.dynamodb.DynamoDBChatMessageHistory.html
5d010c539536-1
Append the message to the record in DynamoDB add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from DynamoDB __init__(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)[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in DynamoDB add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from DynamoDB Examples using DynamoDBChatMessageHistory¶ Dynamodb Chat Message History
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.dynamodb.DynamoDBChatMessageHistory.html
e24f8d1797d7-0
langchain_community.chat_message_histories.upstash_redis.UpstashRedisChatMessageHistory¶ class langchain_community.chat_message_histories.upstash_redis.UpstashRedisChatMessageHistory(session_id: str, url: str = '', token: str = '', key_prefix: str = 'message_store:', ttl: Optional[int] = None)[source]¶ Chat message history stored in an Upstash Redis database. Attributes key Construct the record key to use messages Retrieve the messages from Upstash Redis Methods __init__(session_id[, url, token, ...]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in Upstash Redis add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from Upstash Redis __init__(session_id: str, url: str = '', token: str = '', key_prefix: str = 'message_store:', ttl: Optional[int] = None)[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in Upstash Redis add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from Upstash Redis
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.upstash_redis.UpstashRedisChatMessageHistory.html
b1933275d4e9-0
langchain_community.chat_message_histories.momento.MomentoChatMessageHistory¶ class langchain_community.chat_message_histories.momento.MomentoChatMessageHistory(session_id: str, cache_client: momento.CacheClient, cache_name: str, *, key_prefix: str = 'message_store:', ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True)[source]¶ Chat message history cache that uses Momento as a backend. See https://gomomento.com/ Instantiate a chat message history cache that uses Momento as a backend. Note: to instantiate the cache client passed to MomentoChatMessageHistory, you must have a Momento account at https://gomomento.com/. Parameters session_id (str) – The session ID to use for this chat session. cache_client (CacheClient) – The Momento cache client. cache_name (str) – The name of the cache to use to store the messages. key_prefix (str, optional) – The prefix to apply to the cache key. Defaults to “message_store:”. ttl (Optional[timedelta], optional) – The TTL to use for the messages. Defaults to None, ie the default TTL of the cache will be used. ensure_cache_exists (bool, optional) – Create the cache if it doesn’t exist. Defaults to True. Raises ImportError – Momento python package is not installed. TypeError – cache_client is not of type momento.CacheClientObject Attributes messages Retrieve the messages from Momento. Methods __init__(session_id, cache_client, cache_name, *) Instantiate a chat message history cache that uses Momento as a backend. add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Store a message in the cache.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.momento.MomentoChatMessageHistory.html
b1933275d4e9-1
add_message(message) Store a message in the cache. add_user_message(message) Convenience method for adding a human message string to the store. clear() Remove the session's messages from the cache. from_client_params(session_id, cache_name, ...) Construct cache from CacheClient parameters. __init__(session_id: str, cache_client: momento.CacheClient, cache_name: str, *, key_prefix: str = 'message_store:', ttl: Optional[timedelta] = None, ensure_cache_exists: bool = True)[source]¶ Instantiate a chat message history cache that uses Momento as a backend. Note: to instantiate the cache client passed to MomentoChatMessageHistory, you must have a Momento account at https://gomomento.com/. Parameters session_id (str) – The session ID to use for this chat session. cache_client (CacheClient) – The Momento cache client. cache_name (str) – The name of the cache to use to store the messages. key_prefix (str, optional) – The prefix to apply to the cache key. Defaults to “message_store:”. ttl (Optional[timedelta], optional) – The TTL to use for the messages. Defaults to None, ie the default TTL of the cache will be used. ensure_cache_exists (bool, optional) – Create the cache if it doesn’t exist. Defaults to True. Raises ImportError – Momento python package is not installed. TypeError – cache_client is not of type momento.CacheClientObject add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Store a message in the cache. Parameters
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.momento.MomentoChatMessageHistory.html
b1933275d4e9-2
Store a message in the cache. Parameters message (BaseMessage) – The message object to store. Raises SdkException – Momento service or network error. Exception – Unexpected response. add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Remove the session’s messages from the cache. Raises SdkException – Momento service or network error. Exception – Unexpected response. classmethod from_client_params(session_id: str, cache_name: str, ttl: timedelta, *, configuration: Optional[momento.config.Configuration] = None, api_key: Optional[str] = None, auth_token: Optional[str] = None, **kwargs: Any) → MomentoChatMessageHistory[source]¶ Construct cache from CacheClient parameters. Examples using MomentoChatMessageHistory¶ Momento Chat Message History
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.momento.MomentoChatMessageHistory.html
f86739c7d112-0
langchain_community.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory¶ class langchain_community.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory(index: str, session_id: str, *, es_connection: Optional[Elasticsearch] = None, es_url: Optional[str] = None, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_api_key: Optional[str] = None, es_password: Optional[str] = None)[source]¶ Chat message history that stores history in Elasticsearch. Parameters es_url – URL of the Elasticsearch instance to connect to. es_cloud_id – Cloud ID of the Elasticsearch instance to connect to. es_user – Username to use when connecting to Elasticsearch. es_password – Password to use when connecting to Elasticsearch. es_api_key – API key to use when connecting to Elasticsearch. es_connection – Optional pre-existing Elasticsearch connection. index – Name of the index to use. session_id – Arbitrary key that is used to store the messages of a single chat session. Attributes messages Retrieve the messages from Elasticsearch Methods __init__(index, session_id, *[, ...]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Add a message to the chat session in Elasticsearch add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory in Elasticsearch connect_to_elasticsearch(*[, es_url, ...]) get_user_agent()
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory.html
f86739c7d112-1
connect_to_elasticsearch(*[, es_url, ...]) get_user_agent() __init__(index: str, session_id: str, *, es_connection: Optional[Elasticsearch] = None, es_url: Optional[str] = None, es_cloud_id: Optional[str] = None, es_user: Optional[str] = None, es_api_key: Optional[str] = None, es_password: Optional[str] = None)[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Add a message to the chat session in Elasticsearch add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory in Elasticsearch static connect_to_elasticsearch(*, es_url: Optional[str] = None, cloud_id: Optional[str] = None, api_key: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None) → Elasticsearch[source]¶ static get_user_agent() → str[source]¶
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.elasticsearch.ElasticsearchChatMessageHistory.html
faf7c56ee843-0
langchain_community.chat_message_histories.cassandra.CassandraChatMessageHistory¶ class langchain_community.chat_message_histories.cassandra.CassandraChatMessageHistory(session_id: str, session: Session, keyspace: str, table_name: str = 'message_store', ttl_seconds: Optional[int] = None)[source]¶ Chat message history that stores history in Cassandra. Parameters session_id – arbitrary key that is used to store the messages of a single chat session. session – a Cassandra Session object (an open DB connection) keyspace – name of the keyspace to use. table_name – name of the table to use. ttl_seconds – time-to-live (seconds) for automatic expiration of stored entries. None (default) for no expiration. Attributes messages Retrieve all session messages from DB Methods __init__(session_id, session, keyspace[, ...]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Write a message to the table add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from DB __init__(session_id: str, session: Session, keyspace: str, table_name: str = 'message_store', ttl_seconds: Optional[int] = None) → None[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Write a message to the table add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.cassandra.CassandraChatMessageHistory.html
faf7c56ee843-1
message – The string contents of a human message. clear() → None[source]¶ Clear session memory from DB Examples using CassandraChatMessageHistory¶ Cassandra Chat Message History Cassandra
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.cassandra.CassandraChatMessageHistory.html
01598b519659-0
langchain_community.chat_message_histories.sql.create_message_model¶ langchain_community.chat_message_histories.sql.create_message_model(table_name, DynamicBase)[source]¶ Create a message model for a given table name. Parameters table_name – The name of the table to use. DynamicBase – The base class to use for the model. Returns The model class.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.sql.create_message_model.html
1100961c5b9f-0
langchain_community.chat_message_histories.sql.DefaultMessageConverter¶ class langchain_community.chat_message_histories.sql.DefaultMessageConverter(table_name: str)[source]¶ The default message converter for SQLChatMessageHistory. Methods __init__(table_name) from_sql_model(sql_message) Convert a SQLAlchemy model to a BaseMessage instance. get_sql_model_class() Get the SQLAlchemy model class. to_sql_model(message, session_id) Convert a BaseMessage instance to a SQLAlchemy model. __init__(table_name: str)[source]¶ from_sql_model(sql_message: Any) → BaseMessage[source]¶ Convert a SQLAlchemy model to a BaseMessage instance. get_sql_model_class() → Any[source]¶ Get the SQLAlchemy model class. to_sql_model(message: BaseMessage, session_id: str) → Any[source]¶ Convert a BaseMessage instance to a SQLAlchemy model.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.sql.DefaultMessageConverter.html
b44676bdd4b0-0
langchain_community.chat_message_histories.streamlit.StreamlitChatMessageHistory¶ class langchain_community.chat_message_histories.streamlit.StreamlitChatMessageHistory(key: str = 'langchain_messages')[source]¶ Chat message history that stores messages in Streamlit session state. Parameters key – The key to use in Streamlit session state for storing messages. Attributes messages Retrieve the current list of messages Methods __init__([key]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Add a message to the session memory add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory __init__(key: str = 'langchain_messages')[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Add a message to the session memory add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory Examples using StreamlitChatMessageHistory¶ Streamlit Chat Message History
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.streamlit.StreamlitChatMessageHistory.html
410d4c1d23eb-0
langchain_community.chat_message_histories.astradb.AstraDBChatMessageHistory¶ class langchain_community.chat_message_histories.astradb.AstraDBChatMessageHistory(*, session_id: str, collection_name: str = 'langchain_message_store', token: Optional[str] = None, api_endpoint: Optional[str] = None, astra_db_client: Optional[LibAstraDB] = None, namespace: Optional[str] = None)[source]¶ Chat message history that stores history in Astra DB. Args (only keyword-arguments accepted): session_id: arbitrary key that is used to store the messagesof a single chat session. collection_name (str): name of the Astra DB collection to create/use. token (Optional[str]): API token for Astra DB usage. api_endpoint (Optional[str]): full URL to the API endpoint, such as “https://<DB-ID>-us-east1.apps.astra.datastax.com”. astra_db_client (Optional[Any]): alternative to token+api_endpoint,you can pass an already-created ‘astrapy.db.AstraDB’ instance. namespace (Optional[str]): namespace (aka keyspace) where thecollection is created. Defaults to the database’s “default namespace”. Create an Astra DB chat message history. Attributes messages Retrieve all session messages from DB Methods __init__(*, session_id[, collection_name, ...]) Create an Astra DB chat message history. add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Write a message to the table add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from DB
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.astradb.AstraDBChatMessageHistory.html
410d4c1d23eb-1
clear() Clear session memory from DB __init__(*, session_id: str, collection_name: str = 'langchain_message_store', token: Optional[str] = None, api_endpoint: Optional[str] = None, astra_db_client: Optional[LibAstraDB] = None, namespace: Optional[str] = None) → None[source]¶ Create an Astra DB chat message history. add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Write a message to the table add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from DB
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.astradb.AstraDBChatMessageHistory.html
f449802395d3-0
langchain_community.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory¶ class langchain_community.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory(session_id: str, *, table_name: str = 'message_store', id_field: str = 'id', session_id_field: str = 'session_id', message_field: str = 'message', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]¶ Chat message history stored in a SingleStoreDB database. Initialize with necessary components. Parameters table_name (str, optional) – Specifies the name of the table in use. Defaults to “message_store”. id_field (str, optional) – Specifies the name of the id field in the table. Defaults to “id”. session_id_field (str, optional) – Specifies the name of the session_id field in the table. Defaults to “session_id”. message_field (str, optional) – Specifies the name of the message field in the table. Defaults to “message”. pool (Following arguments pertain to the connection) – pool_size (int, optional) – Determines the number of active connections in the pool. Defaults to 5. 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. connection (database) – host (str, optional) – Specifies the hostname, IP address, or URL for the database connection. The default scheme is “mysql”. user (str, optional) – Database username. password (str, optional) – Database password.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html
f449802395d3-1
password (str, optional) – Database password. port (int, optional) – Database port. Defaults to 3306 for non-HTTP connections, 80 for HTTP connections, and 443 for HTTPS connections. database (str, optional) – Database name. the (Additional optional arguments provide further customization over) – connection – pure_python (bool, optional) – Toggles the connector mode. If True, operates in pure Python mode. local_infile (bool, optional) – Allows local file uploads. charset (str, optional) – Specifies the character set for string values. ssl_key (str, optional) – Specifies the path of the file containing the SSL key. ssl_cert (str, optional) – Specifies the path of the file containing the SSL certificate. ssl_ca (str, optional) – Specifies the path of the file containing the SSL certificate authority. ssl_cipher (str, optional) – Sets the SSL cipher list. ssl_disabled (bool, optional) – Disables SSL usage. ssl_verify_cert (bool, optional) – Verifies the server’s certificate. Automatically enabled if ssl_ca is specified. ssl_verify_identity (bool, optional) – Verifies the server’s identity. 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. results_type (str, optional) – Determines the structure of the query results: tuples, namedtuples, dicts. results_format (str, optional) – Deprecated. This option has been renamed to results_type. Examples Basic Usage: from langchain_community.chat_message_histories import (
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html
f449802395d3-2
Examples Basic Usage: from langchain_community.chat_message_histories import ( SingleStoreDBChatMessageHistory ) message_history = SingleStoreDBChatMessageHistory( session_id="my-session", host="https://user:password@127.0.0.1:3306/database" ) Advanced Usage: from langchain_community.chat_message_histories import ( SingleStoreDBChatMessageHistory ) message_history = SingleStoreDBChatMessageHistory( session_id="my-session", host="127.0.0.1", port=3306, user="user", password="password", database="db", table_name="my_custom_table", pool_size=10, timeout=60, ) Using environment variables: from langchain_community.chat_message_histories import ( SingleStoreDBChatMessageHistory ) os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' message_history = SingleStoreDBChatMessageHistory("my-session") Attributes messages Retrieve the messages from SingleStoreDB Methods __init__(session_id, *[, table_name, ...]) Initialize with necessary components. add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in SingleStoreDB add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from SingleStoreDB
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html
f449802395d3-3
clear() Clear session memory from SingleStoreDB __init__(session_id: str, *, table_name: str = 'message_store', id_field: str = 'id', session_id_field: str = 'session_id', message_field: str = 'message', pool_size: int = 5, max_overflow: int = 10, timeout: float = 30, **kwargs: Any)[source]¶ Initialize with necessary components. Parameters table_name (str, optional) – Specifies the name of the table in use. Defaults to “message_store”. id_field (str, optional) – Specifies the name of the id field in the table. Defaults to “id”. session_id_field (str, optional) – Specifies the name of the session_id field in the table. Defaults to “session_id”. message_field (str, optional) – Specifies the name of the message field in the table. Defaults to “message”. pool (Following arguments pertain to the connection) – pool_size (int, optional) – Determines the number of active connections in the pool. Defaults to 5. 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. connection (database) – host (str, optional) – Specifies the hostname, IP address, or URL for the database connection. The default scheme is “mysql”. user (str, optional) – Database username. password (str, optional) – Database password. port (int, optional) – Database port. Defaults to 3306 for non-HTTP connections, 80 for HTTP connections, and 443 for HTTPS connections. database (str, optional) – Database name.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html
f449802395d3-4
database (str, optional) – Database name. the (Additional optional arguments provide further customization over) – connection – pure_python (bool, optional) – Toggles the connector mode. If True, operates in pure Python mode. local_infile (bool, optional) – Allows local file uploads. charset (str, optional) – Specifies the character set for string values. ssl_key (str, optional) – Specifies the path of the file containing the SSL key. ssl_cert (str, optional) – Specifies the path of the file containing the SSL certificate. ssl_ca (str, optional) – Specifies the path of the file containing the SSL certificate authority. ssl_cipher (str, optional) – Sets the SSL cipher list. ssl_disabled (bool, optional) – Disables SSL usage. ssl_verify_cert (bool, optional) – Verifies the server’s certificate. Automatically enabled if ssl_ca is specified. ssl_verify_identity (bool, optional) – Verifies the server’s identity. 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. results_type (str, optional) – Determines the structure of the query results: tuples, namedtuples, dicts. results_format (str, optional) – Deprecated. This option has been renamed to results_type. Examples Basic Usage: from langchain_community.chat_message_histories import ( SingleStoreDBChatMessageHistory ) message_history = SingleStoreDBChatMessageHistory( session_id="my-session",
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html
f449802395d3-5
message_history = SingleStoreDBChatMessageHistory( session_id="my-session", host="https://user:password@127.0.0.1:3306/database" ) Advanced Usage: from langchain_community.chat_message_histories import ( SingleStoreDBChatMessageHistory ) message_history = SingleStoreDBChatMessageHistory( session_id="my-session", host="127.0.0.1", port=3306, user="user", password="password", database="db", table_name="my_custom_table", pool_size=10, timeout=60, ) Using environment variables: from langchain_community.chat_message_histories import ( SingleStoreDBChatMessageHistory ) os.environ['SINGLESTOREDB_URL'] = 'me:p455w0rd@s2-host.com/my_db' message_history = SingleStoreDBChatMessageHistory("my-session") add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in SingleStoreDB add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from SingleStoreDB
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.singlestoredb.SingleStoreDBChatMessageHistory.html
6eaf9b68f242-0
langchain_community.chat_message_histories.xata.XataChatMessageHistory¶ class langchain_community.chat_message_histories.xata.XataChatMessageHistory(session_id: str, db_url: str, api_key: str, branch_name: str = 'main', table_name: str = 'messages', create_table: bool = True)[source]¶ Chat message history stored in a Xata database. Initialize with Xata client. Attributes messages Methods __init__(session_id, db_url, api_key[, ...]) Initialize with Xata client. add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the Xata table add_user_message(message) Convenience method for adding a human message string to the store. clear() Delete session from Xata table. __init__(session_id: str, db_url: str, api_key: str, branch_name: str = 'main', table_name: str = 'messages', create_table: bool = True) → None[source]¶ Initialize with Xata client. add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the Xata table add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Delete session from Xata table. Examples using XataChatMessageHistory¶ Xata chat memory
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.xata.XataChatMessageHistory.html
4015b56b1fa3-0
langchain_community.chat_message_histories.firestore.FirestoreChatMessageHistory¶ class langchain_community.chat_message_histories.firestore.FirestoreChatMessageHistory(collection_name: str, session_id: str, user_id: str, firestore_client: Optional[Client] = None)[source]¶ Chat message history backed by Google Firestore. Initialize a new instance of the FirestoreChatMessageHistory class. Parameters collection_name – The name of the collection to use. session_id – The session ID for the chat.. user_id – The user ID for the chat. Attributes messages A list of Messages stored in-memory. Methods __init__(collection_name, session_id, user_id) Initialize a new instance of the FirestoreChatMessageHistory class. add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Add a Message object to the store. add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from this memory and Firestore. load_messages() Retrieve the messages from Firestore prepare_firestore() Prepare the Firestore client. upsert_messages([new_message]) Update the Firestore document. __init__(collection_name: str, session_id: str, user_id: str, firestore_client: Optional[Client] = None)[source]¶ Initialize a new instance of the FirestoreChatMessageHistory class. Parameters collection_name – The name of the collection to use. session_id – The session ID for the chat.. user_id – The user ID for the chat. add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Add a Message object to the store.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.firestore.FirestoreChatMessageHistory.html
4015b56b1fa3-1
Add a Message object to the store. Parameters message – A BaseMessage object to store. add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from this memory and Firestore. load_messages() → None[source]¶ Retrieve the messages from Firestore prepare_firestore() → None[source]¶ Prepare the Firestore client. Use this function to make sure your database is ready. upsert_messages(new_message: Optional[BaseMessage] = None) → None[source]¶ Update the Firestore document.
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.firestore.FirestoreChatMessageHistory.html
d65891574857-0
langchain_community.chat_message_histories.mongodb.MongoDBChatMessageHistory¶ class langchain_community.chat_message_histories.mongodb.MongoDBChatMessageHistory(connection_string: str, session_id: str, database_name: str = 'chat_history', collection_name: str = 'message_store')[source]¶ Chat message history that stores history in MongoDB. Parameters connection_string – connection string to connect to MongoDB session_id – arbitrary key that is used to store the messages of a single chat session. database_name – name of the database to use collection_name – name of the collection to use Attributes messages Retrieve the messages from MongoDB Methods __init__(connection_string, session_id[, ...]) add_ai_message(message) Convenience method for adding an AI message string to the store. add_message(message) Append the message to the record in MongoDB add_user_message(message) Convenience method for adding a human message string to the store. clear() Clear session memory from MongoDB __init__(connection_string: str, session_id: str, database_name: str = 'chat_history', collection_name: str = 'message_store')[source]¶ add_ai_message(message: str) → None¶ Convenience method for adding an AI message string to the store. Parameters message – The string contents of an AI message. add_message(message: BaseMessage) → None[source]¶ Append the message to the record in MongoDB add_user_message(message: str) → None¶ Convenience method for adding a human message string to the store. Parameters message – The string contents of a human message. clear() → None[source]¶ Clear session memory from MongoDB Examples using MongoDBChatMessageHistory¶ Mongodb Chat Message History
https://api.python.langchain.com/en/latest/chat_message_histories/langchain_community.chat_message_histories.mongodb.MongoDBChatMessageHistory.html
006c1a17fb1e-0
langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser¶ class langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser[source]¶ Bases: VectorSQLOutputParser Based on VectorSQLOutputParser It also modify the SQL to get all columns param distance_func_name: str = 'distance'¶ Distance name for Vector SQL param model: langchain_core.embeddings.Embeddings [Required]¶ Embedding model to extract embedding for entity async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶ Default implementation runs ainvoke in parallel using asyncio.gather. The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; e.g., if the underlying runnable uses an API which supports a batch mode. async ainvoke(input: str | langchain_core.messages.base.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → T¶ Default implementation of ainvoke, calls invoke from a thread. The default implementation allows usage of async code even if the runnable did not implement a native async version of invoke. Subclasses should override this method if they can run asynchronously. async aparse(text: str) → T¶ Parse a single string model output into some structure. Parameters text – String output of a language model. Returns Structured output. async aparse_result(result: List[Generation], *, partial: bool = False) → T¶ Parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation. Parameters
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-1
Parameters result – A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. Returns Structured output. async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶ Default implementation of astream, which calls ainvoke. Subclasses should override this method if they support streaming output. async astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, with_streamed_output_list: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) → Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]¶ Stream all output from a runnable, as reported to the callback system. This includes all inner runs of LLMs, Retrievers, Tools, etc. Output is streamed as Log objects, which include a list of jsonpatch ops that describe how the state of the run has changed in each step, and the final state of the run. The jsonpatch ops can be applied in order to construct state. Parameters input – The input to the runnable. config – The config to use for the runnable. diff – Whether to yield diffs between each step, or the current state. with_streamed_output_list – Whether to yield the streamed_output list. include_names – Only include logs with these names. include_types – Only include logs with these types. include_tags – Only include logs with these tags.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-2
include_tags – Only include logs with these tags. exclude_names – Exclude logs with these names. exclude_types – Exclude logs with these types. exclude_tags – Exclude logs with these tags. async atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶ Default implementation of atransform, which buffers input and calls astream. Subclasses should override this method if they can start producing output while input is still being generated. batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶ Default implementation runs invoke in parallel using a thread pool executor. The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; e.g., if the underlying runnable uses an API which supports a batch mode. bind(**kwargs: Any) → Runnable[Input, Output]¶ Bind arguments to a Runnable, returning a new Runnable. config_schema(*, include: Optional[Sequence[str]] = None) → Type[BaseModel]¶ The type of config this runnable accepts specified as a pydantic model. To mark a field as configurable, see the configurable_fields and configurable_alternatives methods. Parameters include – A list of fields to include in the config schema. Returns A pydantic model that can be used to validate config. configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) → RunnableSerializable[Input, Output]¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-3
configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) → RunnableSerializable[Input, Output]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) → Dict¶ Return dictionary representation of output parser. classmethod from_embeddings(model: Embeddings, distance_func_name: str = 'distance', **kwargs: Any) → BaseOutputParser¶ classmethod from_orm(obj: Any) → Model¶ get_format_instructions() → str¶ Instructions on how the LLM output should be formatted. get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶ Get a pydantic model that can be used to validate input to the runnable. Runnables that leverage the configurable_fields and configurable_alternatives
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-4
Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic input schema that depends on which configuration the runnable is invoked with. This method allows to get an input schema for a specific configuration. Parameters config – A config to use when generating the schema. Returns A pydantic model that can be used to validate input. classmethod get_lc_namespace() → List[str]¶ Get the namespace of the langchain object. For example, if the class is langchain.llms.openai.OpenAI, then the namespace is [“langchain”, “llms”, “openai”] get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶ Get a pydantic model that can be used to validate output to the runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic output schema that depends on which configuration the runnable is invoked with. This method allows to get an output schema for a specific configuration. Parameters config – A config to use when generating the schema. Returns A pydantic model that can be used to validate output. invoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) → T¶ Transform a single input into an output. Override to implement. Parameters input – The input to the runnable. config – A config to use when invoking the runnable. The config supports standard keys like ‘tags’, ‘metadata’ for tracing purposes, ‘max_concurrency’ for controlling how much work to do in parallel, and other keys. Please refer to the RunnableConfig for more details. Returns The output of the runnable. classmethod is_lc_serializable() → bool¶ Is this class serializable?
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-5
classmethod is_lc_serializable() → bool¶ Is this class serializable? json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod lc_id() → List[str]¶ A unique identifier for this class for serialization purposes. The unique identifier is a list of strings that describes the path to the object. map() → Runnable[List[Input], List[Output]]¶ Return a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input. parse(text: str) → str[source]¶ Parse a single string model output into some structure. Parameters text – String output of a language model. Returns Structured output. classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-6
parse_result(result: List[Generation], *, partial: bool = False) → T¶ Parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation. Parameters result – A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. Returns Structured output. parse_with_prompt(completion: str, prompt: PromptValue) → Any¶ Parse the output of an LLM call with the input prompt for context. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so. Parameters completion – String output of a language model. prompt – Input PromptValue. Returns Structured output classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶ Default implementation of stream, which calls invoke. Subclasses should override this method if they support streaming output. to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶ to_json_not_implemented() → SerializedNotImplemented¶ transform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶ Default implementation of transform, which buffers input and then calls stream. Subclasses should override this method if they can start producing output while input is still being generated.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-7
input is still being generated. classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ with_config(config: Optional[RunnableConfig] = None, **kwargs: Any) → Runnable[Input, Output]¶ Bind config to a Runnable, returning a new Runnable. with_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) → RunnableWithFallbacksT[Input, Output]¶ Add fallbacks to a runnable, returning a new Runnable. Parameters fallbacks – A sequence of runnables to try if the original runnable fails. exceptions_to_handle – A tuple of exception types to handle. Returns A new Runnable that will try the original runnable, and then each fallback in order, upon failures. with_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) → Runnable[Input, Output]¶ Bind lifecycle listeners to a Runnable, returning a new Runnable. on_start: Called before the runnable starts running, with the Run object. on_end: Called after the runnable finishes running, with the Run object. on_error: Called if the runnable throws an error, with the Run object. The Run object contains information about the run, including its id, type, input, output, error, start_time, end_time, and any tags or metadata added to the run.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-8
added to the run. with_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) → Runnable[Input, Output]¶ Create a new Runnable that retries the original runnable on exceptions. Parameters retry_if_exception_type – A tuple of exception types to retry on wait_exponential_jitter – Whether to add jitter to the wait time between retries stop_after_attempt – The maximum number of attempts to make before giving up Returns A new Runnable that retries the original runnable on exceptions. with_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) → Runnable[Input, Output]¶ Bind input and output types to a Runnable, returning a new Runnable. property InputType: Any¶ The type of input this runnable accepts specified as a type annotation. property OutputType: Type[langchain_core.output_parsers.base.T]¶ The type of output this runnable produces specified as a type annotation. property config_specs: List[langchain_core.runnables.utils.ConfigurableFieldSpec]¶ List configurable fields for this runnable. property input_schema: Type[pydantic.main.BaseModel]¶ The type of input this runnable accepts specified as a pydantic model. property lc_attributes: Dict¶ List of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_secrets: Dict[str, str]¶ A map of constructor argument names to secret ids. For example,{“openai_api_key”: “OPENAI_API_KEY”} property output_schema: Type[pydantic.main.BaseModel]¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
006c1a17fb1e-9
property output_schema: Type[pydantic.main.BaseModel]¶ The type of output this runnable produces specified as a pydantic model.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLRetrieveAllOutputParser.html
be89f79a4358-0
langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain¶ class langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain[source]¶ Bases: SQLDatabaseChain Chain for interacting with Vector SQL Database. Example from langchain_experimental.sql import SQLDatabaseChain from langchain.llms import OpenAI, SQLDatabase, OpenAIEmbeddings db = SQLDatabase(...) db_chain = VectorSQLDatabaseChain.from_llm(OpenAI(), db, OpenAIEmbeddings()) Security note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include the permissions this chain needs. Failure to do so may result in data corruption or loss, since this chain may attempt commands like DROP TABLE or INSERT if appropriately prompted. The best way to guard against such negative outcomes is to (as appropriate) limit the permissions granted to the credentials used with this chain. This issue shows an example negative outcome if these steps are not taken: https://github.com/langchain-ai/langchain/issues/5923 Create a new model by parsing and validating input data from keyword arguments. Raises ValidationError if the input data cannot be parsed to form a valid model. param callback_manager: Optional[BaseCallbackManager] = None¶ Deprecated, use callbacks instead. param callbacks: Callbacks = None¶ Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. param database: SQLDatabase [Required]¶ SQL Database to connect to. param llm: Optional[BaseLanguageModel] = None¶ [Deprecated] LLM wrapper to use. param llm_chain: LLMChain [Required]¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-1
param llm_chain: LLMChain [Required]¶ param memory: Optional[BaseMemory] = None¶ Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. param metadata: Optional[Dict[str, Any]] = None¶ Optional metadata associated with the chain. Defaults to None. This metadata will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. param native_format: bool = False¶ If return_direct, controls whether to return in python native format param prompt: Optional[BasePromptTemplate] = None¶ [Deprecated] Prompt to use to translate natural language to SQL. param query_checker_prompt: Optional[BasePromptTemplate] = None¶ The prompt template that should be used by the query checker param return_direct: bool = False¶ Whether or not to return the result of querying the SQL table directly. param return_intermediate_steps: bool = False¶ Whether or not to return the intermediate steps along with the final answer. param return_sql: bool = False¶ Will return sql-command directly without executing it param sql_cmd_parser: VectorSQLOutputParser [Required]¶ Parser for Vector SQL param tags: Optional[List[str]] = None¶ Optional list of tags associated with the chain. Defaults to None. These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-2
and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. param top_k: int = 5¶ Number of results to return from the query param use_query_checker: bool = False¶ Whether or not the query checker tool should be used to attempt to fix the initial SQL from the LLM. param verbose: bool [Optional]¶ Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to the global verbose value, accessible via langchain.globals.get_verbose(). __call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) → Dict[str, Any]¶ Execute the chain. Parameters 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 the chain’s memory. return_only_outputs – Whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. 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 pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but only
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-3
addition to tags passed to the chain during construction, but only these runtime tags will propagate to calls to other objects. metadata – Optional metadata associated with the chain. Defaults to None include_run_info – Whether to include run info in the response. Defaults to False. Returns A dict of named outputs. Should contain all outputs specified inChain.output_keys. async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶ Default implementation runs ainvoke in parallel using asyncio.gather. The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; e.g., if the underlying runnable uses an API which supports a batch mode. async acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) → Dict[str, Any]¶ Asynchronously execute the chain. Parameters 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 the chain’s memory. return_only_outputs – Whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. callbacks – Callbacks to use for this chain run. These will be called in
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-4
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 pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but only these runtime tags will propagate to calls to other objects. metadata – Optional metadata associated with the chain. Defaults to None include_run_info – Whether to include run info in the response. Defaults to False. Returns A dict of named outputs. Should contain all outputs specified inChain.output_keys. async ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Dict[str, Any]¶ Default implementation of ainvoke, calls invoke from a thread. The default implementation allows usage of async code even if the runnable did not implement a native async version of invoke. Subclasses should override this method if they can run asynchronously. apply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → List[Dict[str, str]]¶ Call the chain on all inputs in the list. async arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → Any¶ Convenience method for executing chain. The main difference between this method and Chain.__call__ is that this method expects inputs to be passed directly in as positional arguments or keyword arguments, whereas Chain.__call__ expects a single input dictionary with all the inputs Parameters
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-5
with all the inputs Parameters *args – If the chain expects a single input, it can be passed in as the 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 pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but only these runtime tags will propagate to calls to other objects. **kwargs – If the chain expects multiple inputs, they can be passed in directly as keyword arguments. Returns The chain output. Example # Suppose we have a single-input chain that takes a 'question' string: await chain.arun("What's the temperature in Boise, Idaho?") # -> "The temperature in Boise is..." # Suppose we have a multi-input chain that takes a 'question' string # and 'context' string: question = "What's the temperature in Boise, Idaho?" context = "Weather report for Boise, Idaho on 07/03/23..." await chain.arun(question=question, context=context) # -> "The temperature in Boise is..." async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶ Default implementation of astream, which calls ainvoke. Subclasses should override this method if they support streaming output.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-6
Subclasses should override this method if they support streaming output. async astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, with_streamed_output_list: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) → Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]¶ Stream all output from a runnable, as reported to the callback system. This includes all inner runs of LLMs, Retrievers, Tools, etc. Output is streamed as Log objects, which include a list of jsonpatch ops that describe how the state of the run has changed in each step, and the final state of the run. The jsonpatch ops can be applied in order to construct state. Parameters input – The input to the runnable. config – The config to use for the runnable. diff – Whether to yield diffs between each step, or the current state. with_streamed_output_list – Whether to yield the streamed_output list. include_names – Only include logs with these names. include_types – Only include logs with these types. include_tags – Only include logs with these tags. exclude_names – Exclude logs with these names. exclude_types – Exclude logs with these types. exclude_tags – Exclude logs with these tags. async atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶ Default implementation of atransform, which buffers input and calls astream.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-7
Default implementation of atransform, which buffers input and calls astream. Subclasses should override this method if they can start producing output while input is still being generated. batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶ Default implementation runs invoke in parallel using a thread pool executor. The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; e.g., if the underlying runnable uses an API which supports a batch mode. bind(**kwargs: Any) → Runnable[Input, Output]¶ Bind arguments to a Runnable, returning a new Runnable. config_schema(*, include: Optional[Sequence[str]] = None) → Type[BaseModel]¶ The type of config this runnable accepts specified as a pydantic model. To mark a field as configurable, see the configurable_fields and configurable_alternatives methods. Parameters include – A list of fields to include in the config schema. Returns A pydantic model that can be used to validate config. configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) → RunnableSerializable[Input, Output]¶ configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) → RunnableSerializable[Input, Output]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-8
Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) → Dict¶ Dictionary representation of chain. Expects Chain._chain_type property to be implemented and for memory to benull. Parameters **kwargs – Keyword arguments passed to default pydantic.BaseModel.dict method. Returns A dictionary representation of the chain. Example chain.dict(exclude_unset=True) # -> {"_type": "foo", "verbose": False, ...} classmethod from_llm(llm: BaseLanguageModel, db: SQLDatabase, prompt: Optional[BasePromptTemplate] = None, sql_cmd_parser: Optional[VectorSQLOutputParser] = None, **kwargs: Any) → VectorSQLDatabaseChain[source]¶ Create a SQLDatabaseChain from an LLM and a database connection. Security note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include the permissions this chain needs. Failure to do so may result in data corruption or loss, since this chain may
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-9
Failure to do so may result in data corruption or loss, since this chain may attempt commands like DROP TABLE or INSERT if appropriately prompted. The best way to guard against such negative outcomes is to (as appropriate) limit the permissions granted to the credentials used with this chain. This issue shows an example negative outcome if these steps are not taken: https://github.com/langchain-ai/langchain/issues/5923 classmethod from_orm(obj: Any) → Model¶ get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶ Get a pydantic model that can be used to validate input to the runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic input schema that depends on which configuration the runnable is invoked with. This method allows to get an input schema for a specific configuration. Parameters config – A config to use when generating the schema. Returns A pydantic model that can be used to validate input. classmethod get_lc_namespace() → List[str]¶ Get the namespace of the langchain object. For example, if the class is langchain.llms.openai.OpenAI, then the namespace is [“langchain”, “llms”, “openai”] get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶ Get a pydantic model that can be used to validate output to the runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic output schema that depends on which configuration the runnable is invoked with. This method allows to get an output schema for a specific configuration. Parameters config – A config to use when generating the schema. Returns A pydantic model that can be used to validate output.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-10
Returns A pydantic model that can be used to validate output. invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Dict[str, Any]¶ Transform a single input into an output. Override to implement. Parameters input – The input to the runnable. config – A config to use when invoking the runnable. The config supports standard keys like ‘tags’, ‘metadata’ for tracing purposes, ‘max_concurrency’ for controlling how much work to do in parallel, and other keys. Please refer to the RunnableConfig for more details. Returns The output of the runnable. classmethod is_lc_serializable() → bool¶ Is this class serializable? json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod lc_id() → List[str]¶ A unique identifier for this class for serialization purposes. The unique identifier is a list of strings that describes the path to the object. map() → Runnable[List[Input], List[Output]]¶ Return a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-11
by calling invoke() with each input. classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ prep_inputs(inputs: Union[Dict[str, Any], Any]) → Dict[str, str]¶ Validate and prepare chain inputs, including adding inputs from memory. Parameters inputs – Dictionary of raw 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 the chain’s memory. Returns A dictionary of all inputs, including those added by the chain’s memory. prep_outputs(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. Parameters inputs – Dictionary of chain inputs, including any inputs added by chain memory. outputs – Dictionary of initial chain outputs. return_only_outputs – Whether to only return the chain outputs. If False, inputs are also added to the final outputs. Returns A dict of the final chain outputs. run(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → Any¶ Convenience method for executing chain. The main difference between this method and Chain.__call__ is that this
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-12
The main difference between this method and Chain.__call__ is that this method expects inputs to be passed directly in as positional arguments or keyword arguments, whereas Chain.__call__ expects a single input dictionary with all the inputs Parameters *args – If the chain expects a single input, it can be passed in as the 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 pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but only these runtime tags will propagate to calls to other objects. **kwargs – If the chain expects multiple inputs, they can be passed in directly as keyword arguments. Returns The chain output. Example # Suppose we have a single-input chain that takes a 'question' string: chain.run("What's the temperature in Boise, Idaho?") # -> "The temperature in Boise is..." # Suppose we have a multi-input chain that takes a 'question' string # and 'context' string: question = "What's the temperature in Boise, Idaho?" context = "Weather report for Boise, Idaho on 07/03/23..." chain.run(question=question, context=context) # -> "The temperature in Boise is..." save(file_path: Union[Path, str]) → None¶ Save the chain. Expects Chain._chain_type property to be implemented and for memory to benull. Parameters file_path – Path to file to save the chain to. Example chain.save(file_path="path/chain.yaml") classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-13
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶ Default implementation of stream, which calls invoke. Subclasses should override this method if they support streaming output. to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶ to_json_not_implemented() → SerializedNotImplemented¶ transform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶ Default implementation of transform, which buffers input and then calls stream. Subclasses should override this method if they can start producing output while input is still being generated. classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ with_config(config: Optional[RunnableConfig] = None, **kwargs: Any) → Runnable[Input, Output]¶ Bind config to a Runnable, returning a new Runnable. with_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) → RunnableWithFallbacksT[Input, Output]¶ Add fallbacks to a runnable, returning a new Runnable. Parameters fallbacks – A sequence of runnables to try if the original runnable fails. exceptions_to_handle – A tuple of exception types to handle. Returns A new Runnable that will try the original runnable, and then each fallback in order, upon failures.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-14
fallback in order, upon failures. with_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) → Runnable[Input, Output]¶ Bind lifecycle listeners to a Runnable, returning a new Runnable. on_start: Called before the runnable starts running, with the Run object. on_end: Called after the runnable finishes running, with the Run object. on_error: Called if the runnable throws an error, with the Run object. The Run object contains information about the run, including its id, type, input, output, error, start_time, end_time, and any tags or metadata added to the run. with_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) → Runnable[Input, Output]¶ Create a new Runnable that retries the original runnable on exceptions. Parameters retry_if_exception_type – A tuple of exception types to retry on wait_exponential_jitter – Whether to add jitter to the wait time between retries stop_after_attempt – The maximum number of attempts to make before giving up Returns A new Runnable that retries the original runnable on exceptions. with_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) → Runnable[Input, Output]¶ Bind input and output types to a Runnable, returning a new Runnable. property InputType: Type[langchain_core.runnables.utils.Input]¶ The type of input this runnable accepts specified as a type annotation. property OutputType: Type[langchain_core.runnables.utils.Output]¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
be89f79a4358-15
property OutputType: Type[langchain_core.runnables.utils.Output]¶ The type of output this runnable produces specified as a type annotation. property config_specs: List[langchain_core.runnables.utils.ConfigurableFieldSpec]¶ List configurable fields for this runnable. property input_schema: Type[pydantic.main.BaseModel]¶ The type of input this runnable accepts specified as a pydantic model. property lc_attributes: Dict¶ List of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_secrets: Dict[str, str]¶ A map of constructor argument names to secret ids. For example,{“openai_api_key”: “OPENAI_API_KEY”} property output_schema: Type[pydantic.main.BaseModel]¶ The type of output this runnable produces specified as a pydantic model.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLDatabaseChain.html
b8879f5b1ec7-0
langchain_experimental.sql.vector_sql.VectorSQLOutputParser¶ class langchain_experimental.sql.vector_sql.VectorSQLOutputParser[source]¶ Bases: BaseOutputParser[str] Output Parser for Vector SQL 1. finds for NeuralArray() and replace it with the embedding 2. finds for DISTANCE() and replace it with the distance name in backend SQL param distance_func_name: str = 'distance'¶ Distance name for Vector SQL param model: langchain_core.embeddings.Embeddings [Required]¶ Embedding model to extract embedding for entity async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶ Default implementation runs ainvoke in parallel using asyncio.gather. The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; e.g., if the underlying runnable uses an API which supports a batch mode. async ainvoke(input: str | langchain_core.messages.base.BaseMessage, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → T¶ Default implementation of ainvoke, calls invoke from a thread. The default implementation allows usage of async code even if the runnable did not implement a native async version of invoke. Subclasses should override this method if they can run asynchronously. async aparse(text: str) → T¶ Parse a single string model output into some structure. Parameters text – String output of a language model. Returns Structured output. async aparse_result(result: List[Generation], *, partial: bool = False) → T¶ Parse a list of candidate model Generations into a specific format.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-1
Parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation. Parameters result – A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. Returns Structured output. async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶ Default implementation of astream, which calls ainvoke. Subclasses should override this method if they support streaming output. async astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, with_streamed_output_list: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) → Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]¶ Stream all output from a runnable, as reported to the callback system. This includes all inner runs of LLMs, Retrievers, Tools, etc. Output is streamed as Log objects, which include a list of jsonpatch ops that describe how the state of the run has changed in each step, and the final state of the run. The jsonpatch ops can be applied in order to construct state. Parameters input – The input to the runnable. config – The config to use for the runnable. diff – Whether to yield diffs between each step, or the current state. with_streamed_output_list – Whether to yield the streamed_output list.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-2
with_streamed_output_list – Whether to yield the streamed_output list. include_names – Only include logs with these names. include_types – Only include logs with these types. include_tags – Only include logs with these tags. exclude_names – Exclude logs with these names. exclude_types – Exclude logs with these types. exclude_tags – Exclude logs with these tags. async atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶ Default implementation of atransform, which buffers input and calls astream. Subclasses should override this method if they can start producing output while input is still being generated. batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶ Default implementation runs invoke in parallel using a thread pool executor. The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; e.g., if the underlying runnable uses an API which supports a batch mode. bind(**kwargs: Any) → Runnable[Input, Output]¶ Bind arguments to a Runnable, returning a new Runnable. config_schema(*, include: Optional[Sequence[str]] = None) → Type[BaseModel]¶ The type of config this runnable accepts specified as a pydantic model. To mark a field as configurable, see the configurable_fields and configurable_alternatives methods. Parameters include – A list of fields to include in the config schema. Returns A pydantic model that can be used to validate config.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-3
Returns A pydantic model that can be used to validate config. configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) → RunnableSerializable[Input, Output]¶ configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) → RunnableSerializable[Input, Output]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) → Dict¶ Return dictionary representation of output parser. classmethod from_embeddings(model: Embeddings, distance_func_name: str = 'distance', **kwargs: Any) → BaseOutputParser[source]¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-4
classmethod from_orm(obj: Any) → Model¶ get_format_instructions() → str¶ Instructions on how the LLM output should be formatted. get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶ Get a pydantic model that can be used to validate input to the runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic input schema that depends on which configuration the runnable is invoked with. This method allows to get an input schema for a specific configuration. Parameters config – A config to use when generating the schema. Returns A pydantic model that can be used to validate input. classmethod get_lc_namespace() → List[str]¶ Get the namespace of the langchain object. For example, if the class is langchain.llms.openai.OpenAI, then the namespace is [“langchain”, “llms”, “openai”] get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶ Get a pydantic model that can be used to validate output to the runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic output schema that depends on which configuration the runnable is invoked with. This method allows to get an output schema for a specific configuration. Parameters config – A config to use when generating the schema. Returns A pydantic model that can be used to validate output. invoke(input: Union[str, BaseMessage], config: Optional[RunnableConfig] = None) → T¶ Transform a single input into an output. Override to implement. Parameters input – The input to the runnable. config – A config to use when invoking the runnable. The config supports standard keys like ‘tags’, ‘metadata’ for tracing
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-5
The config supports standard keys like ‘tags’, ‘metadata’ for tracing purposes, ‘max_concurrency’ for controlling how much work to do in parallel, and other keys. Please refer to the RunnableConfig for more details. Returns The output of the runnable. classmethod is_lc_serializable() → bool¶ Is this class serializable? json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod lc_id() → List[str]¶ A unique identifier for this class for serialization purposes. The unique identifier is a list of strings that describes the path to the object. map() → Runnable[List[Input], List[Output]]¶ Return a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input. parse(text: str) → str[source]¶ Parse a single string model output into some structure. Parameters text – String output of a language model. Returns Structured output. classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-6
classmethod parse_obj(obj: Any) → Model¶ classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ parse_result(result: List[Generation], *, partial: bool = False) → T¶ Parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, whichis assumed to be the highest-likelihood Generation. Parameters result – A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. Returns Structured output. parse_with_prompt(completion: str, prompt: PromptValue) → Any¶ Parse the output of an LLM call with the input prompt for context. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so. Parameters completion – String output of a language model. prompt – Input PromptValue. Returns Structured output classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶ classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶ stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶ Default implementation of stream, which calls invoke. Subclasses should override this method if they support streaming output. to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶ to_json_not_implemented() → SerializedNotImplemented¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-7
to_json_not_implemented() → SerializedNotImplemented¶ transform(input: Iterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶ Default implementation of transform, which buffers input and then calls stream. Subclasses should override this method if they can start producing output while input is still being generated. classmethod update_forward_refs(**localns: Any) → None¶ Try to update ForwardRefs on fields based on this Model, globalns and localns. classmethod validate(value: Any) → Model¶ with_config(config: Optional[RunnableConfig] = None, **kwargs: Any) → Runnable[Input, Output]¶ Bind config to a Runnable, returning a new Runnable. with_fallbacks(fallbacks: Sequence[Runnable[Input, Output]], *, exceptions_to_handle: Tuple[Type[BaseException], ...] = (<class 'Exception'>,)) → RunnableWithFallbacksT[Input, Output]¶ Add fallbacks to a runnable, returning a new Runnable. Parameters fallbacks – A sequence of runnables to try if the original runnable fails. exceptions_to_handle – A tuple of exception types to handle. Returns A new Runnable that will try the original runnable, and then each fallback in order, upon failures. with_listeners(*, on_start: Optional[Listener] = None, on_end: Optional[Listener] = None, on_error: Optional[Listener] = None) → Runnable[Input, Output]¶ Bind lifecycle listeners to a Runnable, returning a new Runnable. on_start: Called before the runnable starts running, with the Run object. on_end: Called after the runnable finishes running, with the Run object. on_error: Called if the runnable throws an error, with the Run object. The Run object contains information about the run, including its id,
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-8
The Run object contains information about the run, including its id, type, input, output, error, start_time, end_time, and any tags or metadata added to the run. with_retry(*, retry_if_exception_type: ~typing.Tuple[~typing.Type[BaseException], ...] = (<class 'Exception'>,), wait_exponential_jitter: bool = True, stop_after_attempt: int = 3) → Runnable[Input, Output]¶ Create a new Runnable that retries the original runnable on exceptions. Parameters retry_if_exception_type – A tuple of exception types to retry on wait_exponential_jitter – Whether to add jitter to the wait time between retries stop_after_attempt – The maximum number of attempts to make before giving up Returns A new Runnable that retries the original runnable on exceptions. with_types(*, input_type: Optional[Type[Input]] = None, output_type: Optional[Type[Output]] = None) → Runnable[Input, Output]¶ Bind input and output types to a Runnable, returning a new Runnable. property InputType: Any¶ The type of input this runnable accepts specified as a type annotation. property OutputType: Type[langchain_core.output_parsers.base.T]¶ The type of output this runnable produces specified as a type annotation. property config_specs: List[langchain_core.runnables.utils.ConfigurableFieldSpec]¶ List configurable fields for this runnable. property input_schema: Type[pydantic.main.BaseModel]¶ The type of input this runnable accepts specified as a pydantic model. property lc_attributes: Dict¶ List of attribute names that should be included in the serialized kwargs. These attributes must be accepted by the constructor. property lc_secrets: Dict[str, str]¶ A map of constructor argument names to secret ids.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
b8879f5b1ec7-9
A map of constructor argument names to secret ids. For example,{“openai_api_key”: “OPENAI_API_KEY”} property output_schema: Type[pydantic.main.BaseModel]¶ The type of output this runnable produces specified as a pydantic model.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.VectorSQLOutputParser.html
c8ba1e27def1-0
langchain_experimental.sql.vector_sql.get_result_from_sqldb¶ langchain_experimental.sql.vector_sql.get_result_from_sqldb(db: SQLDatabase, cmd: str) → Sequence[Dict[str, Any]][source]¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.vector_sql.get_result_from_sqldb.html
d7e55d8ad23b-0
langchain_experimental.sql.base.SQLDatabaseSequentialChain¶ class langchain_experimental.sql.base.SQLDatabaseSequentialChain[source]¶ Bases: Chain Chain for querying SQL database that is a sequential chain. The chain is as follows: 1. Based on the query, determine which tables to use. 2. Based on those tables, call the normal SQL database chain. This is useful in cases where the number of tables in the database is large. Create a new model by parsing and validating input data from keyword arguments. Raises ValidationError if the input data cannot be parsed to form a valid model. param callback_manager: Optional[BaseCallbackManager] = None¶ Deprecated, use callbacks instead. param callbacks: Callbacks = None¶ Optional list of callback handlers (or callback manager). Defaults to None. Callback handlers are called throughout the lifecycle of a call to a chain, starting with on_chain_start, ending with on_chain_end or on_chain_error. Each custom chain can optionally call additional callback methods, see Callback docs for full details. param decider_chain: LLMChain [Required]¶ param memory: Optional[BaseMemory] = None¶ Optional memory object. Defaults to None. Memory is a class that gets called at the start and at the end of every chain. At the start, memory loads variables and passes them along in the chain. At the end, it saves any returned variables. There are many different types of memory - please see memory docs for the full catalog. param metadata: Optional[Dict[str, Any]] = None¶ Optional metadata associated with the chain. Defaults to None. This metadata will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-1
You can use these to eg identify a specific instance of a chain with its use case. param return_intermediate_steps: bool = False¶ param sql_chain: SQLDatabaseChain [Required]¶ param tags: Optional[List[str]] = None¶ Optional list of tags associated with the chain. Defaults to None. These tags will be associated with each call to this chain, and passed as arguments to the handlers defined in callbacks. You can use these to eg identify a specific instance of a chain with its use case. param verbose: bool [Optional]¶ Whether or not run in verbose mode. In verbose mode, some intermediate logs will be printed to the console. Defaults to the global verbose value, accessible via langchain.globals.get_verbose(). __call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) → Dict[str, Any]¶ Execute the chain. Parameters 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 the chain’s memory. return_only_outputs – Whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. 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.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-2
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 only these runtime tags will propagate to calls to other objects. metadata – Optional metadata associated with the chain. Defaults to None include_run_info – Whether to include run info in the response. Defaults to False. Returns A dict of named outputs. Should contain all outputs specified inChain.output_keys. async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶ Default implementation runs ainvoke in parallel using asyncio.gather. The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; e.g., if the underlying runnable uses an API which supports a batch mode. async acall(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) → Dict[str, Any]¶ Asynchronously execute the chain. Parameters 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 the chain’s memory. return_only_outputs – Whether to return only outputs in the response. If True, only new keys generated by this chain will be returned. If False, both input keys and new keys generated by this
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-3
returned. If False, both input keys and new keys generated by this chain will be returned. Defaults to False. 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 pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but only these runtime tags will propagate to calls to other objects. metadata – Optional metadata associated with the chain. Defaults to None include_run_info – Whether to include run info in the response. Defaults to False. Returns A dict of named outputs. Should contain all outputs specified inChain.output_keys. async ainvoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Dict[str, Any]¶ Default implementation of ainvoke, calls invoke from a thread. The default implementation allows usage of async code even if the runnable did not implement a native async version of invoke. Subclasses should override this method if they can run asynchronously. apply(input_list: List[Dict[str, Any]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) → List[Dict[str, str]]¶ Call the chain on all inputs in the list. async arun(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) → Any¶ Convenience method for executing chain. The main difference between this method and Chain.__call__ is that this method expects inputs to be passed directly in as positional arguments or
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-4
method expects inputs to be passed directly in as positional arguments or keyword arguments, whereas Chain.__call__ expects a single input dictionary with all the inputs Parameters *args – If the chain expects a single input, it can be passed in as the 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 pass to all callbacks. These will be passed in addition to tags passed to the chain during construction, but only these runtime tags will propagate to calls to other objects. **kwargs – If the chain expects multiple inputs, they can be passed in directly as keyword arguments. Returns The chain output. Example # Suppose we have a single-input chain that takes a 'question' string: await chain.arun("What's the temperature in Boise, Idaho?") # -> "The temperature in Boise is..." # Suppose we have a multi-input chain that takes a 'question' string # and 'context' string: question = "What's the temperature in Boise, Idaho?" context = "Weather report for Boise, Idaho on 07/03/23..." await chain.arun(question=question, context=context) # -> "The temperature in Boise is..." async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶ Default implementation of astream, which calls ainvoke. Subclasses should override this method if they support streaming output.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-5
Subclasses should override this method if they support streaming output. async astream_log(input: Any, config: Optional[RunnableConfig] = None, *, diff: bool = True, with_streamed_output_list: bool = True, include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Optional[Any]) → Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]¶ Stream all output from a runnable, as reported to the callback system. This includes all inner runs of LLMs, Retrievers, Tools, etc. Output is streamed as Log objects, which include a list of jsonpatch ops that describe how the state of the run has changed in each step, and the final state of the run. The jsonpatch ops can be applied in order to construct state. Parameters input – The input to the runnable. config – The config to use for the runnable. diff – Whether to yield diffs between each step, or the current state. with_streamed_output_list – Whether to yield the streamed_output list. include_names – Only include logs with these names. include_types – Only include logs with these types. include_tags – Only include logs with these tags. exclude_names – Exclude logs with these names. exclude_types – Exclude logs with these types. exclude_tags – Exclude logs with these tags. async atransform(input: AsyncIterator[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → AsyncIterator[Output]¶ Default implementation of atransform, which buffers input and calls astream.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-6
Default implementation of atransform, which buffers input and calls astream. Subclasses should override this method if they can start producing output while input is still being generated. batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → List[Output]¶ Default implementation runs invoke in parallel using a thread pool executor. The default implementation of batch works well for IO bound runnables. Subclasses should override this method if they can batch more efficiently; e.g., if the underlying runnable uses an API which supports a batch mode. bind(**kwargs: Any) → Runnable[Input, Output]¶ Bind arguments to a Runnable, returning a new Runnable. config_schema(*, include: Optional[Sequence[str]] = None) → Type[BaseModel]¶ The type of config this runnable accepts specified as a pydantic model. To mark a field as configurable, see the configurable_fields and configurable_alternatives methods. Parameters include – A list of fields to include in the config schema. Returns A pydantic model that can be used to validate config. configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) → RunnableSerializable[Input, Output]¶ configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) → RunnableSerializable[Input, Output]¶ classmethod construct(_fields_set: Optional[SetStr] = None, **values: Any) → Model¶ Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data.
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-7
Default values are respected, but no other validation is performed. Behaves as if Config.extra = ‘allow’ was set since it adds all passed values copy(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, update: Optional[DictStrAny] = None, deep: bool = False) → Model¶ Duplicate a model, optionally choose which fields to include, exclude and change. Parameters include – fields to include in new model exclude – fields to exclude from new model, as with values this takes precedence over include update – values to change/add in the new model. Note: the data is not validated before creating the new model: you should trust this data deep – set to True to make a deep copy of the model Returns new model instance dict(**kwargs: Any) → Dict¶ Dictionary representation of chain. Expects Chain._chain_type property to be implemented and for memory to benull. Parameters **kwargs – Keyword arguments passed to default pydantic.BaseModel.dict method. Returns A dictionary representation of the chain. Example chain.dict(exclude_unset=True) # -> {"_type": "foo", "verbose": False, ...}
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-8
# -> {"_type": "foo", "verbose": False, ...} classmethod from_llm(llm: BaseLanguageModel, db: SQLDatabase, query_prompt: BasePromptTemplate = PromptTemplate(input_variables=['dialect', 'input', 'table_info', 'top_k'], template='Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer. Unless the user specifies in his question a specific number of examples he wishes to obtain, always limit your query to at most {top_k} results. You can order the results by a relevant column to return the most interesting examples in the database.\n\nNever query for all the columns from a specific table, only ask for a the few relevant columns given the question.\n\nPay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.\n\nUse the following format:\n\nQuestion: Question here\nSQLQuery: SQL Query to run\nSQLResult: Result of the SQLQuery\nAnswer: Final answer here\n\nOnly use the following tables:\n{table_info}\n\nQuestion: {input}'), decider_prompt: BasePromptTemplate = PromptTemplate(input_variables=['query', 'table_names'], output_parser=CommaSeparatedListOutputParser(), template='Given the below input question and list of potential tables, output a comma separated list of the table names that may be necessary to answer this question.\n\nQuestion: {query}\n\nTable Names: {table_names}\n\nRelevant Table Names:'), **kwargs: Any) → SQLDatabaseSequentialChain[source]¶ Load the necessary chains. classmethod from_orm(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-9
Load the necessary chains. classmethod from_orm(obj: Any) → Model¶ get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶ Get a pydantic model that can be used to validate input to the runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic input schema that depends on which configuration the runnable is invoked with. This method allows to get an input schema for a specific configuration. Parameters config – A config to use when generating the schema. Returns A pydantic model that can be used to validate input. classmethod get_lc_namespace() → List[str]¶ Get the namespace of the langchain object. For example, if the class is langchain.llms.openai.OpenAI, then the namespace is [“langchain”, “llms”, “openai”] get_output_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶ Get a pydantic model that can be used to validate output to the runnable. Runnables that leverage the configurable_fields and configurable_alternatives methods will have a dynamic output schema that depends on which configuration the runnable is invoked with. This method allows to get an output schema for a specific configuration. Parameters config – A config to use when generating the schema. Returns A pydantic model that can be used to validate output. invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Dict[str, Any]¶ Transform a single input into an output. Override to implement. Parameters input – The input to the runnable. config – A config to use when invoking the runnable. The config supports standard keys like ‘tags’, ‘metadata’ for tracing
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html
d7e55d8ad23b-10
The config supports standard keys like ‘tags’, ‘metadata’ for tracing purposes, ‘max_concurrency’ for controlling how much work to do in parallel, and other keys. Please refer to the RunnableConfig for more details. Returns The output of the runnable. classmethod is_lc_serializable() → bool¶ Is this class serializable? json(*, include: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, exclude: Optional[Union[AbstractSetIntStr, MappingIntStrAny]] = None, by_alias: bool = False, skip_defaults: Optional[bool] = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Optional[Callable[[Any], Any]] = None, models_as_dict: bool = True, **dumps_kwargs: Any) → unicode¶ Generate a JSON representation of the model, include and exclude arguments as per dict(). encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps(). classmethod lc_id() → List[str]¶ A unique identifier for this class for serialization purposes. The unique identifier is a list of strings that describes the path to the object. map() → Runnable[List[Input], List[Output]]¶ Return a new Runnable that maps a list of inputs to a list of outputs, by calling invoke() with each input. classmethod parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶ classmethod parse_obj(obj: Any) → Model¶
https://api.python.langchain.com/en/latest/sql/langchain_experimental.sql.base.SQLDatabaseSequentialChain.html