Building Your First AI Agent with LangChain
local graph
Chapter 6 — Building Your First AI Agent with LangChain
Section titled “Chapter 6 — Building Your First AI Agent with LangChain”In the previous chapters, we explored the theory behind AI agents—their architecture, the role of tools, memory, and planning, and how frameworks such as LangChain make it possible to orchestrate these components. Now, it’s time to move from theory to practice.
In this chapter, we’ll walk through the process of building your first AI agent using LangChain. We’ll do so through a practical use case: an e-commerce assistant for a digital piadineria. From understanding the scenario and assembling the core building blocks to developing and evaluating the agent’s performance, you’ll gain hands-on experience with LangChain’s capabilities. You’ll also explore how to trace and observe agent behavior using tools such as LangSmith, and finally, how to extend this assistant into a mobile experience.
We will cover the following topics:
- Introduction to the LangChain ecosystem
- Overview of the out-of-the-box components
- Use case – e-commerce AI agent
By the end of this chapter, you’ll not only have a working AI agent prototype—you’ll also understand the patterns and components needed to build and maintain intelligent, trustworthy assistants in real-world applications.
Technical requirements
Section titled “Technical requirements”To replicate the AI-powered assistant for the Piadineria restaurant, follow these steps:
- Clone the project repository
Start by cloning the GitHub repository containing the notebook, source code, and necessary assets:
git clone https://github.com/PacktPublishing/AI-Agents-in-Practicecd "your_folder"- Install required Python packages
Create a virtual environment and install the dependencies listed in requirements.txt or manually install the following packages:
langchain, openai, python-dotenvfaiss-cpu, sqlite3, pandas, requestslangsmith for evaluation and analyticspip install -r requirements.txt- Configure environment variables
Create a .env file in the project root with your configuration keys:
AZURE_OPENAI_API_VERSION=AZURE_OPENAI_ENDPOINT=AZURE_OPENAI_API_KEY=AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=LANGSMITH_API_KEY=LANGSMITH_ENDPOINT=LANGSMITH_PROJECT=Note
in this book, we will leverage Azure OpenAI GPT-4o as LLM, which comes with a cost of /1M tokens for outputs (you can find the whole pricing page here: https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/?msockid=126c546e17da69082d204197166168f0.
If you wish to leverage free LLMs, you can leverage the Hugging Face (HF) Hub and its native integration with LangChain. Install the required package:
pip install langchain-huggingfaceYou will then have two options:
- Load your model directly from the
from_model_idmethod:from langchain_huggingface import HuggingFacePipelinellm = HuggingFacePipeline.from_model_id(model_id="microsoft/Phi-3-mini-4k-instruct",task="text-generation",pipeline_kwargs={"max_new_tokens": 100, "top_k": 50,"temperature": 0.1,},)llm.invoke("Your query here")
(1) to quickly copy code into your coding environment, or click the Explain button
(2) to get the AI assistant to explain a block of code to you.
- Use the Hugging Face endpoint (you can create a free tier account to access it – learn more about HF accounts here: https://huggingface.co/pricing):
from langchain_huggingface import HuggingFaceEndpointllm = HuggingFaceEndpoint(repo_id="meta-llama/Meta-Llama-3-8B-Instruct",task="text-generation", max_new_tokens=100,do_sample=False, ) llm.invoke("Hugging Face is")
For example, if you want to leverage a chat model in LangChain from HF, use the following:
from langchain_huggingface import ( HuggingFaceEndpoint, ChatHuggingFace)llm = HuggingFaceEndpoint( repo_id="microsoft/Phi-3-mini-4k-instruct", task="text-generation", max_new_tokens=512, do_sample=False, repetition_penalty=1.03, )chat = ChatHuggingFace(llm=llm, verbose=True)You can find a full tutorial here: https://python.langchain.com/v0.2/api_reference/huggingface/chat_models/langchain_huggingface.chat_models.huggingface.ChatHuggingFace.html
- Prepare local resources
Ensure the following files and folders are present in the project directory:
piadineria.db: SQLite database with products and suppliersdocuments/: Folder containing PDF files (e.g., food safety certificates, owner history)- Run the Shopping Cart API
Launch a mock JSON server on localhost:3000 to enable the cart management tool:
json-server --watch cart-data.json --port 3000- Familiarize yourself with the notebook
Open the Jupyter notebook provided in the repo and begin interacting with the AI agent to do the following:
- Query product details
- Add items to the cart
- Search restaurant documentation
- Evaluate agent responses using LangSmith integration
- Launch the mobile application
Launch the Streamlit frontend to interact with the agent (the app will run on your localhost:8080):
streamlit run app.pyIntroduction to the LangChain ecosystem
Section titled “Introduction to the LangChain ecosystem”LangChain was introduced in October 2022 as an open source framework aimed at simplifying the development of applications powered by large language models (LLMs). Initially, it provided developers with tools to connect LLMs to external data sources and utilities, facilitating the creation of more dynamic and context-aware applications.
Over time, LangChain evolved beyond its original framework into a comprehensive ecosystem. This transformation was driven by the growing complexity of AI applications and the need for more robust tools to manage the entire lifecycle of LLM-powered solutions. Today, LangChain encompasses a suite of components and integrations designed to support developers from the initial prototyping phase through to deployment and ongoing management.

Figure 6.1: LangChain ecosystem
Figure 6.1: LangChain ecosystem
According to the official documentation, the entire LangChain ecosystem allows you to build, run, and deploy your AI-powered solutions. Let’s detail these three steps a bit more in the light of the preceding figure.
Build – the architectural foundation
Section titled “Build – the architectural foundation”At the base of the ecosystem are the foundational open source libraries: LangChain and LangGraph.
These two components represent the essential building blocks for AI application logic:
- LangChain offers modular components such as chains, agents, tools, and memory to help developers orchestrate LLM behavior. It focuses on composability and integration, making it easy to prototype and scale workflows.
- LangGraph, while newer, introduces a powerful paradigm based on a state machine – a computational model that defines a sequence of states and transitions between them, governed by events or conditions. It allows developers to construct multi-agent systems and complex control flows (e.g., looping, branching, conditional reasoning) using a graph-based abstraction. This is especially valuable for applications that require persistent state and complex planning.
Note
In this chapter, we are going to leverage LangChain as the library, while we will use LangGraph in the next chapter while dealing with multi-agent systems.
Together, these tools represent the build-time logic and control plane of the LangChain ecosystem. They’re open source, ensuring flexibility, transparency, and community-driven innovation.
Run – the operational layer
Section titled “Run – the operational layer”Once an agent is built, the next step is deployment. This is where LangGraph Platform comes into play. LangGraph Platform provides a managed environment to do the following:
- Host and deploy LangGraph agents or workflows
- Enable streaming interactions
- Integrate human-in-the-loop flows
- Handle real-time concurrency and state management
This platform bridges the gap between experimentation and production, abstracting away the infrastructure overhead typically associated with running LLM agents in cloud environments.
Complementing the platform is the Integrations layer (also open source), which allows developers to connect their agents to the following:
- APIs and webhooks (the latter are a way to allow external systems to receive real-time notifications or data when specific events occur during the execution of a LangChain process)
- Vector databases and data stores
- External tools such as calculators, retrieval systems, or third-party services
These integrations provide the agent with practical capabilities, allowing it to perform meaningful actions based on external data and systems, and we are going to cover some of them in the next paragraph.
Manage – observability and iteration
Section titled “Manage – observability and iteration”Management is often where the success of real-world AI applications is determined. In the LangChain ecosystem, this is handled by LangSmith.
LangSmith is a commercial platform that addresses these essential needs:
- Debugging agent behaviors
- Monitoring usage and performance
- Evaluating output quality
- Managing prompts and datasets
- Annotation and feedback loops for supervised improvement
Unlike traditional logging or APM tools, LangSmith is purpose-built for LLM-native applications, providing insight not just into the “what happened” but also the “why it happened”—from prompt structure to tool calls and intermediate reasoning steps.
By integrating LangSmith into your agent development lifecycle, you ensure you can do the following:
- Trace failures or unexpected outputs
- Evaluate the effectiveness of prompt versions or tool logic
- Continuously refine and optimize the application in production
In light of the preceding components, the LangChain ecosystem is no longer just a developer-friendly framework – it’s a structured platform for the entire lifecycle of AI agents and, more broadly, AI-powered solutions.
In the next section, we are going to zoom into some of the pre-build components that we can leverage at the “Build” level, and that we are going to use to initialize our AI agent.
Overview of out-of-the-box components
Section titled “Overview of out-of-the-box components”LangChain offers a comprehensive suite of pre-built components that facilitate the development of sophisticated language model applications. These components are organized into four primary categories: retrieval-augmented generation (RAG), storage and indexing, extraction, and agents:
- RAG: As we explored in previous chapters, RAGenables language models to go beyond their static knowledge by dynamically retrieving relevant information from external sources—typically document stores or vector databases—before generating a response. LangChain provides native support for the full RAG lifecycle:
- Document ingestion and chunking: Source materials (such as PDFs, Notion pages, HTML, or markdown) are loaded and broken into semantically meaningful chunks using flexible TextSplitters. These chunks are more manageable for embedding and retrieval.
- Embedding generation: Each chunk is embedded into a high-dimensional vector using embedding models (e.g., OpenAI, Cohere, Hugging Face).
- Storage in vector databases: These vectors are stored in pluggable vector stores such as FAISS, Chroma, Weaviate, or Pinecone, allowing for efficient similarity-based retrieval.
- Retriever interfaces: LangChain supports both basic retrievers and advanced retrieval strategies such as MultiQueryRetriever, ParentDocumentRetriever, and ContextualCompressionRetriever, each designed for use cases with different trade-offs in precision, recall, and relevance.
- Document ingestion and chunking: Source materials (such as PDFs, Notion pages, HTML, or markdown) are loaded and broken into semantically meaningful chunks using flexible TextSplitters. These chunks are more manageable for embedding and retrieval.
RAG is crucial for applications such as document Q&A, legal assistants, customer support bots, and research copilots—any context where real-time grounding in external data is necessary.
- Storage and indexing: Supporting the RAG pipeline is a suite of tools dedicated to storage and indexing. These components handle the backend preparation of data, ensuring it can be efficiently accessed during retrieval:
- Document loaders: LangChain includes over 50 document loaders for various data sources, such as local files, APIs, web pages, Notion databases, Google Docs, and more. These loaders standardize content into LangChain’s document format.
- Text splitters: These split documents based on character count, sentences, or recursive heuristics while preserving the logical integrity of the content (e.g., keeping paragraphs together or titles connected to content).
- Vector stores: LangChain supports integration with numerous vector databases through a common interface. Developers can switch between FAISS, Chroma, Qdrant, or Azure Cognitive Search without changing their retrieval logic.
- Metadata and filtering: Embedded metadata (such as source, date, or topic) is stored alongside document chunks, allowing for filtered or hybrid retrieval, where both keyword and vector search are combined.
- Document loaders: LangChain includes over 50 document loaders for various data sources, such as local files, APIs, web pages, Notion databases, Google Docs, and more. These loaders standardize content into LangChain’s document format.
This layer is foundational to any system that relies on structured or semi-structured knowledge access at scale.
- Extraction: LangChain also provides capabilities for information extraction, which involves identifying and structuring specific pieces of information from unstructured text. This is useful in domains where data needs to be mined from documents, chats, or responses and made available in a structured form (e.g., JSON or database records):
- Entity extraction: Developers can define schemas for named entities or key-value pairs, and the language model will extract matching information (e.g., from resumes, invoices, or clinical notes).
- Custom schema parsers: Using Pydantic or TypedDict, developers can guide the LLM to output data in structured formats, which can then be validated, stored, or used downstream.
- Structured output parsers: LangChain provides tools to enforce structured outputs, reducing the likelihood of hallucinations or formatting errors in sensitive use cases.
- Entity extraction: Developers can define schemas for named entities or key-value pairs, and the language model will extract matching information (e.g., from resumes, invoices, or clinical notes).
Use cases include automated form filling, summarizing meeting notes into CRM fields, converting legal text into clause mappings, or extracting timelines from event descriptions.
- Agents: The agent framework in LangChain introduces a higher level of autonomy and flexibility. Unlike static chains, agents can reason over a task, choose which tool to use, and adapt based on the outcome of intermediate steps:
- Tool abstractions: Tools are Python functions wrapped with metadata (name, description, input schema) that agents can invoke when relevant. LangChain integrates with OpenAI’s function/tool-calling capabilities seamlessly.
- Toolkits: Pre-packaged sets of tools are available for common platforms such as SQL databases, file systems, Python REPLs, or browser automation. Toolkits drastically reduce time to production.
- Agent executors: These components orchestrate the agent’s reasoning loop, track memory, invoke tools, and manage intermediate outputs. Options include ReactAgent, OpenAIToolsAgent, and ChatConversationalAgent, depending on the level of structure and flexibility required.
- Multi-tool reasoning: Agents can perform multi-step tasks by chaining tool invocations, interpreting results, and planning the next move—ideal for complex workflows such as “find a supplier, check stock, generate a quote.”
- Tool abstractions: Tools are Python functions wrapped with metadata (name, description, input schema) that agents can invoke when relevant. LangChain integrates with OpenAI’s function/tool-calling capabilities seamlessly.
LangChain agents can behave like dynamic assistants, orchestrating logic across various systems, whether it’s customer support, sales automation, or research tasks.
Even if not exhaustive – and continuously updating over time – the preceding list gives you an idea of the “model” behind LangChain pre-built components. In fact, these four categories of components reflect LangChain’s commitment to building not just LLM wrappers but composable AI systems – and as we have mentioned multiple times, modularity and composability are key, especially when building agentic systems!
By abstracting away common challenges—such as how to ingest documents, store and retrieve knowledge, extract structured data, or reason across tools—LangChain enables developers to focus on building intelligent, scalable, and production-ready AI solutions with confidence.
Now we have all the tools we need to build our first AI agent, let’s code!
Use case – e-commerce AI agent
Section titled “Use case – e-commerce AI agent”AI agents are reshaping the way businesses engage with customers—offering personalized, real-time assistance that feels conversational yet deeply functional. In the food and retail industry, this shift opens up new possibilities for enhancing the customer experience, streamlining operations, and building brand loyalty through intelligent automation. In this section, we are going to explore a concrete example in this industry.
Scenario description
Section titled “Scenario description”We’re going to build an AI agent for a real-world scenario: a modern, family-run Italian eatery called Mammachepiada. This piadineria—named after the expression "Mamma che piada!", which loosely translates to "Wow, what a piadina!" —has recently expanded its business by launching an online shop.
At its core, Mammachepiada is known for freshly made piadine, filled with high-quality Italian ingredients: prosciutto crudo, stracchino cheese, grilled vegetables, sun-dried tomatoes, and more. But beyond these ready-to-eat meals, the shop also sells individual ingredients—such as artisanal cheeses, pickled vegetables, and olive oil—for customers who want to recreate the experience at home.
The business operates as an e-commerce store where customers can do the following:
- Order freshly made piadine and meals for local delivery (within a certain distance)
- Shop for ingredients and products that are shipped nationwide
The goal of this chapter is to create a digital assistant—an AI agent—that can help customers interact with the store naturally. Users may want to do any of the following:
- Check what’s available on the menu
- Ask about product ingredients
- Ask about available items in stock
- Get suggestions for piadina pairings
- Create a customized cart and place orders
The agent will be ready to help with these tasks.
The result will be a friendly, efficient interface that brings Mammachepiada’s charm into the digital world—bridging tradition with technology, and language with action.
We will call our AI agent AskMamma.
In the sections that follow, we’ll walk through how to create this AI agent interface step by step, integrating retrieval capabilities, external tools, and logic to handle real-world interactions in a way that feels natural to the customer.
AskMamma’s building blocks
Section titled “AskMamma’s building blocks”In Chapter 1, we had an overview of the main ingredients of an AI agent:

Figure 6.2: Anatomy of an AI agent
Figure 6.2: Anatomy of an AI agent
Let’s now further detail them to design AskMamma:

Figure 6.3: Anatomy of the AskMamma agent
Figure 6.3: Anatomy of the AskMamma agent
Let’s explore each component shown in Figure 6.3:
- UI: The AI agent will live in the context of the restaurant’s mobile application. In this section, we are going to focus on the core components one by one, while in the next section, we will see the final result with the Streamlit UI.
- LLM: We will use Azure OpenAI GPT-4o, as it offers state-of-the-art reasoning capabilities while being optimized for latency—making it ideal for real-time restaurant interactions.
Note
Picking an LLM means balancing the following:
- Quality versus cost: Bigger models such as GPT-4o are smarter but pricier.
- Speed versus power: Faster models respond quickly, but may miss nuance.
- Context needs: Longer chats or big documents? Use models with larger context windows.
- Multimodal: Go with GPT-4o if your agent needs to see images. Choose the model that best fits your app’s needs—not just the biggest one.
- System message: We are instructing the agent to be a helpful AI assistant for the Italian restaurant.
- Orchestration: We will leverage LangChain for orchestration and LangSmith for observability and traceability.
- Memory: Our agent will be endowed with a short-term memory to keep track of the ongoing conversation.
- Knowledge base: Our agent will know all the relevant certificates and awards obtained through the years by the restaurant’s owners.
- Tools: Beyond the RAG tool mentioned, we will have two further tools:
- Database tool: This tool is going to retrieve in-stock items, their prices, suppliers, allergens, and other relevant information.
- Add to cart tool: This will be an API tool that is going to communicate with the backend of the restaurant’s application. In fact, the user’s cart is powered by a database, and this tool is going to add items to the DB according to the user’s query.
Note that, in this scenario, we are using three different types of tools: an unstructured knowledge base and a structured database as retrievers, and API integration.
Note
We are going to treat the knowledge base as a tool in the implementation, leveraging the agentic RAG concept explored in Chapter 5.
Let’s now see how to do that in practice.
Developing the agent
Section titled “Developing the agent”Let’s see how to build the AskMamma agent step by step:
- Importing libraries and initializing models: Here, we are going to initialize the two models we will need: the LLM, which will act as the brain of the agent (Azure OpenAI GPT-4o), and the embedding model that we will use to vectorize and index our unstructured PDFs (Azure OpenAI text-embedding-3-large).
import osfrom dotenv import load_dotenvfrom langchain_openai import (AzureChatOpenAI)import requestsfrom langchain.agents import (AgentExecutor, create_openai_tools_agent)from langchain_core.prompts import (ChatPromptTemplate, MessagesPlaceholder)from langchain.tools import BaseTool, StructuredTool, tool# Load environment variables from .env fileload_dotenv()# Access the environment variablesopenai_api_version = os.getenv("AZURE_OPENAI_API_VERSION")azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")openai_api_key = os.getenv("AZURE_OPENAI_API_KEY")azure_chat_deployment = \os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME")# Initialize the Azure OpenAI modelmodel = AzureChatOpenAI(openai_api_version=openai_api_version,azure_deployment=azure_chat_deployment,)from langchain_openai import AzureOpenAIEmbeddingsembeddings = AzureOpenAIEmbeddings(api_key = openai_api_key,azure_deployment="text-embedding-3-large")
- Initializing the SQL tool: Here, we are going to leverage one of LangChain’s pre-built components,
SQLDatabaseToolkit. This is a set of tools that can work with SQL databases and perform many tasks – including but not limited to inferring the schema, running queries, and checking query correctness.
To initialize the toolkit, you will need an LLM and a DB instance. For the latter, we will use a SQLite instance with the following schema:

Figure 6.4: Structure of the restaurant’s database
Figure 6.4: Structure of the restaurant’s database
You can find the DB in the GitHub repository of the book.
Let’s now initialize the toolkit and the first tool of the list:
from langchain_community.utilities.sql_database import SQLDatabasedb = SQLDatabase.from_uri("sqlite:///piadineria.db")from langchain_community.agent_toolkits.sql.toolkit import ( SQLDatabaseToolkit)sql_toolkit = SQLDatabaseToolkit(db=db, llm=model)sql_toolkit.get_tools()[0]Here’s the output:
[QuerySQLDatabaseTool(description="Input to this tool is a detailed and correct SQL query, output is a result from the database. If the query is not correct, an error message will be returned. If an error is returned, rewrite the query, check the query, and try again. If you encounter an issue with Unknown column 'xxxx' in 'field list', use sql_db_schema to query the correct table fields.", db=<langchain_community.utilities.sql_database.SQLDatabase object at 0x00000256933169F0>)]As you can see, the tool comes with a name (QuerySQLDatabaseTool) and a description of its capabilities, so that the agent will know when to invoke it.
3. Initializing the add_to_cart tool: Here, we need to write a proper HTTP operation to add items to the backend database of our restaurant’s application. To do so, we need to first prepare a DB instance that will host our user’s items in the context of a session. In this case, I initialized an empty db.json object as follows:
{ "cart": []}Before running the agent, we will need to make sure that this DB is online (we will run it locally for the purpose of this demonstration).
Note
This DB is different from the SQL DB mentioned in the SQL tool section! Let’s clearly distinguish between the two:
SQL DB: This is the restaurant’s store system of records, where owners can keep track of in-stock items, prices, suppliers, and so on.
db.json: This is the DB powering the user’s cart in the context of a session. It’s the application database.
Now that we have the cart DB, we can define our tool:
# Define the tool to add an item to the cart@tooldef add_to_cart(item_name: str, item_price: float) -> str: """Add an item to the cart.""" url = 'http://localhost:3000/cart' # Ensure this matches the JSON Server endpoint cart_item = { 'name': item_name, 'price': item_price }
response = requests.post(url, json=cart_item)
if response.status_code == 201: return f"Item '{item_name}' added to cart successfully." else: return f"Failed to add item to cart: {response.status_code} {response.text}"As you can see, we defined our tool with the @tool decorator, typical of LangChain. Then, we added a name (add_to_cart) and a description (in the format of """docstring"""). We also specified the two parameters needed for this tool to be properly invoked: the name of the item and the relative price; this means that the agent will do its best to retrieve these two elements before invoking the tool. Finally, the proper “action” is a POST method against the endpoint of the live cart DB.
4. Initializing the RAG tool: Here, we want to ground our agent to some context around the restaurant’s food compliance certificates and awards gained over the years. These are a couple of examples of paragraphs extracted from the provided PDFs:

Figure 6.5: Snapshots of the food certificates we are going to use as a knowledge base
Figure 6.5: Snapshots of the food certificates we are going to use as a knowledge base
To create our tool, we first need to properly vectorize and index our PDFs into a vector DB. To do that, we will use some pre-built components in LangChain for document processing, and, as a store, we will use a FAISS vector DB.
Definition
Facebook AI Similarity Search (FAISS) is an open source vector database and library developed by Meta AI for efficient similarity search and clustering of dense vectors. It enables fast retrieval of high-dimensional vectors, making it ideal for applications such as semantic search, recommendation systems, and LLM-based retrieval.
Let’s start by initializing our vectore_store object.
import faissfrom langchain_community.docstore.in_memory import InMemoryDocstorefrom langchain_community.vectorstores import FAISS#Create a FAISS index using L2 (Euclidean) distance with the same #dimensionality#as the output of the embedding function (e.g., length of a single embedded #vector)index = faiss.IndexFlatL2(len(embeddings.embed_query("hello world")))vector_store = FAISS( embedding_function=embeddings, index=index, docstore=InMemoryDocstore(), index_to_docstore_id={},)Then we can leverage LangChain’s libraries to chunk and process our documents:
from langchain_text_splitters import CharacterTextSplitterfrom langchain.document_loaders import PyPDFDirectoryLoaderfile_path = ( "documents")loader = PyPDFDirectoryLoader(file_path)documents = loader.load()text_splitter = CharacterTextSplitter( chunk_size=1000, chunk_overlap=0)docs = text_splitter.split_documents(documents)Note that, in this case, we leveraged a text splitter library – CharacterTextSplitter – which splits text based on character count. However, LangChain offers several types of text splitters to break large documents into smaller, manageable chunks before feeding them into a vector store. Some of the most popular include the following:
RecursiveCharacterTextSplitter(recommended): Tries to split on more meaningful boundaries (e.g., paragraphs → sentences → words → characters). It recursively falls back to smaller units if the chunk is too large.TokenTextSplitter: Splits based on token count (useful for LLMs with strict token limits such as OpenAI’s GPT models). Works well for aligning input with model context windows.NLTKTextSplitter/SpacyTextSplitter: Language-aware splitters that use sentence segmentation from NLP libraries. Good for use cases that require more syntactic preservation.
Once we split our documents into manageable chunks and pass them to vector_store.add_documents(), each chunk is transformed into a high-dimensional vector representation using an embedding model.
vector_store.add_documents(documents=docs)These vectors are then indexed in the vector store, allowing for similarity search later on. Here’s an example:
Chunk 1: "Mozzarella is an Italian cheese..." Vector: [0.21, -0.45, ...]Chunk 2: "Prosciutto pairs well with melon..." Vector: [0.67, 0.10, ...]Chunk 3: "Our piadine are made fresh daily..." Vector: [0.33, -0.88, ...]These embeddings are stored in the vector database along with metadata (e.g., source document ID, position in the original file). When a user asks a question, their query is also embedded and compared with the stored vectors to retrieve the most relevant chunks.
This process allows the system to “retrieve” knowledge based on semantic meaning, not just keywords.
Now we have all the ingredients to create our RAG tool:
retriever = vector_store.as_retriever()from langchain.tools.retriever import create_retriever_toolrag_tool = create_retriever_tool( retriever, "document_search", """ Search and return information about restaurant's health certificate and owner's history. """)As you can see, the vector_store object in LangChain comes with a method (.as_retriever) that automatically converts it into a retriever object. By doing so, we can create our tool with the create_retriever_tool function, which, as we have learned in many examples, will need a name and a description of the tool’s capabilities.
5. Initializing the system message:The last ingredient that we need before creating the agent is the system message. In LangChain, we can leverage the ChatPromptTemplate class, designed to structure prompts for chat-based language models.
It has the following key features:
- Role-based messaging: Define messages with specific roles to set the context and flow of the conversation
- Dynamic variables: Incorporate placeholders within messages that can be filled with user input or other dynamic data at runtime
- Context management: Maintain conversation history and intermediate steps using placeholders such as
MessagesPlaceholder, enabling the AI to generate coherent and contextually relevant responses
By using ChatPromptTemplate, you can create dynamic and context-aware prompts that incorporate variables and placeholders.
For our AskMamma agent, we will have the following structure:
# Define the prompt templateprompt = ChatPromptTemplate.from_messages( [ ("system", """You are an AI assistant for a Piadineria Restaurant. You help customers explore the menu and choose the best piadine or Italian specialties through friendly, interactive questions. When the user asks for product details (ingredients, allergens, vegetarian options, price, etc.), you can query the product database. Once the user is ready to order, ask if they'd like to add the selected item to their cart. If they confirm, add the item to the cart using your tools. When using a tool, respond only with the final result. For example: Human: Add Classic Piadina to the cart with price 5.50 AI: Item 'Classic Piadina' added to cart successfully. """), MessagesPlaceholder("chat_history", optional=True), ("human", "{input}"), MessagesPlaceholder("agent_scratchpad"), ]Let’s break it down into its three main components:
- System message: This is the instructional message that sets the overall behavior and boundaries of the AI.
("system", """You are an AI assistant for a Piadineria Restaurant. ...""")
- MessagesPlaceholder(“chat_history”): This is a dynamic placeholder that inserts the full conversation history (if available) into the prompt, so the AI has context about what’s been said already. Note that it is marked
optional=True, so the chat can begin fresh or continue an ongoing session. - Human message with input placeholder: This is where the current user message gets inserted. The
{input}placeholder will be replaced at runtime with whatever the user just typed (e.g., “Do you have any gluten-free options?”).("human", "{input}") - MessagesPlaceholder(“agent_scratchpad”): This is where intermediate agent reasoning or tool usage traces are injected during tool-augmented workflows.
Note
This structured format is ideal for agent-based systems where the following applies:
- You need persistent memory (chat_history)
- The agent can call tools (such as adding to cart, querying products)
- You want to give clear behavioral instructions up front (via the system message) It ensures the AI behaves consistently, adapts to context, and performs actions like a real assistant—without hallucinating or responding outside the scope of what it’s allowed to do.
6. Initializing the agent: We now have all the ingredients to initialize our agent. To do so, we will leverage the create_openai_tools_agent pre-built function available in LangChain, designed to construct an AI agent that leverages OpenAI’s tool-calling capabilities.
Definition
OpenAI’s tool-calling capabilities, formerly known as function calling, empower language models to interact with external tools or functions in a structured and dynamic manner. In the new landscape of AI agents, tool calling becomes one piece of a larger orchestration puzzle, where, as we have mentioned multiple times, we are adding an extra layer of intelligence on top of the LLM, so that we empower the agent to decide whether to use a tool, select which tool to call, chain tools together, plan and execute next actions, and so on. So, while the mechanics of tool-calling are still present, developers are moving away from writing raw tool-calling logic and toward agentic interfaces that handle that reasoning for you.
Let’s initialize it:
# Setup the toolkittoolkit = [rag_tool, add_to_cart, *sql_toolkit.get_tools()[:4]]from langchain_community.chat_message_histories import( ChatMessageHistory)from langchain_core.runnables.history import( RunnableWithMessageHistory)message_history = ChatMessageHistory()# Construct the OpenAI Tools agentagent = create_openai_tools_agent(model, toolkit, prompt)# Create an agent executor by passing in the agent and toolsagent_executor = AgentExecutor(agent=agent, tools=toolkit, verbose=True)agent_with_chat_history = RunnableWithMessageHistory( agent_executor, # This is needed because in most real world scenarios, a session id is needed # It isn't really used here because we are using a simple in memory ChatMessageHistory lambda session_id: message_history, input_messages_key="input", history_messages_key="chat_history",)Now it’s time to test it. Before running our agent, we need to deploy db.json so that the agent can properly execute the POST request from the add_to_cart tool if needed. To run your DB, you can execute the following commands in your terminal:
npm install -g json-servercd path_to_your_dbjson-server --watch db.jsonNow your db.json is running on your localhost at port 3000 (default port):

Figure 6.6: Application database running as a localhost
Figure 6.6: Application database running as a localhost
Great, now we can run our agent. To simulate a conversation, I will use a while loop:
# Interactive loopwhile True: user_input = input("Type your question here (or type 'exit' to quit): ") if user_input.lower() == 'exit': break result = agent_with_chat_history.invoke( {"input": user_input}, # This is needed because in most real world scenarios, a session id is needed # It isn't really used here because we are using a simple in memory ChatMessageHistory config={"configurable": {"session_id": "<foo>"} ) print(f'User: {user_input}') print(f'AI: {result['output']}')After running the code, I sent the following input (note that I’m sending some questions that assume the previous context is preserved to test the short-term memory):
- “hello”
- “which food certificates do you have?”
- “do you have ricotta cheese in stock?”
- “yes add it to cart”
- “and what is the supplier for the item?”
Let’s see the results. Note that I kept my agent verbose, meaning that we can see the intermediate steps and tool output. Following, the output is truncated in some intermediate steps, but you can see the whole version in the GitHub repository.
To make the following content more readable, I will highlight User input, AI output, and Reasoning steps. In between, I’ll add my comments to highlight some specific agentic patterns that are interesting to keep in mind:
User: HelloThe agent understands that this is a simple interaction that requires no specific tool.AI: Hi there! Welcome to our Piadineria Restaurant. How can I assist you today? Are you looking to explore our menu or need help with something specific?User: Which food certificates do you have?The agent understands that it needs to invoke the specific RAG tool with a specific query to answer this question.> Entering new AgentExecutor chain...Invoking: \`document_search\` with \`{'query': 'food certificates'}\`Piadineria Hygiene & Food Safety Compliance ReportPage 2: HACCP CertificationHazard Analysis […]> Finished chain.AI: We have several food safety certificates and compliance measures in place:1. **HACCP Certification**: We have a fully documented Hazard Analysis and Critical Control Points (HACCP) system that identifies and monitors all critical control points in the preparation of our products. This system is reviewed and audited quarterly by an external certification body.2. **Local Food Safety Training & PIC**: Every food handler in our piadineria completes accredited food safety training in accordance with local regulations. We also have a Person In Charge (PIC) at each location to supervise hygiene standards and enforce best practices.Would you like to know more about our menu or anything else?User: Do you have ricotta cheese in stock?The agent understands it needs to invoke some SQL tools for that. First, it needs to understand the schema with the sql_db_list_tables and sql_db_schema tools, then it will run the actual query with \`sql_db_query\`.> Entering new AgentExecutor chain...Invoking: \`sql_db_list_tables\` with \`{}\`responded: Let me check the availability of ricotta cheese for you. I'll need a moment to look it up.products, suppliersInvoking: \`sql_db_schema\` with \`{'table_names': 'products'}\`[…]Invoking: \`sql_db_query\` with \`{'query': 'SELECT * FROM products WHERE "Product Name" = \'Ricotta Cheese\''}\`[…]> Finished chain.AI: Yes, we do have ricotta cheese in stock! Here are the details:**Product Name**: Ricotta Cheese**Category**: Cheese**Price**: $7.75**Stock**: 15 units**Allergens**: Dairy**Description**: Creamy ricotta cheese, ideal for desserts or pasta.**Calories**: 120**Vegetarian**: YesWould you like to add this to your cart or need help with anything else?User: Yes, add it to cartThe agent understands it needs to invoke the add_to_cart tool and it is able to retrieve the two parameters needed – name and price – from the previous conversation.> Entering new AgentExecutor chain...Invoking: \`add_to_cart\` with \`{'item_name': 'Ricotta Cheese', 'item_price': 7.75}\`Item 'Ricotta Cheese' added to cart successfully.The Ricotta Cheese has been successfully added to your cart. Is there anything else you would like to add or any other assistance you need?> Finished chain.Once this tool is executed, if you rerun your db.json server, you will see that it has been updated accordingly:

Figure 6.7: Application database once it is populated with items
Figure 6.7: Application database once it is populated with items
AI: The Ricotta cheese has been successfully added to your cart. Is there anything else you would like to add or any other assistance you need?User: And who is the supplier for the item?The agent is able to invoke once more the SQL tools and, this time, is going to perform a join operation as well to look up the two tables and extract the Ricotta Cheese's supplier. Plus, we didn't specify the item but rather relied on the context-awareness of our agent.> Entering new AgentExecutor chain...Invoking: \`sql_db_list_tables\` with \`{}\`products, suppliersInvoking: \`sql_db_schema\` with \`{'table_names': 'products, suppliers'}\`[…]Invoking: \`sql_db_query\` with \`{'query': 'SELECT suppliers."Supplier Name" FROM suppliers JOIN products ON suppliers."Supplier ID" = products."Supplier ID" WHERE products."Product Name" = \'Ricotta Cheese\''}\`[…]> Finished chain.AI: The supplier for our Ricotta Cheese is **Dolce Italia**.Is there anything else you would like to know or add to your order?User: Thanks!AI: You're welcome! If you have any other questions or need further assistance, feel free to ask. Enjoy your meal!As you can see, the agent was able to do the following:
- Invoke the right tool depending on the user’s request, thanks to the natural language description each tool is equipped with
- Keep memory in the context of the user session
- Interact with the user in a conversational way
With three tools only, we were able to enhance the user experience with a powerful agent.
However, we are missing one important piece of the puzzle: how do we monitor the behavior of our agent? In fact, in real-world scenarios, observability and traceability, along with evaluation and continuous improvement, are key elements to keep in mind while designing your end-to-end architecture.
In the next section, we are going to explore how to do that with a few lines of code.
Observability, traceability, and evaluation
Section titled “Observability, traceability, and evaluation”Observability, traceability, and evaluation are critical components in achieving these goals. They provide insights into the internal workings of AI agents, facilitate debugging, and enable continuous improvement.
Observability refers to the ability to understand the internal state of a system based on its external outputs. In AI agents, this involves monitoring inputs, outputs, intermediate processes, and interactions with external tools or APIs. Traceability complements observability by providing a detailed record of the agent’s decision-making process, including the sequence of actions taken and the rationale behind them. Together, they allow developers to pinpoint issues, understand agent behavior, and ensure that the system operates as intended.
Evaluation involves assessing the performance of AI agents against predefined metrics or benchmarks. This can include accuracy, relevance, coherence, or other domain-specific criteria. Regular evaluation helps in identifying areas for improvement, validating updates, and ensuring that the agent meets the desired standards. It also plays a crucial role in maintaining user trust and satisfaction.
Note
- Several methodologies can be used to evaluate AI agents, depending on the task and context. These include the following:
- Human-in-the-loop evaluation, where human judges assess the quality or helpfulness of an agent’s response.
- LLM-as-a-judge, where a trusted model (e.g., GPT-4) scores responses for relevance or accuracy.
- Knowledge base (KB) validation, useful for retrieval-augmented systems where the correctness of retrieved documents matters.
- Automatic metrics, such as BLEU, ROUGE, or exact match for tasks such as summarization or question answering.
Choosing the right method depends on whether you are evaluating reasoning, factual accuracy, or user satisfaction.
However, as AI agents become more complex—capable of reasoning, using tools, and maintaining multi-turn memory—the need for robust observability and evaluation becomes critical. Unlike traditional software systems, where errors can often be traced to a specific line of code or logic branch, AI agents operate within probabilistic, dynamic environments. Their decisions depend not only on input data, but also on prompt structure, retrieved context, tool interactions, and previous dialogue turns. This makes debugging and performance assessment inherently more difficult. To address this, tools such as LangSmith have emerged, offering a structured way to monitor, trace, and evaluate agent behavior in real time.
LangSmith – part of the LangChain ecosystem – is a platform designed to enhance observability, traceability, and evaluation in AI applications. It offers tools for logging and visualizing agent interactions, analyzing performance metrics, and conducting systematic evaluations.
Key features of LangSmith include the following:
- Execution tracing: Visualize the agent’s step-by-step decisions, including inputs, outputs, and tool usage
- Performance insights: Monitor key stats such as latency, token count, and error patterns to optimize your system
- Flexible evaluation: Run structured evaluations with built-in or custom logic to assess response quality
- Prompt versioning: Track, compare, and iterate on prompts to refine agent behavior over time
- Collaboration-friendly: Share runs, feedback, and evaluations with your team to support joint development
LangSmith integrates seamlessly with various AI frameworks (not limited to LangChain!), providing a unified interface for monitoring and improving AI agents.
Let’s see it in practice.
The first step is that of creating an API key on the LangSmith settings page at the following link: https://smith.langchain.com/settings.

Figure 6.8: LangSmith admin portal
Figure 6.8: LangSmith admin portal
Note that, if you don’t have an account already, you will be asked to register (it’s free).
Then, you can install the LangSmith dependencies:
pip install -U langsmithSet up your environment with your variables. In our case, as we are demonstrating the agent in a Jupyter notebook, I’ll use the os module to initialize my variables directly while creating my LangSmith client:
from langsmith import Clientclient = Client( api_key=os.getenv("LANGSMITH_API_KEY"), api_url=os.getenv("LANGSMITH_ENDPOINT"),)Now we have all the ingredients to initialize a LangChainTracer object, a specialized callback handler in LangChain designed to capture detailed execution traces of your application’s components—such as chains, tools, and language model interactions—and send this information to LangSmith.
from langchain.callbacks.tracers import LangChainTracertracer = LangChainTracer(client=client, project_name="askmamma")As you can see, LangChainTracer is initialized with the client and an optional project_name parameter – this will mark the folder where our logs will be saved and analyzed. This tracer hooks into LangChain’s execution flow, capturing events such as the start and end of chains, tool invocations, and language model calls.
The tracer is the only additional element we will need to add to our existing agent. We can pass it as a config parameter when invoking our agent as follows:
agent_with_chat_history.invoke( {"input": user_input}, # This is needed because in most real world scenarios, a session id is needed # It isn't really used here because we are using a simple in memory ChatMessageHistory config={"configurable": {"session_id": "<foo>"}, "callbacks": [tracer]}, )This configuration ensures that each step of the agent’s execution is logged to LangSmith, allowing you to visualize the sequence of operations, inspect inputs and outputs, and identify any errors or performance bottlenecks.
For example, once we run our agent, we will see a new project initialized on our LangSmith dashboard:

Figure 6.9: LangSmith’s tracing projects
Figure 6.9: LangSmith’s tracing projects
We can already see interesting statistics such as error rate, total cost, number of runs, and others. Let’s now get more details from the AskMamma project overview:

Figure 6.10: LangSmith’s project overview
Figure 6.10: LangSmith’s project overview
Here, you can see three main sources of information:
- Runs: A run is a single interaction with the agent. For example, if the user types “Hi,” that’s a run.
Under each run, we can explore many details about the agent’s activity to answer questions. For example, in the run when we asked “which food certificates do you have?”, the agent took several steps, and we can have visibility of all of them in LangSmith:

Figure 6.11: LangSmith’s run overview
Figure 6.11: LangSmith’s run overview
We can also inspect those runs that failed:

Figure 6.12: LangSmith run steps overview
Figure 6.12: LangSmith run steps overview
In this case, the reason is that, when invoking the add_to_cart tool, the agent could not proceed further as the database was offline.
2. Threads: A thread can be defined as a session. Threads are marked by unique identifiers that you can initialize as names. For example, in our scenario, we initialized a nthread called <foo>:
In fact, you can see this thread logged in LangSmith:

Figure 6.13: LangSmith’s thread overview
Figure 6.13: LangSmith’s thread overview
Threads help you organize your runs and have a higher-level view of what’s happening behind the scenes of your agent:

Figure 6.14: LangSmith thread tracing overview
Figure 6.14: LangSmith thread tracing overview
3. Monitor: Here, you can some useful graphs for a 360-degree view of your agent, including trace count, LLM call count, success rates, and so on:

Figure 6.15: LangSmith’s monitoring dashboards
Figure 6.15: LangSmith’s monitoring dashboards
When it comes to evaluation, AI agents and, more broadly, LLM-powered applications cannot rely on traditional machine learning evaluators, such as accuracy, false-positive rate, ROC curve, and more. In fact, AI outputs are, by design, conversational, meaning that we need new tools and techniques to assess the performance of our AI-powered solution.
Typically, to assess the quality of an LLM or an agent pipeline, there are three main components you work with:
- Dataset:This is the collection of test cases—the inputs and, optionally, expected outputs—that your model or agent will be evaluated on. Think of it as your ground truth or benchmark set.
- Target function: This is the actual thing you want to test – in our case, the AI agent’s output. When you run an evaluation, LangSmith will pass each dataset input to this target function and capture the output—just like automated test execution. The output will then be compared to the expected output or assessed independently, depending on the evaluator you choose.
- Evaluator: Evaluators are used to judge the quality of the target function’s output. They can be LLM-based evaluators, string metrics such as BLEU or ROUGE, or traditional metrics such as accuracy (in case we are using LLMs for tasks such as classification or prediction). Definition BLEU (or Bilingual Evaluation Understudy) and ROUGE (Recall-Oriented Understudy for Gisting Evaluation) are two of the most widely used automatic evaluation metrics in Natural Language Processing (NLP), especially for tasks such as text generation, translation, and summarization. BLEU is a precision-based metric that evaluates the quality of generated text by measuring how many n-gram overlaps it has with one or more reference texts—commonly used in machine translation. ROUGE is a recall-based metric that assesses text generation by comparing how much of the reference text’s content appears in the output, often used in summarization tasks.
Let’s see an example with our AskMamma agent. In this scenario, we are going to leverage the LangSmith SDK; however, you can run sample evaluations from the UI Playground as well:
- Initializing the dataset: Here, we will initialize a LangSmith test dataset with some input-output pairs. Note that, here, we will think about general answers that do not require invoking tools – we first want to test our agent’s general answering capabilities.
from langsmith import Clientclient = Client(api_key=os.getenv("LANGSMITH_API_KEY"), # This can be retrieved from a secrets managerapi_url=os.getenv("LANGSMITH_ENDPOINT"), # Update appropriately for self-hosted installations or the EU region)dataset = client.create_dataset(dataset_name="QA Askmamma",description="A sample dataset in LangSmith.")# Create examplesexamples = [{"inputs": {"question": "What is Piadina?"},"outputs": {"answer": "A traditional Italian flatbread,typically made with wheat flour, water, and salt."},},{"inputs": {"question": "What is the tradition of Piadina?"},"outputs": {"answer": "Piadina is a traditional Italian flatbread that originated in the Romagna region. It is typically filled with various ingredients and served warm."},},]# Add examples to the datasetclient.create_examples(dataset_id=dataset.id, examples=examples)
You will then be able to visualize your dataset in your LangSmith control pane, under Datasets & Experiments:

Figure 6.16: LangSmith’s datasets and experiments
Figure 6.16: LangSmith’s datasets and experiments
- Defining the evaluator: The evaluator will compare the expected output with the actual output and evaluate it according to a specific metric. In our case, we will leverage an AI-powered evaluation. Note With AI-powered evaluation, we point to LLMs with a very specific prompt that turns them into “judges” of other LLMs’ output.
Let’s initialize our LLM as a judge. In this case, we will use a correctness metric that is going to evaluate the match between the expected output and the actual output:
from openai import AzureOpenAIaoai_client = AzureOpenAI( azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), api_key = os.getenv("AZURE_OPENAI_API_KEY"), api_version = os.getenv("AZURE_OPENAI_API_VERSION") )from langsmith import wrapperseval_instructions = "You are an expert professor specialized in grading students' answers to questions."def correctness( inputs: dict, outputs: dict, reference_outputs: dict) -> bool: user_content = f"""You are grading the following question:{inputs['question']}Here is the real answer:{reference_outputs['answer']}You are grading the following predicted answer:{outputs['response']}Respond with a score of 1-5, where 1 is the worst and 5 is the best. Your answer ONLY contains the score.""" response = openai_client.chat.completions.create( model="gpt-4o", temperature=0, messages=[ {"role": "system", "content": eval_instructions}, {"role": "user", "content": user_content}, ], ).choices[0].message.content return response.strip()Note
If you want to leverage pre-built evaluators, you can go for OpenEvals, an open source evaluation framework that provides a standardized way to build and register evaluation functions—such as accuracy checks, helpfulness ratings, or LLM-based critiques—and apply them consistently across datasets and models.
- Initializing the target function: The last ingredient is the logic of the evaluation – we want to match our agent’s output structure with the evaluator we defined.
def target(inputs: dict) -> dict:response = agent_with_chat_history.invoke({"input": inputs['question']},# This is needed because in most real world scenarios, a session id is needed# It isn't really used here because we are using a simple in memory ChatMessageHistoryconfig={"configurable": {"session_id": "<foo>"},"callbacks": [tracer]},)return { "response": response['output'] }
And that’s it! Let’s now run our evaluator:
experiment_results = client.evaluate( target, data="QA Askmamma", evaluators=[ correctness, # can add multiple evaluators here ], experiment_prefix="first-eval-in-langsmith", max_concurrency=2,)You can now inspect the results from the UI:

Figure 6.17: LangSmith’s evaluation results
Figure 6.17: LangSmith’s evaluation results
As you can see, both our actual outputs returned a correctness score of 5. For each example, you can inspect relevant metrics such as the actual output, latency, tokens, and so forth.
In addition to that, in the context of AI agents, we also need to take into account tool management:
- Is tool calling working?
- Is the agent able to invoke multiple tools to accomplish complex questions?
- Is the agent smart enough not to invoke tools if not needed?
In other words, you need to evaluate the trajectory of your agent. Let’s see an example of how to do so (note: the following code is an adaptation from the official LangSmith documentation you can find here: https://docs.smith.langchain.com/evaluation/how_to_guides).
- Initializing a new dataset: In this case, we will need to add the expected intermediate steps as follows:
import uuidquestions = [("Do you have ricotta cheese in stock",{"reference": "Yes we do have ricotta cheese in stock.","expected_steps": ["sql_db_list_tables","sql_db_schema", "sql_db_query_checker","sql_db_query"],},),("hi",{"reference": "Hello, how can I assist you?","expected_steps": [], # Expect a direct response},),("Can you add ricotta cheese to the cart with price 5.50?",{"reference": "The item 'ricotta cheese' has been added to the cart.","expected_steps": ["add_to_cart"],},),("Do you have food safety certificate?",{"reference": "Yes, we have a food safety certificate.","expected_steps": ["document_search"],},),]uid = uuid.uuid4()dataset_name = f"Agent Tool Eval Example {uid}"ds = client.create_dataset(dataset_name=dataset_name,description="An example agent evals dataset using search and calendar checks.",)client.create_examples(inputs=[{"input": q[0]} for q in questions],outputs=[q[1] for q in questions],dataset_id=ds.id,)
- Initializing our evaluator: Here, we will assess the correctness of the intermediate steps, making sure that the right tool is invoked:
Note In order to get access to our agent’s intermediate steps, we need to make sure that thefrom typing import Optionalfrom langsmith.schemas import Example, Rundef intermediate_step_correctness(run: Run, example: Optional[Example] = None) -> dict:if run.outputs is None:raise ValueError("Run outputs cannot be None")intermediate_steps = run.outputs.get("intermediate_steps") or []trajectory = [action.tool for action, _ in intermediate_steps]# This is what we uploaded to the datasetexpected_trajectory = example.outputs["expected_steps"]score = int(trajectory == expected_trajectory)return {"key": "Intermediate steps correctness", "score": score}
return_intermediate_stepsparameter is set equal toTrue.agent_executor = AgentExecutor(agent=agent, tools=toolkit,verbose=True, return_intermediate_steps=True)
We also need to make sure we initialize our evaluator with the proper schema so that it will parse the multiple outputs we have in our test dataset.
def prepare_data(run: Run, example: Example) -> dict: return { "input": example.inputs["input"], "prediction": run.outputs["output"], "reference": example.outputs["reference"], }# Measures whether a QA response is "Correct", based on a reference answerqa_evaluator = LangChainStringEvaluator( "qa", prepare_data=prepare_data, config={"llm": model})- Defining the target function: Here, we are simply creating a function that will invoke our agent with the proper config parameters.
def agent(inputs: dict):return agent_with_chat_history.invoke(inputs, config={"configurable": {"session_id": "<foo>"}})
Now we have all the ingredients to run our evaluation:
chain_results = evaluate( agent, data=dataset_name, evaluators=[intermediate_step_correctness, qa_evaluator], experiment_prefix="Agent Eval Example", max_concurrency=1,)Let’s inspect results from the LangSmith UI:

Figure 6.18: Evaluation results dashboard
Figure 6.18: Evaluation results dashboard
Great! As you can see, our agent performed fairly well, but we can see that one of the intermediate steps was evaluated as incorrect. Let’s understand why:

Figure 6.19: Agent steps evaluation results
Figure 6.19: Agent steps evaluation results
It seems that the agent didn’t run sql_db_query_checker. Nevertheless, the end result was correct. This is an important insight as we might want to either remove that one tool if not needed or be more prescriptive at the system message level for the agent to use that tool.
Evaluating agents is essential not only to judge the quality of their final responses but also to analyze the full trajectory of reasoning and tool use that led to those outcomes. By assessing both what the agent says and how it arrives at its conclusions—step by step—we gain a deeper understanding of its reliability, transparency, and alignment with intended behaviors. This holistic evaluation is especially important in complex workflows where trust, traceability, and correctness are critical.
Infusing the AI agent in the mobile app
Section titled “Infusing the AI agent in the mobile app”AI agents can be consumed in multiple ways: as a standalone application with an interactive UI, triggered by business processes, or embedded in existing applications. In our scenario, we will explore this last option.
Let’s say that we have a mobile application for our restaurant and we want to infuse it with a conversational UI powered by our askmamma AI agent. The look and feel of the new UI will be the following:

Figure 6.20: UI of the mobile app of our Piadineria
Figure 6.20: UI of the mobile app of our Piadineria
To develop the UI, we will leverage Streamlit, an open source Python library that makes it easy to build and share interactive web apps, especially for data science and machine learning workflows. Instead of spending time on frontend development, you can focus on Python code and Streamlit automatically handles the UI.
Among its features, Streamlit has community-supported components and templates to easily integrate with LangChain pipelines (for example, to create chat interfaces or text generation demos). This synergy lets you spin up proof-of-concept LLM applications quickly, using Streamlit’s interactivity and user-friendly interface alongside LangChain’s robust language processing capabilities.
In our scenario, we are going to leverage this integration to handle the agent component at the UI level. Let’s see some of the main code blocks that you have to consider while re-purposing your agent in Streamlit (you can find the whole code in the GitHub repository):
- Memory management:We first initialize a Streamlit-compatible message history object as a backend memory store for the conversation happening in our app. In this case, we will leverage the
ConversationBufferMemorybuilt-in LangChain memory class, which keeps all messages in a buffer (i.e., a running list).from langchain_community.chat_message_histories import (ChatMessageHistory)from langchain_core.runnables.history import (RunnableWithMessageHistory)from langchain_community.chat_message_histories import (StreamlitChatMessageHistory)msgs = StreamlitChatMessageHistory()memory = ConversationBufferMemory(chat_memory=msgs, return_messages=True,memory_key="chat_history", output_key="output")
With this approach, we will pass agent_executor a memory object that is Streamlit-compatible.
agent_executor = AgentExecutor( agent=agent, tools=toolkit, memory=memory, return_intermediate_steps=True, handle_parsing_errors=True, verbose=True)- Initializing Streamlit session states: In Streamlit, state refers to the ability to preserve variables across user interactions—such as remembering what was typed or clicked even after a rerun.
if 'chat_history' not in st.session_state:st.session_state['chat_history'] = []if "messages" not in st.session_state:st.session_state.messages = []
The preceding code makes sure that when a user opens your app, there’s a place in memory to store both the conversation history (chat_history) and the messages shown onscreen (messages). It’s like setting up two notebooks—one for tracking what was said behind the scenes, and another for what’s displayed to the user. Without this step, the app wouldn’t know where to save or retrieve past messages.
- Rendering persistent memory-based messages: In this block, we want to show the full chat history between the user and the AI, pulling it from memory so everything that happened earlier is shown again.
avatars = {"human": "user", "ai": "assistant"}for idx, msg in enumerate(msgs.messages):with st.chat_message(avatars[msg.type]):# Render intermediate steps if any were savedfor step in st.session_state.steps.get(str(idx), []):if step[0].tool == "_Exception":continuewith st.status(f"**{step[0].tool}**: {step[0].tool_input}",state="complete"):st.write(step[0].log)st.write(step[1])st.write(msg.content)
- Rendering current state messages: This displays messages stored only in the current session state—typically from the current run.
for message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])
- Rendering the AI agent’s chat interface: This code sets up the chat input at the bottom of your Streamlit app, inviting the user to ask something—such as “Want to know what’s in the menu?”. When the user sends a message, it’s immediately shown in the chat as a user bubble. Then, the AI (
agent_executor) takes over: it processes the prompt, possibly using tools along the way, and replies with an answer inside an assistant bubble.prompt = st.chat_input("Want to know what's in the menu?")if prompt:st.chat_message("user").write(prompt)with st.chat_message("assistant"):st_cb = StreamlitCallbackHandler(st.container(),expand_new_thoughts=False)response = agent_executor.invoke({"input": prompt},{"callbacks": [st_cb]})st.write(response["output"])st.session_state.steps[str(len(msgs.messages) - 1)] = \response["intermediate_steps"]
What’s nice here is that the AI’s reasoning steps—such as tools it used behind the scenes—are captured by StreamlitCallbackHandler and stored in st.session_state.steps. This lets you later visualize the steps in detail, giving the user a peek into how the AI came up with its answer.
Once your code is ready and saved in an app.py file, you can run it via streamlit run app.py to see the result in your localhost. This is what the final result will look like:

Figure 6.21: UI of the conversational interface of the AskMamma agent
Figure 6.21: UI of the conversational interface of the AskMamma agent
As you can see, we were able to interact with AskMamma and have some actions executed on our behalf, such as adding one item to the cart.
Summary
Section titled “Summary”Throughout this chapter, we have explored the fundamental concepts and practical steps necessary to create a functional AI agent. From understanding the basics of LangChain to implementing advanced features, you have gained valuable insights into the world of AI development.
By leveraging LangChain’s powerful tools and frameworks, you can create intelligent agents capable of performing complex tasks and making informed decisions. The knowledge and skills acquired in this chapter will serve as a solid foundation for further exploration and innovation in the field of AI.
In the next chapter, we will start seeing multiple agents working together in more complex scenarios, entering the domain of multi-agent applications.