0% found this document useful (0 votes)
16 views5 pages

ChatAgent Documentation Overview

The ChatAgent class is a deprecated agent model in LangChain, which allows for input data parsing and validation to create a model. It provides functionality to specify allowed tools, utilize an LLMChain, and manage output parsing, while also allowing for asynchronous decision-making based on user inputs and intermediate steps. Users are encouraged to use the create_react_agent method instead, as the ChatAgent has been deprecated since version 0.1.0.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views5 pages

ChatAgent Documentation Overview

The ChatAgent class is a deprecated agent model in LangChain, which allows for input data parsing and validation to create a model. It provides functionality to specify allowed tools, utilize an LLMChain, and manage output parsing, while also allowing for asynchronous decision-making based on user inputs and intermediate steps. Users are encouraged to use the create_react_agent method instead, as the ChatAgent has been deprecated since version 0.1.0.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ChatAgent — 🦜🔗 LangChain documentation

[Link]/v0.2/api_reference/langchain/agents/[Link]

Bases: Agent

Deprecated since version 0.1.0: Use create_react_agent instead.

Chat 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 allowed_tools: List[str] | None = None#


Allowed tools for the agent. If None, all tools are allowed.

param llm_chain: LLMChain [Required]#


LLMChain to use for agent.

param output_parser: AgentOutputParser [Optional]#


Output parser for the agent.

Async given input, decided what to do.

Parameters:
intermediate_steps (List[Tuple[AgentAction, str]]) – Steps the LLM has taken
to date, along with observations.

callbacks (List[BaseCallbackHandler] | BaseCallbackManager | None) –


Callbacks to run.

**kwargs (Any) – User inputs.

Returns:
Action specifying what tool to use.

Return type:
AgentAction | AgentFinish

classmethod create_prompt(tools: Sequence[BaseTool],


system_message_prefix: str = 'Answer the following questions as best you

1/5
can. You have access to the following tools:', system_message_suffix: str =
'Begin! Reminder to always use the exact characters `Final Answer` when
responding.', human_message: str = '{input}\n\n{agent_scratchpad}',
format_instructions: str = 'The way you use the tools is by specifying a json
blob.\nSpecifically, this json should have a `action` key (with the name of the
tool to use) and a `action_input` key (with the input to the tool going
here).\n\nThe only values that should be in the "action" field are:
{tool_names}\n\nThe $JSON_BLOB should only contain a SINGLE action, do
NOT return a list of multiple actions. Here is an example of a valid
$JSON_BLOB:\n\n```\n{{{{\n "action": $TOOL_NAME,\n "action_input":
$INPUT\n}}}}\n```\n\nALWAYS use the following format:\n\nQuestion: the input
question you must answer\nThought: you should always think about what to
do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n...
(this Thought/Action/Observation can repeat N times)\nThought: I now know
the final answer\nFinal Answer: the final answer to the original input question',
input_variables: List[str] | None = None) → BasePromptTemplate[source]#
Create a prompt from a list of tools.

Parameters:
tools (Sequence[BaseTool]) – A list of tools.

system_message_prefix (str) – The system message prefix. Default is


SYSTEM_MESSAGE_PREFIX.

system_message_suffix (str) – The system message suffix. Default is


SYSTEM_MESSAGE_SUFFIX.

human_message (str) – The human message. Default is HUMAN_MESSAGE.

format_instructions (str) – The format instructions. Default is


FORMAT_INSTRUCTIONS.

input_variables (List[str] | None) – The input variables. Default is None.

Returns:
A prompt template.

Return type:
BasePromptTemplate

Construct an agent from an LLM and tools.

2/5
Parameters:
llm (BaseLanguageModel) – The language model.

tools (Sequence[BaseTool]) – A list of tools.

callback_manager (BaseCallbackManager | None) – The callback manager.


Default is None.

output_parser (AgentOutputParser | None) – The output parser. Default is


None.

system_message_prefix (str) – The system message prefix. Default is


SYSTEM_MESSAGE_PREFIX.

system_message_suffix (str) – The system message suffix. Default is


SYSTEM_MESSAGE_SUFFIX.

human_message (str) – The human message. Default is HUMAN_MESSAGE.

format_instructions (str) – The format instructions. Default is


FORMAT_INSTRUCTIONS.

input_variables (List[str] | None) – The input variables. Default is None.

kwargs (Any) – Additional keyword arguments.

Returns:
An agent.

Return type:
Agent

get_allowed_tools() → List[str] | None#


Get allowed tools.

Return type:
List[str] | None

get_full_inputs(intermediate_steps: List[Tuple[AgentAction, str]], **kwargs:


Any) → Dict[str, Any]#
Create the full inputs for the LLMChain from intermediate steps.

Parameters:

3/5
intermediate_steps (List[Tuple[AgentAction, str]]) – Steps the LLM has taken
to date, along with observations.

**kwargs (Any) – User inputs.

Returns:
Full inputs for the LLMChain.

Return type:
Dict[str, Any]

Given input, decided what to do.

Parameters:
intermediate_steps (List[Tuple[AgentAction, str]]) – Steps the LLM has taken
to date, along with observations.

callbacks (List[BaseCallbackHandler] | BaseCallbackManager | None) –


Callbacks to run.

**kwargs (Any) – User inputs.

Returns:
Action specifying what tool to use.

Return type:
AgentAction | AgentFinish

Return response when agent has been stopped due to max iterations.

Parameters:
early_stopping_method (str) – Method to use for early stopping.

intermediate_steps (List[Tuple[AgentAction, str]]) – Steps the LLM has taken


to date, along with observations.

**kwargs (Any) – User inputs.

Returns:
Agent finish object.

Return type:
AgentFinish

4/5
Raises:
ValueError – If early_stopping_method is not in [‘force’, ‘generate’].

save(file_path: Path | str) → None#


Save the agent.

Parameters:
file_path (Path | str) – Path to file to save the agent to.

Return type:
None

Example: .. code-block:: python

# If working with agent executor [Link](file_path=”path/[Link]”)

tool_run_logging_kwargs() → Dict#
Return logging kwargs for tool run.

Return type:
Dict

property llm_prefix: str#


Prefix to append the llm call with.

property observation_prefix: str#


Prefix to append the observation with.

property return_values: List[str]#


Return values of the agent.

5/5

Common questions

Powered by AI

The intermediate_steps parameter significantly impacts the ChatAgent's iterative processing by logging each step the agent has taken, along with observations made . This parameter allows the agent to maintain a history of actions and results, facilitating more informed decision-making in subsequent steps. Tracking intermediate steps is critical for executing complex tasks requiring multiple interactions with tools or observations, ensuring that the agent can adapt and refine its strategy based on past experiences to reach more accurate final answers .

In ChatAgent interactions, system messages, human messages, and format instructions collectively create a structured framework for communication. System messages define the boundaries and initial directives for interactions, whereas human messages serve as the actual prompts or queries directed towards the agent . Format instructions guide how responses should be structured, ensuring consistency and clarity in the output. Together, these elements ensure that the interactions are coherent, focused, and productive, facilitating easier understanding and more efficient data processing for the agent .

When setting up callbacks for a ChatAgent, considerations include selecting appropriate handlers that align with the agent's tasks and ensuring they provide timely feedback or processing control . Callbacks influence operational effectiveness by allowing external processes to interject, modify, or monitor agent activities, helping to manage outputs, errors, and efficiency. The choice between BaseCallbackHandler, BaseCallbackManager, or custom callbacks can substantially affect how the agent executes its roles and integrates with larger systems .

The create_prompt method enhances the usability of a ChatAgent by standardizing how input is processed and how actions are executed. It constructs prompts by using system_message_prefix, system_message_suffix, human_message, and format_instructions . This method follows a specific JSON format, requiring an action key specifying the tool to use and an action_input key for the tool's input. It enforces a clear sequence involving the question, thought process, action, observation, and final answer. This consistency allows for reliable tool execution and result accumulation, enhancing the agent's interaction capabilities .

LLMChain plays a crucial role in the ChatAgent functionality by acting as the core mechanism for executing language model tasks. It processes inputs, interacts with the language model to generate responses, and manages output delivery . Its indispensability stems from its role as a bridge between raw input data and actionable insights or answers, ensuring the language model's capabilities are effectively leveraged in real-time agent operations .

A ChatAgent determines the tools it can use through the allowed_tools parameter, which is either a list of specific tools or set to None, allowing all tools . This influences the decision-making capabilities of the agent by constraining or broadening the tools it can select from when taking actions. The agent's effectiveness in answering queries depends on having access to the necessary tools to process information and deliver accurate results. This framework ensures that the agent can dynamically select the best-suited tool for a given task, thus optimizing its overall efficiency .

Saving an agent's state and configuration involves using the save method, specifying a file path to store the agent's current state in a durable format such as YAML . This process captures configuration, tool choices, callback setups, and more, enabling the restoration of the agent to an exact former state. This practice enhances reproducibility by ensuring that the same results can be obtained across different environments or timeframes. For collaborative efforts, sharing the saved configuration allows team members to engage with the same version of the agent, fostering consistency in research and development tasks .

To initialize a ChatAgent, several key parameters are required: allowed_tools (List[str] or None), llm_chain (LLMChain), and output_parser (optional AgentOutputParser). Allowed_tools determines which tools the agent can utilize; if None, all tools are permitted . The llm_chain is mandatory as it directly employs the language model by coordinating input processing and delivery . The output_parser is optional but essential for defining how the agent interprets and structures its responses. These parameters must align to ensure that the agent can parse inputs, utilize tools appropriately, and produce coherent outputs, thereby forming a functional ChatAgent .

When a ChatAgent reaches the maximum iteration limit, it employs an early stopping strategy determined by the parameter early_stopping_method. This can include predefined methods like 'force' or 'generate' . If the agent surpasses this limit without resolving the task, it uses AgentFinish to conclude operations, returning the current state as its final output. This process is managed by setting boundaries to prevent infinite loops, ensuring computational efficiency by ceasing operations once the iteration ceiling is approached, thus maintaining system stability .

The transition from the deprecated ChatAgent to create_react_agent is advised due to potential improvements in robustness, flexibility, and enhancement features in the newer implementation. Deprecated tools often lack support, security patches, and might not receive performance optimizations, thereby risking errors or inefficiencies . create_react_agent likely offers advancements that address limitations present in ChatAgent, such as better error handling, more refined outputs, and streamlined integration capabilities, ensuring the broader utility and alignment with contemporary development practices .

You might also like