Building with Agents
Relevant source files
The following files were used as context for generating this wiki page:
- README.md
- libs/langchain/README.md
- libs/core/langchain_core/runnables/base.py
- libs/langchain/langchain/chains/api/base.py
- libs/langchain/langchain/agents/conversational/prompt.py
- libs/langchain/langchain/agents/conversational_chat/prompt.py
- SECURITY.md
- libs/langchain/langchain/evaluation/agents/trajectory_eval_prompt.py
- cookbook/README.md
- libs/core/README.md
Agents in LangChain are systems that use a Large Language Model (LLM) to reason about which actions to take to accomplish a goal. Unlike simple chains that follow a predetermined sequence of steps, agents employ a reasoning loop where the LLM acts as a decision-maker. It observes the environment, thinks about the next step, and uses available tools to execute actions until the task is complete. This allows for building dynamic and powerful applications that can interact with their environment to solve complex problems.
The core idea is to combine the reasoning capabilities of LLMs with external sources of computation or knowledge, such as APIs, databases, or other computational tools. LangChain provides a standard interface for agents, a selection of agent types to choose from, and examples of end-to-end agent implementations. These agents are fundamental to building advanced applications like complex chatbots, Retrieval Augmented Generation (RAG) systems, and structured data extraction tools.
Sources: libs/langchain/README.md, README.md
Core Concepts
Agents are built upon several core components within the LangChain framework, primarily the Runnable interface, which provides a standard way to compose and invoke components.
*Sources: libs/core/README.md, libs/core/langchain_core/runnables/base.py
The Agent Loop
The fundamental process of an agent is an iterative loop of thought, action, and observation.
- Thought: The LLM receives the user's input and its internal state (scratchpad) and decides if a tool is needed.
- Action: If a tool is needed, the LLM outputs the name of the tool and the input for it.
- Observation: The selected tool is executed with the provided input, and the result (observation) is returned.
- Repeat: The observation is added to the agent's scratchpad, and the loop repeats until the LLM decides it has enough information to generate a final answer.
This diagram illustrates the basic decision-making flow of an agent.
This diagram shows the iterative loop an agent follows, from receiving user input to using tools and finally generating a response.
Sources: libs/langchain/README.md, libs/langchain/langchain/agents/conversational/prompt.py:23-33
The Runnable Interface
Agents, like most components in LangChain, are built on the Runnable interface. This provides a standard, composable way to build and interact with them. Key methods provided by the Runnable interface include:
invoke()/ainvoke(): For single inputs.batch()/abatch(): For multiple inputs.stream()/astream(): For streaming outputs.astream_events(): For streaming detailed execution events.
This interface allows agents to be seamlessly integrated into RunnableSequence and RunnableParallel constructs, enabling complex workflows with automatic support for async, batching, and streaming.
*Sources: libs/core/langchain_core/runnables/base.py:1-100, libs/core/README.md
The following class diagram shows the relationship between the core Runnable classes.
This diagram illustrates that RunnableSequence and RunnableParallel are key composition classes inheriting from RunnableSerializable, which itself is a Runnable.
Sources: libs/core/langchain_core/runnables/base.py
Prompt Engineering for Agents
The behavior of an agent is heavily guided by its prompt. The prompt instructs the LLM on its persona, the tools it has access to, and how it should format its thoughts and actions.
Prompt Structure
A typical agent prompt is composed of several key sections:
| Section | Description | Source File |
|---|---|---|
PREFIX | Sets the context and persona for the LLM (e.g., "Assistant is a large language model..."). It may also list the available tools. | libs/langchain/langchain/agents/conversational/prompt.py:1-10 |
FORMAT_INSTRUCTIONS | Critically defines the exact output format the LLM must use, such as a JSON blob with "action" and "action_input" keys. | libs/langchain/langchain/agents/conversational_chat/prompt.py:13-31 |
SUFFIX | Contains the dynamic parts of the prompt, including the user's input, chat history, and the agent's scratchpad of previous steps. | libs/langchain/langchain/agents/conversational/prompt.py:35-41 |
TEMPLATE_TOOL_RESPONSE | A template for formatting the output of a tool execution to be fed back into the agent's context for the next reasoning step. | libs/langchain/langchain/agents/conversational_chat/prompt.py:37-45 |
Sources: libs/langchain/langchain/agents/conversational/prompt.py, libs/langchain/langchain/agents/conversational_chat/prompt.py
Example: Conversational Chat FORMAT_INSTRUCTIONS
This example shows how the agent is instructed to format its response, either by using a tool or by providing a final answer to the user.
# From libs/langchain/langchain/agents/conversational_chat/prompt.py:13-31
FORMAT_INSTRUCTIONS = """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:
Use this if you want to respond directly to the human. Markdown code snippet formatted in the following schema:
{{{{
"action": "Final Answer",
"action_input": string \\\\ You should put what you want to return to use here
}}}}
```"""
Sources: libs/langchain/langchain/agents/conversational_chat/prompt.py:13-31
Interacting with APIs
A common use case for agents is to interact with external APIs. The APIChain provides a specialized mechanism for this.
The APIChain is designed to:
- Receive a user question.
- Use an LLM (
api_request_chain) to construct the correct API URL based on the question and provided API documentation (api_docs). - Make the API request using a
requests_wrapper. - Use another LLM (
api_answer_chain) to synthesize a final answer from the API response.
Sources: libs/langchain/langchain/chains/api/base.py:73-81
This sequence diagram shows the data flow within an APIChain.
This diagram shows the internal sequence of an APIChain, from generating a request URL to summarizing the response.
Sources: libs/langchain/langchain/chains/api/base.py:284-312
Security Considerations
Giving agents access to external tools and resources introduces security risks. It is crucial to follow security best practices when building applications with agents.
Best Practices
- Limit Permissions: Grant the agent the minimum required permissions. Use read-only credentials and restrict access to sensitive resources. For example,
APIChainhas alimit_to_domainsparameter to restrict which URLs can be called. - Anticipate Potential Misuse: Assume that any credentials or system access granted to an LLM might be used in any way the permissions allow.
- Defense in Depth: Combine multiple security approaches, such as using both read-only permissions and sandboxing (e.g., running in a container).
Sources: SECURITY.md, libs/langchain/langchain/chains/api/base.py:89-102
Example Risks and Mitigations
| Scenario | Mitigation Strategy |
|---|---|
| An agent with file system access is asked to delete critical files. | Limit the agent to a specific directory and use sandboxing (e.g., a Docker container). |
| An agent with API access is asked to write malicious data or delete records. | Provide read-only API keys or limit the agent to endpoints resistant to misuse. |
| An agent with database access is asked to drop a table. | Scope credentials to only the necessary tables and consider issuing READ-ONLY credentials. |
Sources: SECURITY.md
Agent Evaluation
Evaluating generative models and agents is notoriously difficult with traditional metrics. LangChain provides utilities for evaluating agent performance using LLMs themselves.
The trajectory_eval_prompt is designed to have one LLM evaluate the performance of an agent based on its "trajectory" (the sequence of tool uses).
The evaluation considers the following criteria:
- Is the final answer helpful?
- Does the agent use a logical sequence of tools?
- Are the tools used in a helpful way?
- Does the agent use too many steps?
- Are the appropriate tools used?
The evaluator LLM provides a step-by-step analysis and a final score (e.g., from 1 to 5).
Sources: libs/langchain/langchain/evaluation/agents/trajectory_eval_prompt.py:10-26
Conclusion
LangChain Agents are a powerful abstraction for building applications that can reason and interact with the world. They leverage the Runnable interface for composability and are guided by carefully engineered prompts. While they unlock advanced capabilities, developers must prioritize security by limiting permissions and anticipating misuse. The framework also provides tools for evaluating agent performance, which is a critical step in building reliable and effective agent-based systems.