Tony20100/langchain_full huggingface dataset:
Return type
str
Example
completion = llm.predict(adjective="funny")
async apredict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[str, List[str], Dict[str, str]][source]¶
Call apredict and then parse the results.
Parameters
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
kwargs (Any) – 
Return type
Union[str, List[str], Dict[str, str]]
async aprep_inputs(inputs: Union[Dict[str, Any], Any]) → Dict[str, str]¶
Prepare chain inputs, including adding inputs from memory.
Parameters
inputs (Union[Dict[str, Any], Any]) – 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.
Return type
Dict[str, str]
async aprep_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 (Dict[str, str]) – Dictionary of chain inputs, including any inputs added by chain
memory.
outputs (Dict[str, str]) – Dictionary of initial chain outputs.
return_only_outputs (bool) – 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.
Return type
Dict[str, str]
Returns
A dict of the final chain outputs.
Return type
Dict[str, str]
async aprep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None) → Tuple[List[PromptValue], Optional[List[str]]][source]¶
Prepare prompts from inputs.
Parameters
input_list (List[Dict[str, Any]]) – 
run_manager (Optional[AsyncCallbackManagerForChainRun]) – 
Return type
Tuple[List[PromptValue], Optional[List[str]]]
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¶
[Deprecated] 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
*args (Any) – If the chain expects a single input, it can be passed in as the
sole positional argument.
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.
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.
**kwargs (Any) – If the chain expects multiple inputs, they can be passed in
directly as keyword arguments.
directly as keyword arguments.
metadata (Optional[Dict[str, Any]]) – 
**kwargs – 
Returns
The chain output.
Return type
Any
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..."
Notes
Deprecated since version langchain==0.1.0: Use ainvoke instead.
assign(**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]]]]) → RunnableSerializable[Any, Any]¶
Assigns new fields to the dict output of this runnable.
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())
values (Any) – 
Return type
Model
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 (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to include in new model
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – 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 (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
create_outputs(llm_result: LLMResult) → List[Dict[str, Any]][source]¶
Create outputs from response.
Parameters
llm_result (LLMResult) – 
Return type
List[Dict[str, Any]]
dict(**kwargs: Any) → Dict¶
Dictionary representation of chain.
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
**kwargs (Any) – Keyword arguments passed to default pydantic.BaseModel.dict
method.
Returns
A dictionary representation of the chain.
Return type
Dict
Example
chain.dict(exclude_unset=True)
# -> {"_type": "foo", "verbose": False, ...}
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
Parameters
obj (Any) – 
Return type
Model
classmethod from_string(llm: BaseLanguageModel, template: str) → LLMChain[source]¶
Create LLMChain from LLM and template.
Parameters
llm (BaseLanguageModel) – 
template (str) – 
Return type
LLMChain
generate(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) → LLMResult[source]¶
Generate LLM result from inputs.
Parameters
input_list (List[Dict[str, Any]]) – 
run_manager (Optional[CallbackManagerForChainRun]) – 
Return type
LLMResult
get_graph(config: Optional[RunnableConfig] = None) → Graph¶
Return a graph representation of this runnable.
Parameters
config (Optional[RunnableConfig]) – 
Return type
Graph
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 (Optional[RunnableConfig]) – A config to use when generating the schema.
Returns
A pydantic model that can be used to validate input.
Return type
Type[BaseModel]
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”]
Return type
List[str]
def add_one(x: int) -> int:
    return x + 1
def mul_two(x: int) -> int:
    return x * 2
runnable_1 = RunnableLambda(add_one)
runnable_2 = RunnableLambda(mul_two)
sequence = runnable_1.pipe(runnable_2)
# Or equivalently:
# sequence = runnable_1 | runnable_2
# sequence = RunnableSequence(first=runnable_1, last=runnable_2)
sequence.invoke(1)
await sequence.ainvoke(1)
# -> 4
sequence.batch([1, 2, 3])
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]
predict(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → str[source]¶
Format prompt with kwargs and pass to LLM.
Parameters
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – Callbacks to pass to LLMChain
**kwargs (Any) – Keys to pass to prompt template.
Returns
Completion from LLM.
Return type
str
Example
completion = llm.predict(adjective="funny")
predict_and_parse(callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[str, List[str], Dict[str, Any]][source]¶
Call predict and then parse the results.
Parameters
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
kwargs (Any) – 
Return type
kwargs (Any) – 
Return type
Union[str, List[str], Dict[str, Any]]
prep_inputs(inputs: Union[Dict[str, Any], Any]) → Dict[str, str]¶
Prepare chain inputs, including adding inputs from memory.
Parameters
inputs (Union[Dict[str, Any], Any]) – 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.
Return type
Dict[str, str]
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 (Dict[str, str]) – Dictionary of chain inputs, including any inputs added by chain
memory.
outputs (Dict[str, str]) – Dictionary of initial chain outputs.
return_only_outputs (bool) – 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.
Return type
Dict[str, str]
prep_prompts(input_list: List[Dict[str, Any]], run_manager: Optional[CallbackManagerForChainRun] = None) → Tuple[List[PromptValue], Optional[List[str]]][source]¶
Prepare prompts from inputs.
Parameters
input_list (List[Dict[str, Any]]) – 
run_manager (Optional[CallbackManagerForChainRun]) – 
Return type
Tuple[List[PromptValue], Optional[List[str]]]
output_type (Optional[Type[Output]]) – 
Return type
Runnable[Input, Output]
property InputType: Type[Input]¶
The type of input this runnable accepts specified as a type annotation.
property OutputType: Type[Output]¶
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 LLMChain¶
# Oracle Cloud Infrastructure Generative AI
Aim
Alibaba Cloud PAI EAS
Anyscale
Aphrodite Engine
Argilla
Azure ML
Banana
Baseten
Bittensor
C Transformers
CTranslate2
CerebriumAI
Chat Over Documents with Vectara
ChatGLM
Clarifai
Cloudflare Workers AI
Comet
Context
Dall-E Image Generator
DeepInfra
Eden AI
Flyte
ForefrontAI
GPT4All
GigaChat
Google Cloud Vertex AI Reranker
GooseAI
Gradient
Huggingface Endpoints
IPEX-LLM
Javelin AI Gateway
Javelin AI Gateway Tutorial
IPEX-LLM
Javelin AI Gateway
Javelin AI Gateway Tutorial
Llama2Chat
MLflow
MLflow AI Gateway
MLflow Deployments for LLMs
Memorize
Minimax
Modal
MosaicML
Motörhead
NLP Cloud
Nebula (Symbl.ai)
OctoAI
OpaquePrompts
OpenLLM
OpenLM
Petals
PipelineAI
Predibase
Prediction Guard
Ray Serve
RePhraseQuery
Rebuff
Reddit Search 
Replicate
Run LLMs locally
Runhouse
SageMaker Tracking
Shale Protocol
Solar
StochasticAI
Summarize Text
TextGen
Weights & Biases
Writer
Xorbits Inference (Xinference)
YandexGPT
Yellowbrick
Yuan2.0
Zapier Natural Language Actions
vLLM
langchain.chains.flare.base.FlareChain¶
class langchain.chains.flare.base.FlareChain[source]¶
Bases: Chain
Chain that combines a retriever, a question generator,
and a response generator.
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 max_iter: int = 10¶
Maximum number of iterations.
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 min_prob: float = 0.2¶
Minimum probability for a token to be considered low confidence.
param min_token_gap: int = 5¶
Minimum number of tokens between two low confidence spans.
Minimum number of tokens between two low confidence spans.
param num_pad_tokens: int = 2¶
Number of tokens to pad around a low confidence span.
param output_parser: FinishedOutputParser [Optional]¶
Parser that determines whether the chain is finished.
param question_generator_chain: QuestionGeneratorChain [Required]¶
Chain that generates questions from uncertain spans.
param response_chain: _ResponseChain [Required]¶
Chain that generates responses from user input and context.
param retriever: BaseRetriever [Required]¶
Retriever that retrieves relevant documents from a user input.
param start_with_retrieval: bool = True¶
Whether to start with retrieval.
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]¶
[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
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – fields to exclude from new model, as with values this takes precedence over include
update (Optional[DictStrAny]) – 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 (bool) – set to True to make a deep copy of the model
self (Model) – 
Returns
new model instance
Return type
Model
dict(**kwargs: Any) → Dict¶
Dictionary representation of chain.
Expects Chain._chain_type property to be implemented and for memory to benull.
Parameters
**kwargs (Any) – Keyword arguments passed to default pydantic.BaseModel.dict
method.
Returns
A dictionary representation of the chain.
Return type
Dict
Example
chain.dict(exclude_unset=True)
# -> {"_type": "foo", "verbose": False, ...}
classmethod from_llm(llm: BaseLanguageModel, max_generation_len: int = 32, **kwargs: Any) → FlareChain[source]¶
Creates a FlareChain from a language model.
Parameters
llm (BaseLanguageModel) – Language model to use.
max_generation_len (int) – Maximum length of the generated response.
**kwargs (Any) – Additional arguments to pass to the constructor.
Returns
FlareChain class with the given language model.
Return type
FlareChain
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
get_graph(config: Optional[RunnableConfig] = None) → Graph¶
Return a graph representation of this runnable.
Parameters
config (Optional[RunnableConfig]) – 
Return type
Graph
output_type (Optional[Type[Output]]) – 
Return type
Runnable[Input, Output]
property InputType: Type[Input]¶
The type of input this runnable accepts specified as a type annotation.
property OutputType: Type[Output]¶
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_keys: List[str]¶
Input keys for the chain.
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_keys: List[str]¶
Output keys for the chain.
property output_schema: Type[BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
langchain.chains.openai_functions.base.create_openai_fn_chain¶
langchain.chains.openai_functions.base.create_openai_fn_chain(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], llm: BaseLanguageModel, prompt: BasePromptTemplate, *, enforce_single_function_usage: bool = True, output_key: str = 'function', output_parser: Optional[BaseLLMOutputParser] = None, **kwargs: Any) → LLMChain[source]¶
[Deprecated] [Legacy] Create an LLM chain that uses OpenAI functions.
Parameters
functions (Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]]) – A sequence of either dictionaries, pydantic.BaseModels classes, or
Python functions. If dictionaries are passed in, they are assumed to
already be a valid OpenAI functions. If only a single
function is passed in, then it will be enforced that the model use that
function. pydantic.BaseModels and Python functions should have docstrings
describing what the function does. For best results, pydantic.BaseModels
should have descriptions of the parameters and Python functions should have
Google Python style args descriptions in the docstring. Additionally,
Python functions should only use primitive types (str, int, float, bool) or
pydantic.BaseModels for arguments.
llm (BaseLanguageModel) – Language model to use, assumed to support the OpenAI function-calling API.
prompt (BasePromptTemplate) – BasePromptTemplate to pass to the model.
enforce_single_function_usage (bool) – only used if a single function is passed in. If
True, then the model will be forced to use the given function. If False,
then the model will be given the option to use the given function or not.
then the model will be given the option to use the given function or not.
output_key (str) – The key to use when returning the output in LLMChain.__call__.
output_parser (Optional[BaseLLMOutputParser]) – BaseLLMOutputParser to use for parsing model outputs. By default
will be inferred from the function types. If pydantic.BaseModels are passed
in, then the OutputParser will try to parse outputs using those. Otherwise
model outputs will simply be parsed as JSON. If multiple functions are
passed in and they are not pydantic.BaseModels, the chain output will
include both the name of the function that was returned and the arguments
to pass to the function.
kwargs (Any) – 
Returns
An LLMChain that will pass in the given functions to the model when run.
Return type
LLMChain
Example
from typing import Optional
from langchain.chains.openai_functions import create_openai_fn_chain
from langchain_community.chat_models import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
class RecordPerson(BaseModel):
    """Record some identifying information about a person."""
    name: str = Field(..., description="The person's name")
    age: int = Field(..., description="The person's age")
    fav_food: Optional[str] = Field(None, description="The person's favorite food")
class RecordDog(BaseModel):
    """Record some identifying information about a dog."""
    name: str = Field(..., description="The dog's name")
    color: str = Field(..., description="The dog's color")
    fav_food: Optional[str] = Field(None, description="The dog's favorite food")
fav_food: Optional[str] = Field(None, description="The dog's favorite food")
llm = ChatOpenAI(model="gpt-4", temperature=0)
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a world class algorithm for recording entities."),
        ("human", "Make calls to the relevant function to record the entities in the following input: {input}"),
        ("human", "Tip: Make sure to answer in the correct format"),
    ]
)
chain = create_openai_fn_chain([RecordPerson, RecordDog], llm, prompt)
chain.run("Harry was a chubby brown beagle who loved chicken")
# -> RecordDog(name="Harry", color="brown", fav_food="chicken")
Notes
Deprecated since version 0.1.1: Use create_openai_fn_runnable instead.
langchain.chains.llm_checker.base.LLMCheckerChain¶
class langchain.chains.llm_checker.base.LLMCheckerChain[source]¶
Bases: Chain
Chain for question-answering with self-verification.
Example
from langchain_community.llms import OpenAI
from langchain.chains import LLMCheckerChain
llm = OpenAI(temperature=0.7)
checker_chain = LLMCheckerChain.from_llm(llm)
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 check_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['assertions'], template='Here is a bullet point list of assertions:\n{assertions}\nFor each assertion, determine whether it is true or false. If it is false, explain why.\n\n')¶
[Deprecated]
param create_draft_answer_prompt: PromptTemplate = PromptTemplate(input_variables=['question'], template='{question}\n\n')¶
[Deprecated]
param list_assertions_prompt: PromptTemplate = PromptTemplate(input_variables=['statement'], template='Here is a statement:\n{statement}\nMake a bullet point list of the assumptions you made when producing the above statement.\n\n')¶
[Deprecated]
param llm: Optional[BaseLanguageModel] = None¶
[Deprecated] LLM wrapper to use.