Tony20100/langchain_full huggingface dataset:
color: str = Field(..., description="The dog's color")
    fav_food: Optional[str] = Field(None, description="The dog's favorite food")
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are an extraction algorithm. Please extract every possible instance"),
        ('human', '{input}')
    ]
)
structured_llm = create_structured_output_runnable(
    RecordDog,
    llm,
    mode="openai-tools",
    enforce_function_usage=True,
    return_single=True
)
structured_llm.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
# -> RecordDog(name="Harry", color="brown", fav_food="chicken")
OpenAI tools example with dict schema (mode=”openai-tools”):from typing import Optional
from langchain.chains import create_structured_output_runnable
from langchain_openai import ChatOpenAI
dog_schema = {
    "type": "function",
    "function": {
        "name": "record_dog",
        "description": "Record some identifying information about a dog.",
        "parameters": {
            "type": "object",
            "properties": {
                "name": {
                    "description": "The dog's name",
                    "type": "string"
                },
                "color": {
                    "description": "The dog's color",
                    "type": "string"
                },
                "fav_food": {
                    "description": "The dog's favorite food",
                    "type": "string"
                }
            },
            "required": ["name", "color"]
        }
    }
},
            "required": ["name", "color"]
        }
    }
}
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
structured_llm = create_structured_output_runnable(
    dog_schema,
    llm,
    mode="openai-tools",
    enforce_function_usage=True,
    return_single=True
)
structured_llm.invoke("Harry was a chubby brown beagle who loved chicken")
# -> {'name': 'Harry', 'color': 'brown', 'fav_food': 'chicken'}
OpenAI functions example (mode=”openai-functions”):from typing import Optional
from langchain.chains import create_structured_output_runnable
from langchain_openai import ChatOpenAI
from langchain_core.pydantic_v1 import BaseModel, Field
class Dog(BaseModel):
    '''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")
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-functions")
structured_llm.invoke("Harry was a chubby brown beagle who loved chicken")
# -> Dog(name="Harry", color="brown", fav_food="chicken")
OpenAI functions with prompt example:from typing import Optional
from langchain.chains import create_structured_output_runnable
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.pydantic_v1 import BaseModel, Field
class Dog(BaseModel):
    '''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")
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-functions")
system = '''Extract information about any dogs mentioned in the user input.'''
prompt = ChatPromptTemplate.from_messages(
    [("system", system), ("human", "{input}"),]
)
chain = prompt | structured_llm
chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
# -> Dog(name="Harry", color="brown", fav_food="chicken")
OpenAI json response format example (mode=”openai-json”):from typing import Optional
from langchain.chains import create_structured_output_runnable
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
class Dog(BaseModel):
    '''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")
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
structured_llm = create_structured_output_runnable(Dog, llm, mode="openai-json")
system = '''You are a world class assistant for extracting information in structured JSON formats.
Extract a valid JSON blob from the user input that matches the following JSON Schema:
{output_schema}'''
prompt = ChatPromptTemplate.from_messages(
    [("system", system), ("human", "{input}"),]
)
chain = prompt | structured_llm
chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
Notes
Deprecated since version 0.1.17: LangChain has introduced a method called with_structured_output that is available on ChatModels capable of tool calling. You can read more about the method here: https://python.langchain.com/docs/modules/model_io/chat/structured_output/ Please follow our extraction use case documentation for more guidelines on how to do information extraction with LLMs. https://python.langchain.com/docs/use_cases/extraction/. If you notice other issues, please provide feedback here: https://github.com/langchain-ai/langchain/discussions/18154 Use
         from langchain_core.pydantic_v1 import BaseModel, Field
         from langchain_anthropic import ChatAnthropic
class Joke(BaseModel):setup: str = Field(description=”The setup of the joke”)
punchline: str = Field(description=”The punchline to the joke”)
# Or any other chat model that supports tools.
# Please reference to to the documentation of structured_output
# to see an up to date list of which models support
# with_structured_output.
model = ChatAnthropic(model=”claude-3-opus-20240229”, temperature=0)
structured_llm = model.with_structured_output(Joke)
structured_llm.invoke(“Tell me a joke about cats.
langchain.chains.router.base.MultiRouteChain¶
class langchain.chains.router.base.MultiRouteChain[source]¶
Bases: Chain
Use a single chain to route an input to one of multiple candidate 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 default_chain: Chain [Required]¶
Default chain to use when none of the destination chains are suitable.
param destination_chains: Mapping[str, Chain] [Required]¶
Chains that return final answer to inputs.
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 router_chain: RouterChain [Required]¶
Chain that routes inputs to destination chains.
langchain.chains.qa_with_sources.loading.load_qa_with_sources_chain¶
langchain.chains.qa_with_sources.loading.load_qa_with_sources_chain(llm: BaseLanguageModel, chain_type: str = 'stuff', verbose: Optional[bool] = None, **kwargs: Any) → BaseCombineDocumentsChain[source]¶
Load a question answering with sources chain.
Parameters
llm (BaseLanguageModel) – Language Model to use in the chain.
chain_type (str) – Type of document combining chain to use. Should be one of “stuff”,
“map_reduce”, “refine” and “map_rerank”.
verbose (Optional[bool]) – Whether chains should be run in verbose mode or not. Note that this
applies to all chains that make up the final chain.
kwargs (Any) – 
Returns
A chain to use for question answering with sources.
Return type
BaseCombineDocumentsChain
Examples using load_qa_with_sources_chain¶
Chat Over Documents with Vectara
langchain_community.chains.pebblo_retrieval.models.SemanticContext¶
class langchain_community.chains.pebblo_retrieval.models.SemanticContext[source]¶
Bases: BaseModel
Class for a semantic context.
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 pebblo_semantic_entities: Optional[SemanticEntities] = None¶
param pebblo_semantic_topics: Optional[SemanticTopics] = None¶
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
Parameters
_fields_set (Optional[SetStr]) – 
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
langchain_community.chains.ernie_functions.base.create_ernie_fn_chain¶
langchain_community.chains.ernie_functions.base.create_ernie_fn_chain(functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]], llm: BaseLanguageModel, prompt: BasePromptTemplate, *, output_key: str = 'function', output_parser: Optional[BaseLLMOutputParser] = None, **kwargs: Any) → LLMChain[source]¶
[Legacy] Create an LLM chain that uses Ernie 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 Ernie 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 Ernie function-calling API.
prompt (BasePromptTemplate) – BasePromptTemplate to pass to the model.
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
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.ernie_functions import create_ernie_fn_chain
from langchain_community.chat_models import ErnieBotChat
from langchain_core.prompts import ChatPromptTemplate
from langchain.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")
llm = ErnieBotChat(model_name="ERNIE-Bot-4")
prompt = ChatPromptTemplate.from_messages(
    [
        ("user", "Make calls to the relevant function to record the entities in the following input: {input}"),
        ("assistant", "OK!"),
        ("user", "Tip: Make sure to answer in the correct format"),
langchain_google_vertexai.chains.create_structured_runnable¶
langchain_google_vertexai.chains.create_structured_runnable(function: Union[Type[BaseModel], Sequence[Type[BaseModel]]], llm: Runnable, *, prompt: Optional[BasePromptTemplate] = None, use_extra_step: bool = False) → Runnable[source]¶
Create a runnable sequence that uses OpenAI functions.
Parameters
function (Union[Type[BaseModel], Sequence[Type[BaseModel]]]) – Either a single pydantic.BaseModel class or a sequence
of pydantic.BaseModels classes.
For best results, pydantic.BaseModels
should have descriptions of the parameters.
llm (Runnable) – Language model to use,
assumed to support the Google Vertex function-calling API.
prompt (Optional[BasePromptTemplate]) – BasePromptTemplate to pass to the model.
use_extra_step (bool) – whether to make an extra step to parse output into a function
Returns
A runnable sequence that will pass in the given functions to the model when run.
Return type
Runnable
Example
from typing import Optional
from langchain_google_vertexai import ChatVertexAI, create_structured_runnable
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")
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")
llm = ChatVertexAI(model_name="gemini-pro")
prompt = ChatPromptTemplate.from_template("""
You are a world class algorithm for recording entities.
Make calls to the relevant function to record the entities in the following input: {input}
Tip: Make sure to answer in the correct format"""
                         )
chain = create_structured_runnable([RecordPerson, RecordDog], llm, prompt=prompt)
chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
# -> RecordDog(name="Harry", color="brown", fav_food="chicken")
Examples using create_structured_runnable¶
ChatVertexAI
langchain_community.chains.graph_qa.base.GraphQAChain¶
class langchain_community.chains.graph_qa.base.GraphQAChain[source]¶
Bases: Chain
Chain for question-answering against a graph.
Security note: Make sure that the database connection uses credentialsthat are narrowly-scoped to only include necessary permissions.
Failure to do so may result in data corruption or loss, since the calling
code may attempt commands that would result in deletion, mutation
of data if appropriately prompted or reading sensitive data if such
data is present in the database.
The best way to guard against such negative outcomes is to (as appropriate)
limit the permissions granted to the credentials used with this tool.
See https://python.langchain.com/docs/security for more information.
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 entity_extraction_chain: LLMChain [Required]¶
param graph: NetworkxEntityGraph [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
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 qa_chain: LLMChain [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]¶
[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
# -> {"_type": "foo", "verbose": False, ...}
classmethod from_llm(llm: BaseLanguageModel, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['context', 'question'], template="Use the following knowledge triplets to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:"), entity_prompt: BasePromptTemplate = PromptTemplate(input_variables=['input'], template="Extract all entities from the following text. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.\n\nReturn the output as a single comma-separated list, or NONE if there is nothing of note to return.\n\nEXAMPLE\ni'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.\nOutput: Langchain\nEND OF EXAMPLE\n\nEXAMPLE\ni'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Sam.\nOutput: Langchain, Sam\nEND OF EXAMPLE\n\nBegin!\n\n{input}\nOutput:"), **kwargs: Any) → GraphQAChain[source]¶
Initialize from LLM.
Parameters
llm (BaseLanguageModel) – 
qa_prompt (BasePromptTemplate) – 
entity_prompt (BasePromptTemplate) – 
kwargs (Any) – 
Return type
GraphQAChain
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
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 GraphQAChain¶
NetworkX
langchain.chains.history_aware_retriever.create_history_aware_retriever¶
langchain.chains.history_aware_retriever.create_history_aware_retriever(llm: Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[BaseMessage, str]], retriever: Runnable[str, List[Document]], prompt: BasePromptTemplate) → Runnable[Any, List[Document]][source]¶
Create a chain that takes conversation history and returns documents.
If there is no chat_history, then the input is just passed directly to the
retriever. If there is chat_history, then the prompt and LLM will be used
to generate a search query. That search query is then passed to the retriever.
Parameters
llm (Runnable[Union[PromptValue, str, Sequence[Union[BaseMessage, List[str], Tuple[str, str], str, Dict[str, Any]]]], Union[BaseMessage, str]]) – Language model to use for generating a search term given chat history
retriever (Runnable[str, List[Document]]) – RetrieverLike object that takes a string as input and outputs
a list of Documents.
prompt (BasePromptTemplate) – The prompt used to generate the search query for the retriever.
Returns
An LCEL Runnable. The runnable input must take in input, and if there
is chat history should take it in the form of chat_history.
The Runnable output is a list of Documents
Return type
Runnable[Any, List[Document]]
Example
# pip install -U langchain langchain-community
from langchain_community.chat_models import ChatOpenAI
from langchain.chains import create_history_aware_retriever
from langchain import hub
rephrase_prompt = hub.pull("langchain-ai/chat-langchain-rephrase")
rephrase_prompt = hub.pull("langchain-ai/chat-langchain-rephrase")
llm = ChatOpenAI()
retriever = ...
chat_retriever_chain = create_history_aware_retriever(
    llm, retriever, rephrase_prompt
)
chain.invoke({"input": "...", "chat_history": })
Examples using create_history_aware_retriever¶
Conversational RAG
How to add chat history
How to stream results from your RAG application