Tony20100/langchain_full huggingface dataset:
output_type (Optional[Type[Output]]) – 
Return type
Runnable[Input, Output]
property InputType: Any¶
The type of input this runnable accepts specified as a type annotation.
property OutputType: Type[T]¶
The type of output this runnable produces specified as a type annotation.
property config_specs: List[ConfigurableFieldSpec]¶
List configurable fields for this runnable.
property input_schema: Type[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”}
name: Optional[str] = None¶
The name of the runnable. Used for debugging and tracing.
property output_schema: Type[BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
Examples using StrOutputParser¶
# Oracle Cloud Infrastructure Generative AI
AI21LLM
Apache Cassandra
AskNews
Astra DB
Build a Local RAG Application
Build a Question/Answering system over SQL data
Build a Retrieval Augmented Generation (RAG) App
Build a Simple LLM Application
ChatOllama
DSPy
Facebook Messenger
Fiddler
Fleet AI Context
How to add chat history
How to add default invocation args to a Runnable
How to add fallbacks to a runnable
How to add retrieval to chatbots
How to add values to a chain’s state
How to chain runnables
How to create a dynamic (self-constructing) chain
How to do per-user retrieval
How to create a dynamic (self-constructing) chain
How to do per-user retrieval
How to do query validation as part of SQL question-answering
How to do question answering over CSVs
How to get a RAG application to add citations
How to get your RAG application to return sources
How to inspect runnables
How to invoke runnables in parallel
How to map values to a graph database
How to pass through arguments from one step to the next
How to retrieve using multiple vectors per document
How to route between sub-chains
How to run custom functions
How to stream runnables
Hybrid Search
Jaguar Vector Database
Maritalk
Milvus Hybrid Search
NVIDIA NIMs
NVIDIA NIMs 
OpaquePrompts
Tavily Search API
UpTrain
Vectara
Volc Engine Maas
Weaviate
You.com
ZepCloudChatMessageHistory
iMessage
langchain_core.output_parsers.transform.BaseTransformOutputParser¶
class langchain_core.output_parsers.transform.BaseTransformOutputParser[source]¶
Bases: BaseOutputParser[T]
Base class for an output parser that can handle streaming input.
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.
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.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
inputs (Sequence[Input]) – 
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
AsyncIterator[Tuple[int, Union[Output, Exception]]]
exclude_tags (Optional[Sequence[str]]) – Exclude logs with these tags.
kwargs (Any) – 
Return type
Union[AsyncIterator[RunLogPatch], AsyncIterator[RunLog]]
async atransform(input: AsyncIterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) → AsyncIterator[T][source]¶
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.
Parameters
input (AsyncIterator[Union[str, BaseMessage]]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
AsyncIterator[T]
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.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
batch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → Iterator[Tuple[int, Union[Output, Exception]]]¶
Run invoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
await sequence.abatch([1, 2, 3])
# -> [4, 6, 8]
Parameters
others (Union[Runnable[Any, Other], Callable[[Any], Other]]) – 
name (Optional[str]) – 
Return type
RunnableSerializable[Input, Other]
classmethod schema(by_alias: bool = True, ref_template: unicode = '#/definitions/{model}') → DictStrAny¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
Return type
DictStrAny
classmethod schema_json(*, by_alias: bool = True, ref_template: unicode = '#/definitions/{model}', **dumps_kwargs: Any) → unicode¶
Parameters
by_alias (bool) – 
ref_template (unicode) – 
dumps_kwargs (Any) – 
Return type
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.
Parameters
input (Input) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Output]
to_json() → Union[SerializedConstructor, SerializedNotImplemented]¶
Serialize the runnable to JSON.
Return type
Union[SerializedConstructor, SerializedNotImplemented]
to_json_not_implemented() → SerializedNotImplemented¶
Return type
SerializedNotImplemented
transform(input: Iterator[Union[str, BaseMessage]], config: Optional[RunnableConfig] = None, **kwargs: Any) → Iterator[T][source]¶
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.
Parameters
langchain_core.output_parsers.openai_tools.make_invalid_tool_call¶
langchain_core.output_parsers.openai_tools.make_invalid_tool_call(raw_tool_call: Dict[str, Any], error_msg: Optional[str]) → InvalidToolCall[source]¶
Create an InvalidToolCall from a raw tool call.
Parameters
raw_tool_call (Dict[str, Any]) – 
error_msg (Optional[str]) – 
Return type
InvalidToolCall
langchain_core.output_parsers.base.BaseLLMOutputParser¶
class langchain_core.output_parsers.base.BaseLLMOutputParser[source]¶
Abstract base class for parsing the outputs of a model.
Methods
__init__()
aparse_result(result, *[, partial])
Parse a list of candidate model Generations into a specific format.
parse_result(result, *[, partial])
Parse a list of candidate model Generations into a specific format.
__init__()¶
async aparse_result(result: List[Generation], *, partial: bool = False) → T[source]¶
Parse a list of candidate model Generations into a specific format.
Parameters
result (List[Generation]) – A list of Generations to be parsed. The Generations are assumed
to be different candidate outputs for a single model input.
partial (bool) – 
Returns
Structured output.
Return type
T
abstract parse_result(result: List[Generation], *, partial: bool = False) → T[source]¶
Parse a list of candidate model Generations into a specific format.
Parameters
result (List[Generation]) – A list of Generations to be parsed. The Generations are assumed
to be different candidate outputs for a single model input.
partial (bool) – 
Returns
Structured output.
Return type
T
langchain.output_parsers.regex.RegexParser¶
class langchain.output_parsers.regex.RegexParser[source]¶
Bases: BaseOutputParser
Parse the output of an LLM call using a regex.
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 default_output_key: Optional[str] = None¶
The default key to use for the output.
param output_keys: List[str] [Required]¶
The keys to use for the output.
param regex: str [Required]¶
The regex to use to parse the output.
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.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Parameters
inputs (Sequence[Input]) –
langchain_cohere.cohere_agent.create_cohere_tools_agent¶
langchain_cohere.cohere_agent.create_cohere_tools_agent(llm: BaseLanguageModel, tools: Sequence[BaseTool], prompt: ChatPromptTemplate) → Runnable[source]¶
Parameters
llm (BaseLanguageModel) – 
tools (Sequence[BaseTool]) – 
prompt (ChatPromptTemplate) – 
Return type
Runnable
langchain.model_laboratory.ModelLaboratory¶
class langchain.model_laboratory.ModelLaboratory(chains: Sequence[Chain], names: Optional[List[str]] = None)[source]¶
Experiment with different models.
Initialize with chains to experiment with.
Parameters
chains (Sequence[Chain]) – list of chains to experiment with.
names (Optional[List[str]]) – 
Methods
__init__(chains[, names])
Initialize with chains to experiment with.
compare(text)
Compare model outputs on an input text.
from_llms(llms[, prompt])
Initialize with LLMs to experiment with and optional prompt.
__init__(chains: Sequence[Chain], names: Optional[List[str]] = None)[source]¶
Initialize with chains to experiment with.
Parameters
chains (Sequence[Chain]) – list of chains to experiment with.
names (Optional[List[str]]) – 
compare(text: str) → None[source]¶
Compare model outputs on an input text.
If a prompt was provided with starting the laboratory, then this text will be
fed into the prompt. If no prompt was provided, then the input text is the
entire prompt.
Parameters
text (str) – input text to run all models on.
Return type
None
classmethod from_llms(llms: List[BaseLLM], prompt: Optional[PromptTemplate] = None) → ModelLaboratory[source]¶
Initialize with LLMs to experiment with and optional prompt.
Parameters
llms (List[BaseLLM]) – list of LLMs to experiment with
prompt (Optional[PromptTemplate]) – Optional prompt to use to prompt the LLMs. Defaults to None.
If a prompt was provided, it should only have one input variable.
Return type
ModelLaboratory
Examples using ModelLaboratory¶
Manifest
langchain_google_community.gcs_file.GCSFileLoader¶
class langchain_google_community.gcs_file.GCSFileLoader(project_name: str, bucket: str, blob: str, loader_func: Optional[Callable[[str], BaseLoader]] = None)[source]¶
Load from GCS file.
Initialize with bucket and key name.
Parameters
project_name (str) – The name of the project to load
bucket (str) – The name of the GCS bucket.
blob (str) – The name of the GCS blob to load.
loader_func (Optional[Callable[[str], BaseLoader]]) – A loader function that instantiates a loader based on a
file_path argument. If nothing is provided, the
UnstructuredFileLoader is used.
Examples
To use an alternative PDF loader:
>> from from langchain_community.document_loaders import PyPDFLoader
>> loader = GCSFileLoader(…, loader_func=PyPDFLoader)
To use UnstructuredFileLoader with additional arguments:
>> loader = GCSFileLoader(…,
>>      loader_func=lambda x: UnstructuredFileLoader(x, mode=”elements”))
Methods
__init__(project_name, bucket, blob[, ...])
Initialize with bucket and key name.
alazy_load()
A lazy loader for Documents.
aload()
Load data into Document objects.
lazy_load()
A lazy loader for Documents.
load()
Load documents.
load_and_split([text_splitter])
Load Documents and split into chunks.
__init__(project_name: str, bucket: str, blob: str, loader_func: Optional[Callable[[str], BaseLoader]] = None)[source]¶
Initialize with bucket and key name.
Parameters
project_name (str) – The name of the project to load
bucket (str) – The name of the GCS bucket.
bucket (str) – The name of the GCS bucket.
blob (str) – The name of the GCS blob to load.
loader_func (Optional[Callable[[str], BaseLoader]]) – A loader function that instantiates a loader based on a
file_path argument. If nothing is provided, the
UnstructuredFileLoader is used.
Examples
To use an alternative PDF loader:
>> from from langchain_community.document_loaders import PyPDFLoader
>> loader = GCSFileLoader(…, loader_func=PyPDFLoader)
To use UnstructuredFileLoader with additional arguments:
>> loader = GCSFileLoader(…,
>>      loader_func=lambda x: UnstructuredFileLoader(x, mode=”elements”))
async alazy_load() → AsyncIterator[Document]¶
A lazy loader for Documents.
Return type
AsyncIterator[Document]
async aload() → List[Document]¶
Load data into Document objects.
Return type
List[Document]
lazy_load() → Iterator[Document]¶
A lazy loader for Documents.
Return type
Iterator[Document]
load() → List[Document][source]¶
Load documents.
Return type
List[Document]
load_and_split(text_splitter: Optional[TextSplitter] = None) → List[Document]¶
Load Documents and split into chunks. Chunks are returned as Documents.
Do not override this method. It should be considered to be deprecated!
Parameters
text_splitter (Optional[TextSplitter]) – TextSplitter instance to use for splitting documents.
Defaults to RecursiveCharacterTextSplitter.
Returns
List of Documents.
Return type
List[Document]
langchain.agents.mrkl.base.MRKLChain¶
class langchain.agents.mrkl.base.MRKLChain[source]¶
Bases: AgentExecutor
[Deprecated] [Deprecated] Chain that implements the MRKL system.
Notes
Deprecated since version 0.1.0.
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 agent: Union[BaseSingleActionAgent, BaseMultiActionAgent] [Required]¶
The agent to run for creating a plan and determining actions
to take at each step of the execution loop.
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 early_stopping_method: str = 'force'¶
The method to use for early stopping if the agent never
returns AgentFinish. Either ‘force’ or ‘generate’.
“force” returns a string saying that it stopped because it met atime or iteration limit.
“generate” calls the agent’s LLM Chain one final time to generatea final answer based on the previous steps.
param handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = False¶
How to handle errors raised by the agent’s output parser.
Defaults to False, which raises the error.
If true, the error will be sent back to the LLM as an observation.
If true, the error will be sent back to the LLM as an observation.
If a string, the string itself will be sent to the LLM as an observation.
If a callable function, the function will be called with the exception
as an argument, and the result of that function will be passed to the agentas an observation.
param max_execution_time: Optional[float] = None¶
The maximum amount of wall clock time to spend in the execution
loop.
param max_iterations: Optional[int] = 15¶
The maximum number of steps to take before ending the execution
loop.
Setting to ‘None’ could lead to an infinite loop.
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 return_intermediate_steps: bool = False¶
Whether to return the agent’s trajectory of intermediate steps
at the end in addition to the final output.
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.
You can use these to eg identify a specific instance of a chain with its use case.
param tools: Sequence[BaseTool] [Required]¶
The valid tools the agent can call.
param trim_intermediate_steps: Union[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]] = -1¶
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]¶
[Deprecated] Execute the chain.
Parameters
inputs (Union[Dict[str, Any], Any]) – 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 (bool) – 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 (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 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.
these runtime callbacks will propagate to calls to other objects.
tags (Optional[List[str]]) – 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[Dict[str, Any]]) – Optional metadata associated with the chain. Defaults to None
include_run_info (bool) – Whether to include run info in the response. Defaults
to False.
run_name (Optional[str]) – 
Returns
A dict of named outputs. Should contain all outputs specified inChain.output_keys.
Return type
Dict[str, Any]
Notes
Deprecated since version langchain==0.1.0: Use invoke instead.
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.
Parameters
inputs (List[Input]) – 
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 
return_exceptions (bool) – 
kwargs (Optional[Any]) – 
Return type
List[Output]
async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) → AsyncIterator[Tuple[int, Union[Output, Exception]]]¶
Run ainvoke in parallel on a list of inputs,
yielding results as they complete.
Returns a new runnable.
from langchain_community.llms.fake import FakeStreamingListLLM
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import SystemMessagePromptTemplate
from langchain_core.runnables import Runnable
from operator import itemgetter
prompt = (
    SystemMessagePromptTemplate.from_template("You are a nice assistant.")
    + "{question}"
)
llm = FakeStreamingListLLM(responses=["foo-lish"])
chain: Runnable = prompt | llm | {"str": StrOutputParser()}
chain_with_assign = chain.assign(hello=itemgetter("str") | llm)
print(chain_with_assign.input_schema.schema())
# {'title': 'PromptInput', 'type': 'object', 'properties':
{'question': {'title': 'Question', 'type': 'string'}}}
print(chain_with_assign.output_schema.schema()) #
{'title': 'RunnableSequenceOutput', 'type': 'object', 'properties':
{'str': {'title': 'Str',
'type': 'string'}, 'hello': {'title': 'Hello', 'type': 'string'}}}
Parameters
kwargs (Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any], Mapping[str, Union[Runnable[Dict[str, Any], Any], Callable[[Dict[str, Any]], Any]]]]) – 
Return type
RunnableSerializable[Any, Any]
async astream(input: Union[Dict[str, Any], Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → AsyncIterator[AddableDict]¶
Enables streaming over steps taken to reach final output.
Parameters
input (Union[Dict[str, Any], Any]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
AsyncIterator[AddableDict]