What is an AI agent?
Overview
Imagine asking an AI application the following question:
“Find the current price of a laptop, calculate the cost of purchasing five units, and determine whether the purchase fits within a $5,000 budget.”
A conventional language model might generate an answer using information it learned during training. It could estimate a laptop’s price, perform approximate arithmetic, and produce a convincing explanation.
However, the estimated price might be outdated, the calculation might be incorrect, and the resulting recommendation might be unreliable.
An AI agent approaches the problem differently. It can retrieve the price from an external source, execute a calculator, compare the result against the budget, and generate an answer grounded in the information it obtained.
More importantly, it can determine which actions are necessary rather than requiring the developer to explicitly program every possible sequence.
In the previous lesson, you learned how to expose Python functions to language models using LangChain tools. This lesson brings those tools together into an intelligent execution system.
What exactly is an AI agent?
An AI agent is a software system that uses an AI model to select and perform actions in pursuit of a goal, using feedback from those actions to determine what to do next.
An agent typically contains five components:
| Component | Responsibility |
|---|---|
| Model | Interprets requests and selects appropriate actions |
| Instructions | Defines objectives, behavior, and operating boundaries |
| Tools | Provides access to external capabilities |
| State | Maintains information gathered during execution |
| Execution runtime | Executes actions, manages control flow, and enforces stopping conditions |
The model is the decision-making component, but the complete application is the agent.
An LLM alone does not automatically become an agent simply because it can reason about complex problems. The surrounding software must enable it to interact with an environment and use the resulting feedback.
For example, a database assistant needs more than knowledge of SQL. It needs a database interface, permission checks, query execution, result handling, and a mechanism for deciding whether additional queries are necessary.
The combination of the model and its surrounding execution infrastructure is sometimes called a model plus harness.
Preparing your environment
The model-powered examples in this lesson use LangChain 1.x, LangGraph 1.x, and OpenAI’s GPT-5.4 mini.
Install the required packages in your Python environment:
python -m pip install -U "langchain[openai]>=1,<2" "langgraph>=1,<2"Configure your OpenAI API key on macOS or Linux:
export OPENAI_API_KEY="your-api-key"For Windows PowerShell:
$env:OPENAI_API_KEY="your-api-key"Replace the placeholder with your own API key. Avoid hardcoding credentials in application source code.
Each Python example is a standalone script. The search examples intentionally use local datasets rather than live internet services, making the retrieved information reproducible without requiring a separate search API subscription. The APIs are documented current interfaces; the model-powered example outputs are illustrative rather than results from live execution.
Generative AI vs agentic AI
Traditional generative AI
Generative AI produces new content from an input. This content might include text, source code, images, structured data, or explanations.
A conventional LLM-powered application typically receives an input, constructs a prompt, invokes a model, and returns the generated response.
Consider a customer support application that rewrites technical documentation into beginner-friendly language. The application already knows what operation must occur. It does not need the model to decide how to interact with external systems.
The following example demonstrates a standalone generative AI application.
from langchain.chat_models import init_chat_model
from langchain.messages import SystemMessage, HumanMessage
model = init_chat_model("openai:gpt-5.4-mini")
messages = [
SystemMessage(
content="Explain technical concepts in simple language."
),
HumanMessage(
content="Explain what a REST API is in two sentences."
),
]
response = model.invoke(messages)
print(response.text)Possible output:
A REST API allows applications to communicate over HTTP using
standard operations such as GET and POST. It enables one
application to request or exchange data with another application.This program performs a single application-level model invocation. It does not execute external tools, retrieve additional information, or dynamically choose another application operation.
The model may internally perform sophisticated reasoning, but the surrounding application’s execution path remains straightforward.
Agentic AI
Agentic AI extends generative AI by giving the model influence over application actions.
Instead of only generating text, the model can request operations such as searching a knowledge base, retrieving customer records, calculating numerical results, or interacting with external APIs.
The execution runtime performs those operations and returns their results to the model.
Consider an inventory assistant receiving this request:
“Can we fulfill an order for 150 keyboards from our Chennai warehouse?”
A suitable agent might:
- Retrieve the warehouse’s inventory.
- Discover that only 100 keyboards are available.
- Check whether other warehouses have additional stock.
- Determine whether a transfer is possible.
- Report the available options and any limitations.
The precise execution path depends on the information returned during the interaction.
The developer provides the available capabilities, while the model participates in deciding how to use them.
This adaptability is the distinguishing feature of agentic systems.
Comparing generative and agentic AI
| Characteristics | Generative AI | Agentic AI |
|---|---|---|
| Primary purpose | Generate content | Accomplish a goal |
| Application control flow | Usually predetermined | Can adapt during execution |
| External tools | Optional | Commonly used |
| Feedback loop | Not inherently required | Central to adaptive execution |
| Model invocations | Often one or a fixed sequence | Potentially several |
| Environment interaction | Usually limited | Can read or modify external systems |
| Operational risk | Generally lower | Depends on available actions |
| Example | Summarize an email | Investigate and resolve a support request |
These categories are not mutually exclusive. An agent uses generative AI as one of its underlying capabilities.
Similarly, an application that retrieves documents before generating an answer is not necessarily an autonomous agent. If retrieval always happens through a predefined pipeline, it may be better described as a retrieval-augmented workflow.
Note: Tool calling, memory, and advanced reasoning do not independently guarantee agency. What matters is how much decision-making authority the model has over the application’s execution.
Workflows vs autonomous agents
When engineering AI applications, one of your most important architectural decisions is determining which decisions belong to deterministic application code and which should be delegated to an AI model.
What is a workflow?
A workflow is an application whose execution structure is defined by the developer.
For example, consider an automated purchase quotation system.
The application always retrieves a product’s price, calculates the purchase cost, checks the budget, and generates a quotation.
The following diagram illustrates this predefined execution path.
A workflow can contain branches, loops, parallel operations, and even multiple LLM calls. It does not need to be a simple linear sequence.
Its defining characteristic is that the developer specifies the execution structure and routing rules.
Example: A deterministic quotation workflow
The following program implements a quotation workflow without using an LLM.
PRODUCTS = {
"laptop": 850,
"monitor": 250,
"keyboard": 75,
}
def get_price(product: str) -> float:
return PRODUCTS[product.lower()]
def calculate_cost(price: float, quantity: int) -> float:
return price * quantity
def quotation_workflow(
product: str,
quantity: int,
budget: float,
) -> dict:
if quantity < 1 or budget < 0:
raise ValueError("Invalid quantity or budget.")
price = get_price(product)
total = calculate_cost(price, quantity)
return {
"product": product,
"quantity": quantity,
"total": total,
"within_budget": total <= budget,
}
result = quotation_workflow(
product="laptop",
quantity=5,
budget=5000,
)
print(result)Expected output:
{
'product': 'laptop',
'quantity': 5,
'total': 4250,
'within_budget': True
}The workflow is predictable because every operation is explicitly programmed.
If the same input and catalog are supplied again, the result remains unchanged.
Introducing an LLM to decide whether five laptops costing $850 each fit within a $5,000 budget would add unnecessary complexity. Ordinary Python already provides a reliable solution.
What is an autonomous agent?
An autonomous agent has delegated authority to determine parts of its own execution path.
For example, a procurement assistant might receive requests such as:
- Find the cheapest available monitor.
- Compare three laptop models.
- Calculate the cost of purchasing ten keyboards.
- Recommend equipment within a specified budget.
- Explain why a requested product is unavailable.
These requests require different combinations of actions.
Instead of implementing a separate workflow for every possible question, the developer can provide a collection of tools and allow the model to choose relevant operations.
The model can also adjust its approach based on intermediate results. If one product is unavailable, it might search for alternatives rather than immediately terminating.
Autonomy, however, does not mean unrestricted control. The developer still determines which tools exist, which actions are permitted, and when execution must stop.
Workflows and agents are a spectrum
Many production systems combine deterministic orchestration with agent-driven decisions.
| Architecture | Decision-making authority | Suitable use case |
|---|---|---|
| Fixed workflow | Application code | Invoice calculation |
| LLM-assisted workflow | Model handles specific language tasks | Document classification |
| LLM-routed workflow | Model selects among predefined routes | Support ticket routing |
| Tool-using agent | Model selects tools and execution sequence | Research assistant |
| Hybrid system | Application and model share control | Enterprise procurement assistant |
For example, an agent might investigate a purchase request and identify suitable products. A deterministic workflow then validates the budget and obtains authorization before submitting the order.
This design preserves flexibility without delegating financial authorization to a probabilistic model.
LangGraph supports both predefined workflows and adaptive agents. You can use the same orchestration framework to combine deterministic operations with model-driven decisions.
The official LangGraph workflows and agents documentation describes additional patterns, including routing, parallelization, and orchestrator-worker architectures.
The ReAct pattern
Reasoning and acting together
ReAct stands for Reasoning and Acting.
The approach was introduced in the 2022 research paper ReAct: Synergizing Reasoning and Acting in Language Models by Shunyu Yao and colleagues.
The central idea is that a language model can solve problems more effectively by combining decision-making with interaction with external environments.
Instead of generating an entire answer immediately, the model can perform an action, receive information, and reconsider its next step.
A ReAct-style execution cycle contains three conceptual operations:
- Reasoning: Determine what information or action is needed.
- Action: Request execution of an available tool.
- Observation: Receive the result of that tool.
The cycle continues until the model produces a final response or the execution runtime stops it.
The following diagram illustrates a modern tool-calling implementation of the ReAct loop.
Modern tool-calling models represent actions using structured requests rather than requiring developers to parse textual statements such as Action: calculator.
The reasoning stage is conceptual. Your application does not need access to the model’s private chain of thought. Tool requests, arguments, observations, and final responses provide useful execution evidence.
Walking through an agent’s execution
Suppose the user asks:
“What would six laptops from our catalog cost?”
The agent has access to a search tool and a calculator.
A possible execution trace is:
| Step | Operation | Result |
|---|---|---|
| 1 | Model requests product price | Search tool call |
| 2 | Search tool executes | Laptop price is $850 |
| 3 | Model requests multiplication | Calculator tool call |
| 4 | Calculator executes | 850 × 6 = 5,100 |
| 5 | Model produces final answer | Six laptops cost $5,100 |
Notice that the calculator’s arguments depend on the search result.
The agent cannot reliably calculate the total until it retrieves the product price.
This relationship is important. Agents can perform actions whose inputs are discovered during execution, rather than being completely known beforehand.
How tool-calling messages work
When a tool-enabled model requests an action, LangChain represents the request inside an AIMessage.
The tool_calls property contains structured information resembling the following Python dictionary:
{
"name": "multiply",
"args": {"a": 850, "b": 6},
"id": "call_example_001",
"type": "tool_call",
}The model has not executed the Python function. It has only requested that the application execute it.
The runtime calls the corresponding function and returns a ToolMessage containing the result and matching tool-call identifier.
That identifier is particularly important when a model requests several tools in a single response. Each result must be associated with its original request.
The model then receives the updated conversation, including the tool results, and decides whether another action is required.
Implementing a ReAct loop manually
Before using an agent framework, it is useful to understand the execution mechanism that the framework automates.
The following example implements a small ReAct-style loop using ordinary Python, LangChain messages, and tool binding.
from langchain.chat_models import init_chat_model
from langchain.messages import (
HumanMessage,
SystemMessage,
ToolMessage,
)
from langchain.tools import tool
@tool
def search_catalog(product: str) -> str:
"""Search the local catalog for a product's price in USD."""
catalog = {
"laptop": 850,
"monitor": 250,
}
name = product.strip().lower()
if name not in catalog:
return "Product not found."
return f"{name} costs {catalog[name]} USD."
@tool
def multiply(a: float, b: float) -> float:
"""Multiply two numbers."""
return a * b
tools = [search_catalog, multiply]
tool_registry = {item.name: item for item in tools}
model = init_chat_model("openai:gpt-5.4-mini")
model_with_tools = model.bind_tools(tools)
messages = [
SystemMessage(
content=(
"You are a procurement assistant. "
"Use search_catalog to obtain product prices. "
"Use multiply for purchase cost calculations. "
"Never invent missing prices."
)
),
HumanMessage(
content="What is the total cost of six laptops?"
),
]
MAX_MODEL_CALLS = 6
for _ in range(MAX_MODEL_CALLS):
response = model_with_tools.invoke(messages)
messages.append(response)
if response.invalid_tool_calls:
raise RuntimeError("The model returned invalid tool calls.")
if not response.tool_calls:
print("Final answer:", response.text)
break
for call in response.tool_calls:
print("Tool requested:", call["name"])
print("Arguments:", call["args"])
if call["name"] not in tool_registry:
raise RuntimeError("Unknown tool requested.")
selected_tool = tool_registry[call["name"]]
result = selected_tool.invoke(call["args"])
messages.append(
ToolMessage(
content=str(result),
name=call["name"],
tool_call_id=call["id"],
)
)
print("Observation:", result)
else:
print("Stopped: maximum model calls reached.")A possible output is:
Tool requested: search_catalog
Arguments: {'product': 'laptop'}
Observation: laptop costs 850 USD.
Tool requested: multiply
Arguments: {'a': 850, 'b': 6}
Observation: 5100.0
Final answer: The total cost of six laptops is $5,100.The exact message wording, argument order, and execution sequence may vary.
Understanding the implementation
First, bind_tools() exposes the tool names, descriptions, and argument schemas to the model.
Second, the model receives the conversation and returns an AIMessage. If that message contains tool calls, Python executes the requested functions.
Third, the application appends the tool results to the existing message history. The next model invocation therefore has access to the newly discovered information.
Finally, execution terminates when the model returns a response without tool calls or when the maximum number of model invocations is reached.
The model determines the requested actions, while Python remains responsible for executing them.
This example intentionally executes tools sequentially and stops on malformed requests. It does not implement production-level retries, persistent state, parallel tool execution, or error recovery.
Those additional responsibilities explain why agent execution frameworks are valuable.
For further details about message handling, refer to the LangChain model documentation.
Building an agent with LangChain
LangChain 1.x provides the create_agent interface, which builds an agent using a LangGraph-based execution runtime.
Instead of manually implementing the complete tool-calling loop, you supply a model, tools, and instructions.
The framework handles the normal interaction between model invocations, tool execution, and message state.
Example: A calculator and knowledge search assistant
The following complete example introduces the architecture used in this chapter’s hands-on project.
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.messages import AIMessage, ToolMessage
from langchain.tools import tool
from langgraph.errors import GraphRecursionError
KNOWLEDGE_BASE = {
"basic plan": "The Basic plan costs 20 USD per month.",
"pro plan": "The Pro plan costs 50 USD per month.",
"enterprise plan": "Contact sales for Enterprise pricing.",
}
@tool
def search(query: str) -> str:
"""Search the local knowledge base for subscription pricing."""
query = query.lower()
matches = [
description
for name, description in KNOWLEDGE_BASE.items()
if name in query
]
if not matches:
return "No matching information was found."
return "\n".join(matches)
@tool
def calculator(a: float, b: float) -> float:
"""Multiply two numbers to calculate a total cost."""
return a * b
model = init_chat_model("openai:gpt-5.4-mini")
agent = create_agent(
model=model,
tools=[search, calculator],
system_prompt=(
"You are a subscription assistant. "
"Use search for subscription prices. "
"Use calculator for numerical multiplication. "
"Do not invent unavailable pricing information. "
"Answer general questions directly when appropriate."
),
)
questions = [
"Hello! What can you do?",
"What does the Basic plan cost?",
"How much does the Pro plan cost for 12 months?",
"What is the annual cost of the Enterprise plan?",
]
for question in questions:
print(f"\nQuestion: {question}")
try:
result = agent.invoke(
{
"messages": [
{"role": "user", "content": question}
]
},
config={"recursion_limit": 15},
)
for message in result["messages"]:
if isinstance(message, AIMessage):
for call in message.tool_calls:
print(
f"Requested: {call['name']}",
call["args"],
)
elif isinstance(message, ToolMessage):
print(
f"Executed: {message.name}",
message.content,
)
print("Answer:", result["messages"][-1].text)
except GraphRecursionError:
print("The agent reached its execution limit.")Representative output:
Question: Hello! What can you do?
Answer: I can help with subscription pricing and cost calculations.
Question: What does the Basic plan cost?
Requested: search {'query': 'Basic plan'}
Executed: search The Basic plan costs 20 USD per month.
Answer: The Basic plan costs $20 per month.
Question: How much does the Pro plan cost for 12 months?
Requested: search {'query': 'Pro plan'}
Executed: search The Pro plan costs 50 USD per month.
Requested: calculator {'a': 50, 'b': 12}
Executed: calculator 600.0
Answer: The Pro plan costs $600 for 12 months.
Question: What is the annual cost of the Enterprise plan?
Requested: search {'query': 'Enterprise plan'}
Executed: search Contact sales for Enterprise pricing.
Answer: Annual Enterprise pricing is unavailable. Contact sales.The important observation is that one agent handles several different execution paths without requiring a separate Python workflow for each question.
The final example demonstrates another desirable behavior: recognizing when the available information is insufficient rather than inventing an answer.
What happens internally?
Underneath create_agent, LangGraph manages a graph-based execution process.
Conceptually, the graph contains a model operation, a tool execution operation, conditional routing, and a shared message state.
When the model requests tools, execution proceeds to tool handling. Tool results update the state, and execution returns to the model. A normal final response terminates the run.
The returned dictionary contains the resulting agent state, including the accumulated messages.
These messages allow developers to inspect the actions that occurred instead of examining only the final answer.
Each invocation in this example starts an independent interaction. Conversation persistence across invocations requires additional state management or a checkpointer, which you will study later in the course.
The official LangChain agents documentation covers the high-level agent interface and its customization options.
The cost of autonomy
Autonomous agents introduce flexibility, but that flexibility has engineering and business costs.
A production engineer must evaluate whether granting additional decision-making authority improves outcomes enough to justify those costs.
Increased token consumption
Each model invocation processes relevant instructions, messages, tool definitions, and accumulated observations.
As an agent performs more actions, the conversation may grow larger.
For example:
| Model invocation | Input tokens | Output tokens |
|---|---|---|
| Initial decision | 800 | 100 |
| After search | 1,200 | 100 |
| After calculation | 1,500 | 200 |
| Total | 3,500 | 400 |
Even though the user submitted only one request, the system processed 3,900 tokens across three model invocations.
The approximate model cost can be calculated as:
Model cost =
(Total input tokens / 1,000,000) × Input price
+
(Total output tokens / 1,000,000) × Output priceExternal API charges, infrastructure expenses, retries, and applicable cached-token pricing must also be considered.
Repeatedly sending large tool results to a model can significantly increase operating expenses.
Increased latency
A conventional application might perform one model invocation.
An agent may require several model calls, database queries, and network requests before generating an answer.
If later operations depend on earlier results, those operations must occur sequentially.
Independent tool calls can sometimes execute concurrently, reducing overall latency. However, dependent actions such as retrieving a price before calculating a total cannot be fully parallelized.
Measure end-to-end execution time rather than only the duration of individual model requests.
Unpredictable execution and stopping conditions
An agent may repeatedly call the same tool, retry an unsuccessful search, or attempt irrelevant operations.
Every agent needs explicit stopping conditions.
The earlier example uses:
config={"recursion_limit": 15}The recursion limit constrains LangGraph execution steps. It does not represent exactly 15 tool calls or 15 model invocations.
If the graph exceeds this limit, execution can raise GraphRecursionError.
Production systems should also consider separate limits for model calls, tool calls, elapsed time, token consumption, and monetary expenditure.
A graph step limit alone does not prevent a single external operation from hanging.
Tip: Start with a small execution budget and increase it only when evaluation demonstrates that legitimate tasks require additional steps.
Security and operational risks
An agent that can retrieve information has a different risk profile from an agent that can modify a production database, send emails, or initiate payments.
Tool results may also contain untrusted instructions, particularly when retrieved from websites, documents, or external users. This creates a prompt injection risk.
Imagine a search result containing instructions to ignore the user’s request and disclose confidential customer information.
The retrieved content must be treated as data, not as authoritative instructions.
Production agents should enforce:
- Least-privilege permissions for every tool.
- Deterministic validation of tool arguments.
- User authorization independent of model-generated decisions.
- Human approval for sensitive or irreversible operations.
- Timeouts and bounded retries for external services.
- Idempotency protections to avoid duplicate side effects.
- Appropriate logging, monitoring, and sensitive-data redaction.
A system prompt can guide behavior, but it cannot replace application-level security controls.
Testing agent behavior
Traditional software testing often focuses on verifying outputs for known inputs.
Agent testing must additionally examine the execution trajectory: which actions occurred, whether they were appropriate, and whether the agent respected its boundaries.
For the subscription assistant, useful test cases include:
| Test case | Expected behavior |
|---|---|
| General greeting | No unnecessary tools |
| Known subscription price | Retrieve catalog information |
| Annual cost | Search followed by calculation |
| Unknown price | Report insufficient information |
| Repeated unsuccessful searches | Stop within the execution budget |
| Malicious retrieved instructions | Ignore unauthorized instructions |
Avoid requiring an exact tool sequence when several valid approaches exist.
Instead, evaluate whether required operations occurred, forbidden operations were avoided, and the final answer is supported by available evidence.
Later in the course, you will use tracing and evaluation tools to measure these properties systematically.
Common mistakes when designing agents
Using an agent for every problem. Deterministic calculations, validation rules, and predictable transformations are usually better implemented with ordinary code.
Providing vague tool descriptions. The model needs clear descriptions and argument schemas to select the correct tool.
Assuming tool binding executes tools. Binding exposes tool capabilities; an execution mechanism must still perform requested actions.
Allowing unrestricted execution. Without budgets and termination controls, agents can become expensive or unresponsive.
Trusting every tool result. Retrieved information can be incomplete, stale, incorrect, or malicious.
Evaluating only final answers. A correct answer does not necessarily imply a safe or efficient execution path.
The best architectural principle is to grant the minimum level of autonomy required to accomplish the task reliably.
From AI agents to agentic engineering frameworks
You have now moved beyond isolated model calls and individual tools into systems where models participate in application control flow.
As applications become more sophisticated, manually implementing every execution mechanism becomes increasingly difficult.
Consider an enterprise research assistant that must retain conversation state, recover from failures, pause for approval, execute concurrent operations, and provide detailed execution traces.
Different parts of the LangChain ecosystem address these engineering requirements.
In the next lesson, LangChain, LangGraph, LangSmith and Deep Agents, you will examine the responsibilities of these technologies, understand how they work together, and learn when to choose high-level agent abstractions instead of explicitly constructing your own execution graphs.
Build a Tool-Using AI Assistant
Build an AI agent that can search a simulated product catalog and calculate purchase costs using two independent tools. Allow the agent to decide which tools to call based on the user's request. Test the agent with questions requiring no tools, one tool, and multiple dependent tool calls. Set a recursion limit and inspect the executed tool calls to understand the agent's behavior.
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain.tools import tool
from langchain.messages import ToolMessage
from langgraph.errors import GraphRecursionError
model = init_chat_model("openai:gpt-5.4-mini")
PRODUCTS = {
"keyboard": 75,
"mouse": 25,
"monitor": 250,
"headphones": 100,
}
@tool
def search_product(product: str) -> str:
"""Search the product catalog for the price of a product."""
# TODO: Normalize the product name.
# TODO: Return the price or a product-not-found message.
raise NotImplementedError
@tool
def calculate_total(price: float, quantity: int) -> float:
"""Calculate the total purchase cost in USD."""
# TODO: Validate the price and quantity.
# TODO: Calculate and return the total cost.
raise NotImplementedError
# TODO: Create an agent with both tools and a system prompt.
agent = None
questions = [
"What can you help me with?",
"What is the price of a monitor?",
"How much would 3 keyboards and 2 mice cost in total?",
"What is the price of a printer?",
]
for question in questions:
print(f"\nQuestion: {question}")
# TODO: Invoke the agent with a recursion limit.
# TODO: Print the final answer.
# TODO: Inspect ToolMessage objects in the result.
# TODO: Handle GraphRecursionError.from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain.tools import tool
from langchain.messages import ToolMessage
from langgraph.errors import GraphRecursionError
model = init_chat_model("openai:gpt-5.4-mini")
PRODUCTS = {
"keyboard": 75,
"mouse": 25,
"monitor": 250,
"headphones": 100,
}
@tool
def search_product(product: str) -> str:
"""Search the product catalog for the price of a product in USD."""
name = product.strip().lower()
if name not in PRODUCTS:
return f"Product '{name}' was not found."
return f"{name}: {PRODUCTS[name]} USD per unit"
@tool
def calculate_total(price: float, quantity: int) -> float:
"""Calculate the total USD cost from a unit price and quantity."""
if price < 0 or quantity < 1:
raise ValueError(
"Price must be non-negative and quantity must be positive."
)
return round(price * quantity, 2)
@tool
def add_amounts(a: float, b: float) -> float:
"""Add two monetary amounts in USD."""
return round(a + b, 2)
agent = create_agent(
model=model,
tools=[search_product, calculate_total, add_amounts],
system_prompt=(
"You are a shopping assistant. "
"Use search_product for catalog prices. "
"Use calculate_total for multiplication and add_amounts "
"to combine costs. "
"Never invent missing product prices. "
"For general conversation, answer without tools when possible. "
"All prices are in USD."
),
)
questions = [
"What can you help me with?",
"What is the price of a monitor?",
"How much would 3 keyboards and 2 mice cost in total?",
"What is the price of a printer?",
]
for question in questions:
print(f"\nQuestion: {question}")
try:
result = agent.invoke(
{"messages": [{"role": "user", "content": question}]},
config={"recursion_limit": 20},
)
print("Executed tools:")
tool_messages = [
message
for message in result["messages"]
if isinstance(message, ToolMessage)
]
if not tool_messages:
print(" No tools executed.")
for message in tool_messages:
print(f" {message.name}: {message.content}")
print("Answer:", result["messages"][-1].text)
except GraphRecursionError:
print("The agent exceeded its execution limit.")
# Expected behavior:
# General question: no tools are necessary.
# Monitor price: 250 USD.
# Three keyboards and two mice: 275 USD.
# Printer: product not found.Summary
- An AI agent combines a model, tools, state, and an execution mechanism to pursue a goal through adaptive decisions.
- Traditional generative AI primarily generates content, while agentic AI can interact with external systems and respond to their results.
- Workflows follow developer-defined execution paths, whereas autonomous agents determine their next actions dynamically within specified boundaries.
- The ReAct pattern interleaves reasoning, actions, and observations until an answer is produced or a stopping condition is reached.
- LangChain provides create_agent as the high-level interface for building tool-using agents powered by LangGraph.
- Tool-call requests and tool results are represented using structured messages that enable reliable interaction between models and application code.
- Greater autonomy introduces additional costs, latency, security risks, and testing requirements that must be managed through explicit execution boundaries.