Tony20100/langchain_full huggingface dataset:
df (Any) – Pandas dataframe or list of Pandas dataframes.
agent_type (Union[AgentType, Literal['openai-tools', 'tool-calling']]) – One of “tool-calling”, “openai-tools”, “openai-functions”, or
“zero-shot-react-description”. Defaults to “zero-shot-react-description”.
“tool-calling” is recommended over the legacy “openai-tools” and
“openai-functions” types.
callback_manager (Optional[BaseCallbackManager]) – DEPRECATED. Pass “callbacks” key into ‘agent_executor_kwargs’
instead to pass constructor callbacks to AgentExecutor.
prefix (Optional[str]) – Prompt prefix string.
suffix (Optional[str]) – Prompt suffix string.
input_variables (Optional[List[str]]) – DEPRECATED. Input variables automatically inferred from
constructed prompt.
verbose (bool) – AgentExecutor verbosity.
return_intermediate_steps (bool) – Passed to AgentExecutor init.
max_iterations (Optional[int]) – Passed to AgentExecutor init.
max_execution_time (Optional[float]) – Passed to AgentExecutor init.
early_stopping_method (str) – Passed to AgentExecutor init.
agent_executor_kwargs (Optional[Dict[str, Any]]) – Arbitrary additional AgentExecutor args.
include_df_in_prompt (Optional[bool]) – Whether to include the first number_of_head_rows in the
prompt. Must be None if suffix is not None.
number_of_head_rows (int) – Number of initial rows to include in prompt if
include_df_in_prompt is True.
extra_tools (Sequence[BaseTool]) – Additional tools to give to agent on top of a PythonAstREPLTool.
engine (Literal['pandas', 'modin']) – One of “modin” or “pandas”. Defaults to “pandas”.
**kwargs (Any) – DEPRECATED. Not used, kept for backwards compatibility.
Returns
**kwargs (Any) – DEPRECATED. Not used, kept for backwards compatibility.
Returns
An AgentExecutor with the specified agent_type agent and access to
a PythonAstREPLTool with the DataFrame(s) and any user-provided extra_tools.
Return type
AgentExecutor
Example
from langchain_openai import ChatOpenAI
from langchain_experimental.agents import create_pandas_dataframe_agent
import pandas as pd
df = pd.read_csv("titanic.csv")
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
agent_executor = create_pandas_dataframe_agent(
    llm,
    df,
    agent_type="tool-calling",
    verbose=True
)
Examples using create_pandas_dataframe_agent¶
Airbyte Question Answering
How to do question answering over CSVs
Pandas Dataframe
langchain.agents.format_scratchpad.log.format_log_to_str¶
langchain.agents.format_scratchpad.log.format_log_to_str(intermediate_steps: List[Tuple[AgentAction, str]], observation_prefix: str = 'Observation: ', llm_prefix: str = 'Thought: ') → str[source]¶
Construct the scratchpad that lets the agent continue its thought process.
Parameters
intermediate_steps (List[Tuple[AgentAction, str]]) – 
observation_prefix (str) – 
llm_prefix (str) – 
Return type
str
Examples using format_log_to_str¶
Hugging Face
MLX
langchain.agents.agent.AgentExecutor¶
class langchain.agents.agent.AgentExecutor[source]¶
Bases: Chain
Agent that is using tools.
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 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
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][source]¶
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]
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_agent_and_tools(agent: Union[BaseSingleActionAgent, BaseMultiActionAgent], tools: Sequence[BaseTool], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → AgentExecutor[source]¶
Create from agent and tools.
Parameters
agent (Union[BaseSingleActionAgent, BaseMultiActionAgent]) – 
tools (Sequence[BaseTool]) – 
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
kwargs (Any) – 
Return type
AgentExecutor
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
get_input_schema(config: Optional[RunnableConfig] = None) → Type[BaseModel]¶
Parameters
config (Optional[RunnableConfig]) – 
Return type
List[BasePromptTemplate]
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 (Dict[str, Any]) – The input to the runnable.
config (Optional[RunnableConfig]) – 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.
kwargs (Any) – 
Returns
The output of the runnable.
Return type
Dict[str, Any]
classmethod is_lc_serializable() → bool¶
Is this class serializable?
Return type
bool
iter(inputs: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, include_run_info: bool = False, async_: bool = False) → AgentExecutorIterator[source]¶
Enables iteration over steps taken to reach final output.
Parameters
inputs (Any) – 
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 
include_run_info (bool) – 
async_ (bool) – 
Return type
AgentExecutorIterator
async_ (bool) – 
Return type
AgentExecutorIterator
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().
Parameters
include (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
exclude (Optional[Union[AbstractSetIntStr, MappingIntStrAny]]) – 
by_alias (bool) – 
skip_defaults (Optional[bool]) – 
exclude_unset (bool) – 
exclude_defaults (bool) – 
exclude_none (bool) – 
encoder (Optional[Callable[[Any], Any]]) – 
models_as_dict (bool) – 
dumps_kwargs (Any) – 
Return type
unicode
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.
Return type
List[str]
lookup_tool(name: str) → BaseTool[source]¶
Lookup tool by name.
Parameters
name (str) – 
Return type
BaseTool
map() → Runnable[List[Input], List[Output]]¶
Return a new Runnable that maps a list of inputs to a list of outputs,
Example
from langchain_core.runnables import RunnableLambda
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]
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
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:
chain.run("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..."
# Suppose we have a multi-input chain that takes a 'question' string
# and 'context' string:
question = "What's the temperature in Boise, Idaho?"
context = "Weather report for Boise, Idaho on 07/03/23..."
chain.run(question=question, context=context)
# -> "The temperature in Boise is..."
Notes
Deprecated since version langchain==0.1.0: Use invoke instead.
save(file_path: Union[Path, str]) → None[source]¶
Raise error - saving not supported for Agent Executors.
Parameters
file_path (Union[Path, str]) – 
Return type
None
save_agent(file_path: Union[Path, str]) → None[source]¶
Save the underlying agent.
Parameters
file_path (Union[Path, str]) – 
Return type
None
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
dumps_kwargs (Any) – 
Return type
unicode
stream(input: Union[Dict[str, Any], Any], config: Optional[RunnableConfig] = None, **kwargs: Any) → Iterator[AddableDict][source]¶
Enables streaming over steps taken to reach final output.
Parameters
input (Union[Dict[str, Any], Any]) – 
config (Optional[RunnableConfig]) – 
kwargs (Any) – 
Return type
Iterator[AddableDict]
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[Input], config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) → Iterator[Output]¶
Default implementation of transform, which buffers input and then calls stream.
Subclasses should override this method if they can start producing output while
input is still being generated.
Parameters
input (Iterator[Input]) – 
config (Optional[RunnableConfig]) – 
kwargs (Optional[Any]) – 
Return type
Iterator[Output]
classmethod update_forward_refs(**localns: Any) → None¶
Try to update ForwardRefs on fields based on this Model, globalns and localns.
Parameters
localns (Any) – 
Return type
None
classmethod validate(value: Any) → Model¶
Parameters
value (Any) – 
Return type
Model
with_alisteners(*, on_start: Optional[AsyncListener] = None, on_end: Optional[AsyncListener] = None, on_error: Optional[AsyncListener] = None) → Runnable[Input, Output]¶
Bind asynchronous lifecycle listeners to a Runnable, returning a new Runnable.
property output_schema: Type[BaseModel]¶
The type of output this runnable produces specified as a pydantic model.
Examples using AgentExecutor¶
Amadeus
ArXiv
AskNews
Azure AI Services
Azure Container Apps dynamic sessions
Bittensor
Build an Agent
Cassandra Database
Cohere
Conversational RAG
Dataherald
Exa Search
Gmail
How to add a semantic layer over graph database
How to add tools to chatbots
How to debug your LLM apps
How to migrate from legacy LangChain agents to LangGraph
How to track token usage in ChatModels
How to use tools in a chain
Hugging Face
Infobip
Ionic Shopping Tool
LLMonitor
Log, Trace, and Monitor
MLX
Memorize
MultiOn
Passio NutritionAI
Polygon IO Toolkit
Portkey
Python
Reddit Search 
Robocorp
SQL Database
Semantic Scholar API Tool
Slack
Streamlit
Tavily Search
You.com Search
ZHIPU AI
langchain.agents.format_scratchpad.log_to_messages.format_log_to_messages¶
langchain.agents.format_scratchpad.log_to_messages.format_log_to_messages(intermediate_steps: List[Tuple[AgentAction, str]], template_tool_response: str = '{observation}') → List[BaseMessage][source]¶
Construct the scratchpad that lets the agent continue its thought process.
Parameters
intermediate_steps (List[Tuple[AgentAction, str]]) – 
template_tool_response (str) – 
Return type
List[BaseMessage]
langchain.agents.self_ask_with_search.base.create_self_ask_with_search_agent¶
langchain.agents.self_ask_with_search.base.create_self_ask_with_search_agent(llm: BaseLanguageModel, tools: Sequence[BaseTool], prompt: BasePromptTemplate) → Runnable[source]¶
Create an agent that uses self-ask with search prompting.
Parameters
llm (BaseLanguageModel) – LLM to use as the agent.
tools (Sequence[BaseTool]) – List of tools. Should just be of length 1, with that tool having
name Intermediate Answer
prompt (BasePromptTemplate) – The prompt to use, must have input key agent_scratchpad which will
contain agent actions and tool outputs.
Returns
A Runnable sequence representing an agent. It takes as input all the same input
variables as the prompt passed in does. It returns as output either an
AgentAction or AgentFinish.
Return type
Runnable
Examples
from langchain import hub
from langchain_community.chat_models import ChatAnthropic
from langchain.agents import (
    AgentExecutor, create_self_ask_with_search_agent
)
prompt = hub.pull("hwchase17/self-ask-with-search")
model = ChatAnthropic(model="claude-3-haiku-20240307")
tools = [...]  # Should just be one tool with name `Intermediate Answer`
agent = create_self_ask_with_search_agent(model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
agent_executor.invoke({"input": "hi"})
Prompt:
The prompt must have input key agent_scratchpad which willcontain agent actions and tool outputs as a string.
Here’s an example:
from langchain_core.prompts import PromptTemplate
template = '''Question: Who lived longer, Muhammad Ali or Alan Turing?
Are follow up questions needed here: Yes.
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
Question: When was the founder of craigslist born?
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952
Question: Who was the maternal grandfather of George Washington?
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball
Question: Are both the directors of Jaws and Casino Royale from the same country?
Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate answer: New Zealand.
So the final answer is: No
Question: {input}
Are followup questions needed here:{agent_scratchpad}'''
prompt = PromptTemplate.from_template(template)
langchain.agents.output_parsers.xml.XMLAgentOutputParser¶
class langchain.agents.output_parsers.xml.XMLAgentOutputParser[source]¶
Bases: AgentOutputParser
Parses tool invocations and final answers in XML format.
Expects output to be in one of two formats.
If the output signals that an action should be taken,
should be in the below format. This will result in an AgentAction
being returned.
`
<tool>search</tool>
<tool_input>what is 2 + 2</tool_input>
`
If the output signals that a final answer should be given,
should be in the below format. This will result in an AgentFinish
being returned.
`
<final_answer>Foo</final_answer>
`
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]
langchain_core.agents.AgentStep¶
class langchain_core.agents.AgentStep[source]¶
Bases: Serializable
The result of running an AgentAction.
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 action: AgentAction [Required]¶
The AgentAction that was executed.
param observation: Any = None¶
The result of the AgentAction.
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
deep (bool) – set to True to make a deep copy of the model
self (Model) –
langchain.agents.openai_tools.base.create_openai_tools_agent¶
langchain.agents.openai_tools.base.create_openai_tools_agent(llm: BaseLanguageModel, tools: Sequence[BaseTool], prompt: ChatPromptTemplate) → Runnable[source]¶
Create an agent that uses OpenAI tools.
Parameters
llm (BaseLanguageModel) – LLM to use as the agent.
tools (Sequence[BaseTool]) – Tools this agent has access to.
prompt (ChatPromptTemplate) – The prompt to use. See Prompt section below for more on the expected
input variables.
Returns
A Runnable sequence representing an agent. It takes as input all the same input
variables as the prompt passed in does. It returns as output either an
AgentAction or AgentFinish.
Return type
Runnable
Example
from langchain import hub
from langchain_community.chat_models import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_tools_agent
prompt = hub.pull("hwchase17/openai-tools-agent")
model = ChatOpenAI()
tools = ...
agent = create_openai_tools_agent(model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
agent_executor.invoke({"input": "hi"})
# Using with chat history
from langchain_core.messages import AIMessage, HumanMessage
agent_executor.invoke(
    {
        "input": "what's my name?",
        "chat_history": [
            HumanMessage(content="hi! my name is bob"),
            AIMessage(content="Hello Bob! How can I assist you today?"),
        ],
    }
)
Prompt:
The agent prompt must have an agent_scratchpad key that is aMessagesPlaceholder. Intermediate agent actions and tool output
messages will be passed in here.
Here’s an example:
messages will be passed in here.
Here’s an example:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful assistant"),
        MessagesPlaceholder("chat_history", optional=True),
        ("human", "{input}"),
        MessagesPlaceholder("agent_scratchpad"),
    ]
)
Examples using create_openai_tools_agent¶
Cassandra Database
How to add tools to chatbots
Log, Trace, and Monitor
Portkey
SQL Database
Slack