viruPVS/langchain-docs huggingface dataset:
langchain_community.storage.redis.RedisStore¶
class langchain_community.storage.redis.RedisStore(*, client: Any = None, redis_url: Optional[str] = None, client_kwargs: Optional[dict] = None, ttl: Optional[int] = None, namespace: Optional[str] = None)[source]¶
BaseStore implementation using Redis as the underlying store.
Examples
Create a RedisStore instance and perform operations on it:
# Instantiate the RedisStore with a Redis connection
from langchain_community.storage import RedisStore
from langchain_community.utilities.redis import get_client
client = get_client('redis://localhost:6379')
redis_store = RedisStore(client)
# Set values for keys
redis_store.mset([("key1", b"value1"), ("key2", b"value2")])
# Get values for keys
values = redis_store.mget(["key1", "key2"])
# [b"value1", b"value2"]
# Delete keys
redis_store.mdelete(["key1"])
# Iterate over keys
for key in redis_store.yield_keys():
    print(key)
Initialize the RedisStore with a Redis connection.
Must provide either a Redis client or a redis_url with optional client_kwargs.
Parameters
client – A Redis connection instance
redis_url – redis url
client_kwargs – Keyword arguments to pass to the Redis client
ttl – time to expire keys in seconds if provided,
if None keys will never expire
namespace – if provided, all keys will be prefixed with this namespace
Methods
__init__(*[, client, redis_url, ...])
Initialize the RedisStore with a Redis connection.
mdelete(keys)
Delete the given keys.
mget(keys)
Get the values associated with the given keys.
mset(key_value_pairs)
Set the given key-value pairs.
yield_keys(*[, prefix])
Set the given key-value pairs.
yield_keys(*[, prefix])
Yield keys in the store.
__init__(*, client: Any = None, redis_url: Optional[str] = None, client_kwargs: Optional[dict] = None, ttl: Optional[int] = None, namespace: Optional[str] = None) → None[source]¶
Initialize the RedisStore with a Redis connection.
Must provide either a Redis client or a redis_url with optional client_kwargs.
Parameters
client – A Redis connection instance
redis_url – redis url
client_kwargs – Keyword arguments to pass to the Redis client
ttl – time to expire keys in seconds if provided,
if None keys will never expire
namespace – if provided, all keys will be prefixed with this namespace
mdelete(keys: Sequence[str]) → None[source]¶
Delete the given keys.
mget(keys: Sequence[str]) → List[Optional[bytes]][source]¶
Get the values associated with the given keys.
mset(key_value_pairs: Sequence[Tuple[str, bytes]]) → None[source]¶
Set the given key-value pairs.
yield_keys(*, prefix: Optional[str] = None) → Iterator[str][source]¶
Yield keys in the store.
Examples using RedisStore¶
Caching
langchain.storage.in_memory.InMemoryBaseStore¶
class langchain.storage.in_memory.InMemoryBaseStore[source]¶
In-memory implementation of the BaseStore using a dictionary.
store¶
The underlying dictionary that stores
the key-value pairs.
Type
Dict[str, Any]
Examples
from langchain.storage import InMemoryStore
store = InMemoryStore()
store.mset([('key1', 'value1'), ('key2', 'value2')])
store.mget(['key1', 'key2'])
# ['value1', 'value2']
store.mdelete(['key1'])
list(store.yield_keys())
# ['key2']
list(store.yield_keys(prefix='k'))
# ['key2']
Initialize an empty store.
Methods
__init__()
Initialize an empty store.
mdelete(keys)
Delete the given keys and their associated values.
mget(keys)
Get the values associated with the given keys.
mset(key_value_pairs)
Set the values for the given keys.
yield_keys([prefix])
Get an iterator over keys that match the given prefix.
__init__() → None[source]¶
Initialize an empty store.
mdelete(keys: Sequence[str]) → None[source]¶
Delete the given keys and their associated values.
Parameters
keys (Sequence[str]) – A sequence of keys to delete.
mget(keys: Sequence[str]) → List[Optional[V]][source]¶
Get the values associated with the given keys.
Parameters
keys (Sequence[str]) – A sequence of keys.
Returns
A sequence of optional values associated with the keys.
If a key is not found, the corresponding value will be None.
mset(key_value_pairs: Sequence[Tuple[str, V]]) → None[source]¶
Set the values for the given keys.
Parameters
Set the values for the given keys.
Parameters
key_value_pairs (Sequence[Tuple[str, V]]) – A sequence of key-value pairs.
Returns
None
yield_keys(prefix: Optional[str] = None) → Iterator[str][source]¶
Get an iterator over keys that match the given prefix.
Parameters
prefix (str, optional) – The prefix to match. Defaults to None.
Returns
An iterator over keys that match the given prefix.
Return type
Iterator[str]
langchain.chains.query_constructor.base.load_query_constructor_chain¶
langchain.chains.query_constructor.base.load_query_constructor_chain(llm: ~langchain_core.language_models.base.BaseLanguageModel, document_contents: str, attribute_info: ~typing.Sequence[~typing.Union[~langchain.chains.query_constructor.schema.AttributeInfo, dict]], examples: ~typing.Optional[~typing.List] = None, allowed_comparators: ~typing.Sequence[~langchain.chains.query_constructor.ir.Comparator] = (<Comparator.EQ: 'eq'>, <Comparator.NE: 'ne'>, <Comparator.GT: 'gt'>, <Comparator.GTE: 'gte'>, <Comparator.LT: 'lt'>, <Comparator.LTE: 'lte'>, <Comparator.CONTAIN: 'contain'>, <Comparator.LIKE: 'like'>, <Comparator.IN: 'in'>, <Comparator.NIN: 'nin'>), allowed_operators: ~typing.Sequence[~langchain.chains.query_constructor.ir.Operator] = (<Operator.AND: 'and'>, <Operator.OR: 'or'>, <Operator.NOT: 'not'>), enable_limit: bool = False, schema_prompt: ~typing.Optional[~langchain_core.prompts.base.BasePromptTemplate] = None, **kwargs: ~typing.Any) → LLMChain[source]¶
Load a query constructor chain.
Parameters
llm – BaseLanguageModel to use for the chain.
document_contents – The contents of the document to be queried.
attribute_info – Sequence of attributes in the document.
examples – Optional list of examples to use for the chain.
allowed_comparators – Sequence of allowed comparators. Defaults to all
Comparators.
allowed_operators – Sequence of allowed operators. Defaults to all Operators.
enable_limit – Whether to enable the limit operator. Defaults to False.
schema_prompt – Prompt for describing query schema. Should have string input
langchain.chains.qa_generation.base.QAGenerationChain¶
class langchain.chains.qa_generation.base.QAGenerationChain[source]¶
Bases: Chain
Base class for question-answer generation chains.
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 input_key: str = 'text'¶
Key of the input to the chain.
param k: Optional[int] = None¶
Number of questions to generate.
param llm_chain: LLMChain [Required]¶
LLM Chain that generates responses from user input and context.
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.
You can use these to eg identify a specific instance of a chain with its use case.
param output_key: str = 'questions'¶
Key of the output of the chain.
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 text_splitter: TextSplitter = <langchain.text_splitter.RecursiveCharacterTextSplitter object>¶
Text splitter that splits the input into chunks.
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
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, prompt: Optional[BasePromptTemplate] = None, **kwargs: Any) → QAGenerationChain[source]¶
Create a QAGenerationChain from a language model.
Parameters
llm – a language model
prompt – a prompt template
**kwargs – additional arguments
Returns
a QAGenerationChain class
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
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.
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¶
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
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]¶
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_keys: List[str]¶
Keys expected to be in the chain input.
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.
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_keys: List[str]¶
Keys expected to be in the chain output.
property output_schema: Type[pydantic.main.BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
langchain.chains.natbot.base.NatBotChain¶
class langchain.chains.natbot.base.NatBotChain[source]¶
Bases: Chain
Implement an LLM driven browser.
Security Note: This toolkit provides code to control a web-browser.
The web-browser can be used to navigate to:
Any URL (including any internal network URLs)
And local files
Exercise care if exposing this chain to end-users. Control who is able to
access and use this chain, and isolate the network access of the server
that hosts this chain.
See https://python.langchain.com/docs/security for more information.
Example
from langchain.chains import NatBotChain
natbot = NatBotChain.from_default("Buy me a new hat.")
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 llm: Optional[BaseLanguageModel] = None¶
[Deprecated] LLM wrapper to use.
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.
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 objective: str [Required]¶
Objective that NatBot is tasked with completing.
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
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¶
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, ...}
execute(url: str, browser_content: str) → str[source]¶
Figure out next browser command to run.
Parameters
url – URL of the site currently on.
Parameters
url – URL of the site currently on.
browser_content – Content of the page as currently displayed by the browser.
Returns
Next browser command to run.
Example
browser_content = "...."
llm_command = natbot.run("www.google.com", browser_content)
classmethod from_default(objective: str, **kwargs: Any) → NatBotChain[source]¶
Load with default LLMChain.
classmethod from_llm(llm: BaseLanguageModel, objective: str, **kwargs: Any) → NatBotChain[source]¶
Load from LLM.
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