Tony20100/langchain_full huggingface dataset:
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
dict(**kwargs: Any) → Dict[source]¶
Return dictionary representation of agent.
Parameters
kwargs (Any) – 
Return type
Dict
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
get_allowed_tools() → Optional[List[str]][source]¶
Return type
Optional[List[str]]
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]]) –
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 parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
path (Union[str, Path]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
classmethod parse_obj(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
b (Union[str, bytes]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
abstract plan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[List[AgentAction], AgentFinish][source]¶
Given input, decided what to do.
Parameters
Given input, decided what to do.
Parameters
intermediate_steps (List[Tuple[AgentAction, str]]) – Steps the LLM has taken to date,
along with the observations.
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – Callbacks to run.
**kwargs (Any) – User inputs.
Returns
Actions specifying what tool to use.
Return type
Union[List[AgentAction], AgentFinish]
return_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) → AgentFinish[source]¶
Return response when agent has been stopped due to max iterations.
Parameters
early_stopping_method (str) – 
intermediate_steps (List[Tuple[AgentAction, str]]) – 
kwargs (Any) – 
Return type
AgentFinish
save(file_path: Union[Path, str]) → None[source]¶
Save the agent.
Parameters
file_path (Union[Path, str]) – Path to file to save the agent to.
Return type
None
Example:
.. code-block:: python
# If working with agent executor
agent.agent.save(file_path=”path/agent.yaml”)
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
tool_run_logging_kwargs() → Dict[source]¶
Return type
Dict
unicode
tool_run_logging_kwargs() → Dict[source]¶
Return type
Dict
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
property return_values: List[str]¶
Return values of the agent.
langchain.agents.agent.RunnableMultiActionAgent¶
class langchain.agents.agent.RunnableMultiActionAgent[source]¶
Bases: BaseMultiActionAgent
Agent powered by runnables.
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 input_keys_arg: List[str] = []¶
param return_keys_arg: List[str] = []¶
param runnable: Runnable[dict, Union[List[AgentAction], AgentFinish]] [Required]¶
Runnable to call to get agent actions.
param stream_runnable: bool = True¶
Whether to stream from the runnable or not.
If True then underlying LLM is invoked in a streaming fashion to make it possibleto get access to the individual LLM tokens when using stream_log with the Agent
Executor. If False then LLM is invoked in a non-streaming fashion and
individual LLM tokens will not be available in stream_log.
async aplan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[List[AgentAction], AgentFinish][source]¶
Based on past history and current inputs, decide what to do.
Parameters
intermediate_steps (List[Tuple[AgentAction, str]]) – Steps the LLM has taken to date,
along with observations
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – Callbacks to run.
**kwargs (Any) – User inputs.
Returns
Action specifying what tool to use.
Return type
Union[List[AgentAction], AgentFinish]
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) – 
Returns
new model instance
Return type
Model
dict(**kwargs: Any) → Dict¶
Return dictionary representation of agent.
Parameters
kwargs (Any) – 
Return type
Dict
classmethod from_orm(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Model
get_allowed_tools() → Optional[List[str]]¶
Return type
Optional[List[str]]
get_allowed_tools() → Optional[List[str]]¶
Return type
Optional[List[str]]
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 parse_file(path: Union[str, Path], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
path (Union[str, Path]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
classmethod parse_obj(obj: Any) → Model¶
Parameters
obj (Any) – 
Return type
Parameters
obj (Any) – 
Return type
Model
classmethod parse_raw(b: Union[str, bytes], *, content_type: unicode = None, encoding: unicode = 'utf8', proto: Protocol = None, allow_pickle: bool = False) → Model¶
Parameters
b (Union[str, bytes]) – 
content_type (unicode) – 
encoding (unicode) – 
proto (Protocol) – 
allow_pickle (bool) – 
Return type
Model
plan(intermediate_steps: List[Tuple[AgentAction, str]], callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, **kwargs: Any) → Union[List[AgentAction], AgentFinish][source]¶
Based on past history and current inputs, decide what to do.
Parameters
intermediate_steps (List[Tuple[AgentAction, str]]) – Steps the LLM has taken to date,
along with the observations.
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – Callbacks to run.
**kwargs (Any) – User inputs.
Returns
Action specifying what tool to use.
Return type
Union[List[AgentAction], AgentFinish]
return_stopped_response(early_stopping_method: str, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any) → AgentFinish¶
Return response when agent has been stopped due to max iterations.
Parameters
early_stopping_method (str) – 
intermediate_steps (List[Tuple[AgentAction, str]]) – 
kwargs (Any) – 
Return type
AgentFinish
save(file_path: Union[Path, str]) → None¶
Save the agent.
Parameters
file_path (Union[Path, str]) – Path to file to save the agent to.
Return type
None
Example:
.. code-block:: python
Return type
None
Example:
.. code-block:: python
# If working with agent executor
agent.agent.save(file_path=”path/agent.yaml”)
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
tool_run_logging_kwargs() → Dict¶
Return type
Dict
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
property input_keys: List[str]¶
Return the input keys.
Returns
List of input keys.
property return_values: List[str]¶
Return values of the agent.
langchain.agents.conversational.output_parser.ConvoOutputParser¶
class langchain.agents.conversational.output_parser.ConvoOutputParser[source]¶
Bases: AgentOutputParser
Output parser for the conversational agent.
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 ai_prefix: str = 'AI'¶
Prefix to use before AI output.
param format_instructions: str = 'To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```'¶
Default formatting instructions
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.agents.agent_types.AgentType¶
class langchain.agents.agent_types.AgentType(value)[source]¶
[Deprecated] An enum for agent types.
See documentation: https://python.langchain.com/docs/modules/agents/agent_types/
Notes
Deprecated since version 0.1.0: Use Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. instead.
ZERO_SHOT_REACT_DESCRIPTION = 'zero-shot-react-description'¶
A zero shot agent that does a reasoning step before acting.
REACT_DOCSTORE = 'react-docstore'¶
A zero shot agent that does a reasoning step before acting.
This agent has access to a document store that allows it to look up
relevant information to answering the question.
SELF_ASK_WITH_SEARCH = 'self-ask-with-search'¶
An agent that breaks down a complex question into a series of simpler questions.
This agent uses a search tool to look up answers to the simpler questions
in order to answer the original complex question.
CONVERSATIONAL_REACT_DESCRIPTION = 'conversational-react-description'¶
CHAT_ZERO_SHOT_REACT_DESCRIPTION = 'chat-zero-shot-react-description'¶
A zero shot agent that does a reasoning step before acting.
This agent is designed to be used in conjunction
CHAT_CONVERSATIONAL_REACT_DESCRIPTION = 'chat-conversational-react-description'¶
STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION = 'structured-chat-zero-shot-react-description'¶
An zero-shot react agent optimized for chat models.
This agent is capable of invoking tools that have multiple inputs.
OPENAI_FUNCTIONS = 'openai-functions'¶
An agent optimized for using open AI functions.
OPENAI_MULTI_FUNCTIONS = 'openai-multi-functions'¶
Examples using AgentType¶
AINetwork
AWS Lambda
Aim
Airbyte Question Answering
Amazon API Gateway
AINetwork
AWS Lambda
Aim
Airbyte Question Answering
Amazon API Gateway
Argilla
Azure Cognitive Services
Bearly Code Interpreter
CSV
ChatGPT Plugins
ClearML
ClickUp
Comet Tracing
Connery Action Tool
Connery Toolkit
Document Comparison
E2B Data Analysis
Eden AI
Eleven Labs Text2Speech
Flyte
Github
Gitlab
Google Drive
Google Finance
Google Jobs
Google Serper
GraphQL
Human as a tool
Jira
LLMonitor
MLflow
Memorize
NASA
Natural Language APIs
Office365
OpenWeatherMap
Pandas Dataframe
PlayWright Browser
Search Tools
SearchApi
Serper - Google Search API
Shell (bash)
Steam Game Recommendation & Game Details
WandB Tracing
Weights & Biases
Xata
Yahoo Finance News
Zapier Natural Language Actions
Zep Cloud Memory
Zep Open Source Memory
langchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages¶
langchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages(intermediate_steps: Sequence[Tuple[AgentAction, str]]) → List[BaseMessage][source]¶
Convert (AgentAction, tool output) tuples into FunctionMessages.
Parameters
intermediate_steps (Sequence[Tuple[AgentAction, str]]) – Steps the LLM has taken to date, along with observations
Returns
list of messages to send to the LLM for the next prediction
Return type
List[BaseMessage]
Examples using format_to_openai_function_messages¶
How to add a semantic layer over graph database
langchain.agents.json_chat.base.create_json_chat_agent¶
langchain.agents.json_chat.base.create_json_chat_agent(llm: ~langchain_core.language_models.base.BaseLanguageModel, tools: ~typing.Sequence[~langchain_core.tools.BaseTool], prompt: ~langchain_core.prompts.chat.ChatPromptTemplate, stop_sequence: ~typing.Union[bool, ~typing.List[str]] = True, tools_renderer: ~typing.Callable[[~typing.List[~langchain_core.tools.BaseTool]], str] = <function render_text_description>, template_tool_response: str = "TOOL RESPONSE: \n---------------------\n{observation}\n\nUSER'S INPUT\n--------------------\n\nOkay, so what is the response to my last comment? If using information obtained from the tools you must mention it explicitly without mentioning the tool names - I have forgotten all TOOL RESPONSES! Remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else - even if you just want to respond to the user. Do NOT respond with anything except a JSON snippet no matter what!") → Runnable[source]¶
Create an agent that uses JSON to format its logic, build for Chat Models.
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.
stop_sequence (Union[bool, List[str]]) – bool or list of str.
If True, adds a stop token of “Observation:” to avoid hallucinates.
If False, does not add a stop token.
If a list of str, uses the provided list as the stop tokens.
Default is True. You may to set this to False if the LLM you are using
does not support stop sequences.
does not support stop sequences.
tools_renderer (Callable[[List[BaseTool]], str]) – This controls how the tools are converted into a string and
then passed into the LLM. Default is render_text_description.
template_tool_response (str) – Template prompt that uses the tool response (observation)
to make the LLM generate the next action to take.
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_json_chat_agent
prompt = hub.pull("hwchase17/react-chat-json")
model = ChatOpenAI()
tools = ...
agent = create_json_chat_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 prompt must have input keys:
tools: contains descriptions and arguments for each tool.
tool_names: contains all tool names.
agent_scratchpad: must be a MessagesPlaceholder. Contains previous agent actions and tool outputs as messages.
Here’s an example:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
system = '''Assistant is a large language model trained by OpenAI.
system = '''Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering             simple questions to providing in-depth explanations and discussions on a wide range of             topics. As a language model, Assistant is able to generate human-like text based on             the input it receives, allowing it to engage in natural-sounding conversations and             provide responses that are coherent and relevant to the topic at hand.
Assistant is constantly learning and improving, and its capabilities are constantly             evolving. It is able to process and understand large amounts of text, and can use this             knowledge to provide accurate and informative responses to a wide range of questions.             Additionally, Assistant is able to generate its own text based on the input it             receives, allowing it to engage in discussions and provide explanations and             descriptions on a wide range of topics.
Overall, Assistant is a powerful system that can help with a wide range of tasks             and provide valuable insights and information on a wide range of topics. Whether             you need help with a specific question or just want to have a conversation about             a particular topic, Assistant is here to assist.'''
human = '''TOOLS
------
Assistant can ask the user to use tools to look up information that may be helpful in             answering the users original question. The tools the human can use are:
{tools}
RESPONSE FORMAT INSTRUCTIONS
----------------------------
When responding to me, please output a response in one of two formats:
**Option 1:**
Use this if you want the human to use a tool.
Markdown code snippet formatted in the following schema:
```json
{{
    "action": string, \ The action to take. Must be one of {tool_names}
    "action_input": string \ The input to the action
}}
```
**Option #2:**
}}
```
**Option #2:**
Use this if you want to respond directly to the human. Markdown code snippet formatted             in the following schema:
```json
{{
    "action": "Final Answer",
    "action_input": string \ You should put what you want to return to use here
}}
```
USER'S INPUT
--------------------
Here is the user's input (remember to respond with a markdown code snippet of a json             blob with a single action, and NOTHING else):
{input}'''
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", system),
        MessagesPlaceholder("chat_history", optional=True),
        ("human", human),
        MessagesPlaceholder("agent_scratchpad"),
    ]
)
Examples using create_json_chat_agent¶
ZHIPU AI
langchain_experimental.agents.agent_toolkits.xorbits.base.create_xorbits_agent¶
langchain_experimental.agents.agent_toolkits.xorbits.base.create_xorbits_agent(llm: BaseLLM, data: Any, callback_manager: Optional[BaseCallbackManager] = None, prefix: str = '', suffix: str = '', input_variables: Optional[List[str]] = None, verbose: bool = False, return_intermediate_steps: bool = False, max_iterations: Optional[int] = 15, max_execution_time: Optional[float] = None, early_stopping_method: str = 'force', agent_executor_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Dict[str, Any]) → AgentExecutor[source]¶
Construct a xorbits agent from an LLM and dataframe.
Parameters
llm (BaseLLM) – 
data (Any) – 
callback_manager (Optional[BaseCallbackManager]) – 
prefix (str) – 
suffix (str) – 
input_variables (Optional[List[str]]) – 
verbose (bool) – 
return_intermediate_steps (bool) – 
max_iterations (Optional[int]) – 
max_execution_time (Optional[float]) – 
early_stopping_method (str) – 
agent_executor_kwargs (Optional[Dict[str, Any]]) – 
kwargs (Dict[str, Any]) – 
Return type
AgentExecutor
Examples using create_xorbits_agent¶
Xorbits
langchain.agents.loading.load_agent¶
langchain.agents.loading.load_agent(path: Union[str, Path], **kwargs: Any) → Union[BaseSingleActionAgent, BaseMultiActionAgent][source]¶
[Deprecated] Unified method for loading an agent from LangChainHub or local fs.
Parameters
path (Union[str, Path]) – Path to the agent file.
**kwargs (Any) – Additional keyword arguments passed to the agent executor.
Returns
An agent executor.
Return type
Union[BaseSingleActionAgent, BaseMultiActionAgent]
Notes
Deprecated since version 0.1.0.