1. Course Introduction and LangChain V1 Overview
Krishna introduces the one-shot LangChain v1 crash course, covering new features like middleware, memory, and deep agents.
Hello all, my name is Krishna and welcome to my YouTube channel.So guys, uh if you have been following my lang chain playlist, my langraph playlist, I've uploaded tons and tons of videos.Uh I have made end to-end projects.I have taught each and everything specifically uh on this particular frameworks.Now uh this particular video is just like a oneshot video uh on langchain itself because recently lang has come up with its uh recent version that is version v1 and uh there are some various changes specifically in termsof creating agents applying memories.Uh there is a new concepts that have uh recently been come that is called as middleware.So considering all these things I thought why not make a oneshot video with all the recent updates and uh you can watch this entire tutorial.It'll be a longer tutorial where I have included each and everything.
So uh go ahead enjoy this and make sure to hit like uh we'll keep a like target of thousand so that after completing this particular video I'm also parallely recording the updates with respect to langraph and there isone more new topic that is coming which is called as deep agents.So everything will be getting recorded as we go ahead.So go ahead enjoy this particular crash course on Langchen version B1.
2. Documentation Tour and IDE Setup
Overview of the updated LangChain documentation topics and introduction to Google Anti-Gravity IDE as the development environment.
Hello guys.So recently Langchain has come up with lot of updates in their specific documentation in the recent version and uh in this entire series of videos and in this module we are going to see the various changes uh whichlangin has specifically come up with you know so here inside the documentation if I just go ahead and click on docs.Okay.So here you'll be able to see there is lang chain lang graph and deep python.So we will be covering all these things all these modules uh again in an updated way so that we are always up to date with langen documentation.So first of all we will go ahead with langen documentation over here.Now here with respect to this particular documentation uh there are a lot of changes uh specifically with respect to syntaxes with respect to creating agents you know uh how to integrate with multiple different models um how to go
ahead and call a tool how to you know come up with a structured output along with that it also has lot support of messages you know different types of messages like AI message human message uh tool message.Along with that, we'll also be seeing something called a short-term memory.We'll be seeing how to perform streaming, you know, and there is a new concept uh that has basically come up with respect to middleware like built-in middlewares, custom middleware and uh we'll also be learning about guard drills andmany more things.So in this entire series of video we are first of all going to cover the entire lang chain uh recent framework whatever the updates are there and uh you know and we are also going to use an amazingpackage which is called as UV package manager.Now everybody if you have heard about UV package manager this is an extremely fast python package uh and project manager and it is completely written in rust.
So I'll give you an idea how you can actually go ahead and work with UV package manager and this is the entire installation you know uh how to probably go ahead step by step I'll be showing you howto how you can go ahead and create an environment um and along with this you can use any ID right there are also various ids that are now available we have VS code we have cursor we also haveGoogle anti-gravity nowadays I'm actually specifically using Google anti-gravity also so uh all these things we will try to cover and uh our main aim is always to stay up to date with respect to anything that is basically comingin lang chain.Okay.So uh from as we go ahead now we will be covering this step by step and uh I will show you how step by step how to go ahead and create an environment and we will just start with
a specific uh new project itself.So here you'll be able to see that I have already opened uh Google anti-gravity which I will show you in front of you right and I have created a folder which is called as langin updated now we'll startfrom basics now Google anti-gravity also you can go ahead and download it in order to download all you have to do is that just go ahead and search for Google anti-gravity okay and then this ID this is likea aentic ID like how we have VS code how we have cursor right you can also download for windows this It will be just be like a .exe file and then once you go ahead and install this uhyou will be able to start working on it.So this is the ID that we are going to specifically work on.The best part about this ID is like cursor you know it provides access to agent and it also provides you completely for free.
Uh I think for some number of requests not for uh infinity requests right but uh yes with the help of agents you will be able to write the code in a much more efficient way.Right.So now as we go ahead uh we will be covering uh the recent updated lang chain version and we'll try to see that how we can go ahead and create agents how we can go ahead and work withtools each and everything.So let's go ahead and start that.
3. Installing UV and Creating Virtual Environment
Step-by-step installation of the UV package manager and creation and activation of a virtual environment with uv init and uv venv.
So guys now let's go ahead and start with first of all creating a virtual environment and it is always a good practice that we start with creating a virtual environment and uh for any kind of projects that wework with.So the first thing is that uh we will try to create a virtual environment with the help of UV.Okay, UV package manager.But before we go ahead, you know, uh we need to install the UV package manager, right?So how to go ahead and install it.So if you just go ahead and search for UV package manager.So this is the first link that you will be able to see it.Okay.So once you click it here you'll be able to see in the installation you have options for Mac OS Linux and you also have options for Windows right so out of both of these options you can go ahead
and do it.Let's say that if you're using Mac OS or Linux, you can use this command.U if you are using Windows, you can directly open a PowerShell and you can execute this command.Right?So, how to open a PowerShell?So, first of all, what I will do, I'll copy this particular command.And now I will go to my um you know the ID and here I will open my terminal.The opening of the terminal is similar like VS code if you're using VS code till now.Okay.Now here inside this PowerShell see you have PowerShell option you have command prompt option.So here inside this PowerShell only you can just go ahead and paste this command and just press enter.So once you press enter the UV package manager you know will get automatically installed.Okay.So I've already done that installation so I don't have to do it again.
But just to show it to you I have actually done it.Okay.Now I will remove this.I will open my command prompt.Okay.or whatever like let's say that you're using Mac OS whether you're using u uh Linux you know it is up to you whatever things you really want to use you can go ahead and use it okay so tillthen I'll just go ahead and close this now here the first step is that how do I go ahead and create my virtual environment with the help of UV package uh package manager so first of all what Iwill do I will initialize this entire folder as a working repository now in order order to initialize it you know we will go ahead and use one command which is called as uv init okay so please make sureto remember this command so if you want to go ahead and just initialize a working repository let's say this is my working repository so first of all I will initialize it with the help of uv so for that
I will just go ahead and write uv init pro uh command once I execute this so here you can see it has initialized the project which is called as langchain updated so as soon as you init initialize theworking repository.Here you get some of the basic information, right?So here you'll see pi project.2ml.This will give the information like which versions we are specifically working with.So here we are working with python 3.13.So recent updated Python package manager.Uh later on like let's say if python package is also getting updated, you know again when you write uv in it, it'll just take the recent python version.Okay.And it is always a good practice to work with the rethin version.That's the reason you can actually go ahead and directly use this.Now along with that you'll be seeing that a default main.
py is basically there.Then you also have something called as python version file.So here you can see that I'm getting 3.13.Okay.So all this information you can see over here in a very simple way.Now the next thing what I will do is that I will just go ahead and write uv venv.Now see as soon as I write UV venv and I put a slash.Okay.Now what this will do is that it will go ahead and create a virtual environment.So once let me press enter.So here you can see that uh unrecognized subcomand slash.So by def by mistake I have put this slash I should not have put that.So what I will do I will just write uv venv.Now in order to create a virtual environment this is the most simplest command right.UV venv.As soon as I write uv VNV and I press enter.
So here you can see that now it is using this Python 3.13.2 and it has created a virtual environment at this specific location.So Venv is my virtual environment.Right now in order to activate it see if as soon as you create a virtual environment you need to install the libraries inside that virtual environment.Right now in order to install the specific libraries inside that virtual environment, I will first of all activate that virtual environment.Now in order to activate it, the command is given over here.See it is written activate with VNV script/activate.So if you go inside the script, there is something called as activate.I just need to go ahead and call this particular uh or execute this particular command.So what I will do, I will copy this over here.I will paste it over here and I will just execute it.
Now as soon as I do that here you can see that my my virtual environment right is activated which is called nothing but lunction updated.So this virtual environment has got updated.Okay.Now the next step is that how do I go ahead and start the installation of all the libraries.
4. Installing Libraries and API Keys
Creating requirements.txt, installing LangChain libraries with uv add, verifying versions in pyproject.toml, and setting up API keys in .env.
Okay.Now installation of the libraries is very important.Till now uh you know uh whenever we install a virtual a libraries you know you also need to make sure to keep an updated track of which version we are installing right uh but now with the help ofUV package manager this is becoming very very easy now okay so let's say that I go ahead and first of all create a requirement txt file and please make sure to create that particular file outside VNV folder soI will go ahead and write requirement txt now inside this I will be using some of the libraries.Let's say one of the libraries that I'm using is Langchin.Then I have Langchin community.Okay, Langchin community because I will be requiring this.Okay, then I also have Langchin- OpenAI because I want to use this Langchin OpenAI.I also have to use Langchin Grock because I may also use Grock models.
Then I also have Python-Env, right?So I will also be using this.Along with this I will also use langin/ google jenna my main aim over here is to install all these libraries is very simple because I want to show you all the examples with different different libraries and all okayso these are my default libraries and uh here you can see that it is also giving you some suggestions but don't go through that suggestion go ahead and type each and everything in front of you okay now thetime comes is that I have to go ahead and install all these particular libraries inside in my virtual environment.Now here the best thing is that see I'm not given any specific version.We are going to work with the recent version of all these lang libraries over here.Now what is the recent version that also we will go ahead and check it out.
So here what I will do I will write uv add minus r requirements txt right so this is how you go ahead and do the installation.See you can also go ahead and write uvp pip install minus r requirement.xt txt you you used to install all the requirement.txt by writing pip install minus our requirement.txt txt but with the help of UV you can justgo ahead and write uv add minus r requirement txt now once I execute this so here you can see that all my installation will start happening okay it'll give you some warnings but it's okay we can skip thiswarnings now here you can see by default all the libraries has got installed now here you can also see all the version of the specific libraries that has got installed now just by seeing this you'll not be ableto identify it so what I will do I will go ahead and Open this pipro.2mml.
Now inside this you will be seeing that okay langchin 1.1.0 has been installed and this is the recent version.Langchin community.4.1 is installed.Langchin Google geni 3.2.0 is installed and all the different libraries has been installed.Now because of this you will be at least able to identify it because I will also pass you this pi project.2ml to ML file to just get you understand that okay right now we are in the specific versionstomorrow any number of updates that specifically comes you don't have to actually worry about it you know at least you know which is the base version right but my suggestion will be always that try to work with therecent version of langin because there are many many functionalities that will get deprecated some of the functionalities may may get moved to some other libraries and many more things now this is where we have actually gone ahead and
uh you know created or installed all our libraries.Okay.Now the next thing is that I will also go ahead and create some keys.Okay.So I will be requiring three keys.One is the Google API key.So I will go ahead and write Google API key.Okay.So I will go to Google AI studio API key.And here you can see this is my dashboard.And there is an option which says create an API key.So I will go ahead and select one of the project.So let's say this is my project and I'll say okay this is my set key that I really want to go ahead and create or I'll go ahead and name it as lang chain updated and I will justgo ahead and create the key.Okay now you know how to create a keys right at least uh that I think you should be familiar with.
I will go ahead and copy the API key.Similarly I will go ahead with gro API key.So I will write gro API key and here is my API keys.Okay.And I will just go ahead and click on create API key and I can go ahead and create it.Right.Similarly with respect to open AI API.So I have created all these keys and what I will do I will quickly go ahead and create one file which is called asenv and I will go ahead and install uh paste this API keys over here.Right.So these are my API keys that I will be specifically using for my project.There is also one more library that I want to install for my uh Jupyter notebook that is nothing but UV add IPI kernel.Okay, IPI kernel.So IPi kernel you will be able to see that that is also installed.
IPI kernel is just like a kernel provided to the Jupyter notebook.Again let me repeat it guys.Whenever you want to add any independent libraries, you use this command which is called as uv add.Okay.And then you give the library name.Okay, library name.If you want to directly install it from the requirement.txt, then you can just go ahead and write ue add minus r requirement.TXT.Okay, like it's just like you are doing the installation from requirement.txt.So in this video what we have actually done is that in this section we have created a virtual environment.We have created a requirement.txt file which has all the recent libraries and we have installed it by using this command uv minus r requirement.txt.Otherwise you can also go ahead and individually you can go ahead and install all the libraries by writing uv the library name whatever library name that you want.
Let's say you want to go ahead and install lang.So here you can just go ahead and see that and here I have already installed it.So it is showing me resolve this and that right now in the next step what we are going to do is that we will start working on our lang uh updated documentation and we will start implementing agents.We'll show you how you can go ahead and integrate different kind of models.So let's go ahead and start with that.
5. Understanding What Agents Are
Conceptual explanation of agents: how an LLM decides to depend on third-party tools to fetch context and generate answers autonomously.
So guys now we have created a virtual environment.uh we have done the installation of all the libraries that we require in our virtual environment.Uh with the help of UV package manager uh you can also see all those things updated in pi project toml file and here you can see all these libraries we are going to specifically use it.Okay.Now uh you can also add your any descriptions that you specifically want to add also.Now what we are going to do is that we will start with the updated lang chain folder.Okay.So I've created a folder over here.So let me first of all delete this and create a new folder.So I will write updated lang chain.Okay.And uh I will start with the first file which is called as lang chain intro doip yb file.Okay.So, let me minimize this.
I will go ahead and select the kernel.I want Python environment VNV.Okay.And uh we'll write a markdown saying that this is the lang chain version v1.Okay.I will just go ahead and write it.And I will just go ahead and execute it.Perfect.Now, just to check everything is working fine or not.So I will also go ahead and open my code and I'll execute something.Okay.So this is working.The Python code is also working like oneplus 1 is a kind of a numerical operation.Now uh my env file is also been loaded.Everything is ready.So first of all as usual we'll go ahead and import OS.Then from env we are going to import load_.env.And we will go ahead and initialize load_.env.and we will initialize our open AI API key.So I will write OST environment and here you can see that I will go ahead and write open AI API key.
So uh one thing about uh Google anti-gravity is that it provides you a lot of suggestion.Okay.So you will be seeing okay quickly when you're coding it you'll quickly see all the suggestions that is coming up.Right.So OS.getb and open AI API key.So I will go ahead and execute this.So perfect.Um now the first thing that I'm just going to start okay um that is all about agents.Okay.Now first of all you need to understand what exactly is agents.So what I will do I will just open my file over here.I will create a new file so that I write something to you so that you get an understanding.Okay.See uh before uh you know when we started working right when initially we got generative AI at that time generative AI is becoming very very much as a important topic but nowadays everybody is specifically talking about a okay
so everybody is talking about agents and agents is altogether a very very handy topic okay very very important and handy topic altogether so initially if you go ahead and see you know initially we were just talking about LLMmodels so let's say that this is one of my LLM model now the LLM model can be anything it can be an open AI LLM model it can be a generative AI LLM model it can be uh youknow grock LLM model any open source LLM models the main task of the LLM model was that uh whenever we give any kind of input right input let's say if I go ahead and ask Hey uh write mea paragraph about artificial intelligence.So LLM will take that particular input and then it will give you a specific output.Okay, it'll give you a specific output like okay if I'm asking write a paragraph 200 words paragraph on artificial intelligence it'll give me a 200 words paragraph as an output.
Okay, this was a simple generative AI application.Okay, I used to say this as a Gen AI application.So, Gen AI application.Okay, application.Perfect.But now, uh as we move ahead, you know, so let's say that for this particular LLM model, if I ask a question, hey, provide me with the current AI news or today's current AI news.So let's say that I want to know the today'sAI news AI news okay now in this particular scenario you know that LLM has a cutff training training date okay so we basically say that LLM is already trained from previous data it does not have the current informationright recent information like let's say tomorrow's or today's information it does not have right so LLM has to be dependent on some thirdparty tool why it should be dependent on third party tool because when I'm asking this specific
question or tell me about the today's AI news LLM does not have that particular information right because it is already trained with the previous data it is not trained with today's data and there is always a cut offtraining date right this is really really important for you all to understand so this is one of the problem of just using a plain LLM.Now that's the reason whenever we say that if we need to answer if my LLM needs to answer this particular question, it needs to be dependent on some thirdparty tool, some tool.Okay, whenever we say some tool that it can be a third party tool, it can be any kind of tool.Okay, it can be a third party APIs, it can be Google search, it can be something else, right?And based on this particular tool what should happen is that whenever we give an input saying that today's AI what are the today's AI news the LLM should be able to make a decision okay I will not be
able to answer this particular question so now I'm dependent on some other tool which will be able to answer this particular question because this tool is currently connected to the current data or current like today's news it isbasically connected to right specifically AI news and this will be able to give me the response and This response that you basically get from here it is basically called as context right and then only the LLM will beable to generate the output right so in this particular scenario where we have a LLM being dependent on some other tool and from where we are basically getting a context as soon as we give an input the LLMis able to make a decision okay I'm not able to answer this I have to probably dependent on the tool which tool will be able to answer this particular question and it will be able to give the context
and generate the output so This is nothing but it is a basic agent.It is a basic agent.Okay, it is a basic agent.This is the simple functionality of an agent.Okay, so uh that is what an agent is all about.So I hope till now you have got a clear understanding what a basic agent looks like, right?So autonomously here you can see that it is able to make any kind of a simple decision like when to route what kind of query and how to properly solve that particular task.Okay.So uh whenever we talk with respect to an agent before creating a agent with the help of langin was little bit tough you know so before we used to use an LLM model then we used to create aa tool separately then we had to probably go ahead and do a linkage between this particular tool to the LLM we used to use a architecture which is called as react architecture okay react architecture now with the help
of this particular architecture we were building this specific agent but now Creating this agent has become simpler with the recent langchain version that is langchain uh version one.Okay.So now let me go ahead and show you that how we can quickly create an agent uh and how easy it is basically to create an agent.
6. Creating First Agent with create_agent
Building a basic agent with create_agent, adding a get_weather tool, invoking it with messages, and inspecting tool calls and responses.
So first of all in order to create an agent what we will be doing is that we will just go ahead and define something called as from langchain.Okay.Langchain dot agents we import something called as create agent.Okay.Create agent.Now as soon as we write like this langen dot aagents create agent.Here we go ahead and define agent is equal to create agent.And inside this first of all we give our model name.Now model name can be given through different ways.So directly if I'm importing the open AAI library I will be giving the my model name.Let's say my model name is GPT5 which is the recent uh you know specific open AAI model.And then I will go ahead and use tools.So right now I will keep this tools and empty because I don't have any other tools created yet.
Okay.And then apart from this tool we also provide some kind of system prompt.So here I will go ahead and write my system prompt saying that hey you are an helpful assistant.Okay.And then we have also kept verbose is equal to true.I will talk about what is verbose.Okay.It'll give you more information with respect to the invocation.Now as soon as I go ahead and just run or uh write this.So here you can see it got an unexpected keyword argument.I think verbose is not supported yet for this.So let me remove it.Okay.Now let me just go ahead and uh execute this agent.Now you'll be able to see some kind of diagram over here.Okay.And that diagram will definitely match this diagram that we have created.Okay.So this is how we basically go ahead and create a basic agent.
But right now you can just see that tools is right now empty.Okay.So what we have we have start, we have model and we have end.So that basically means we just have this input lm and output.still that tool connection is not there because we have not created any tool right so now what I will do I will just go ahead and define one function so let's say this is my get weather function Iwill give my city over here which will be in the form of string and this will also return string okay and here I will just say return the weather in this city is sunny that's it okay I canalso provide some dock string to provide some more information related to this particular function.It's like get the weather for a city.Okay.And now this same tool I can add it over here.
So that basically means if I ask what is the weather of Bangalore now the LM will be much more smarter enough to know that which tool it needs to call.Right?So now what I have done is that we have created a function which is called as which is called as get weather.Okay.So here what we have done is that we have created a function which is called as get weather.And this get weather is added as a tool to this particular LLM.Okay.Now if I ask hey what is the weather for this particular city?Now the LLM will make a decision.It will not have the current information obviously right because it is already trained with the previous data.So it knows that it has to call this get weather function or tool right and then it'll try to get the context.
The context is nothing but whatever this function is returning that is the context and finally it will be generating the output.Okay now see this as soon as I created a function get weather and I updated inside this tools.Right now I have this tool that is available.Now you see how this agent diagram will change.Now you can see that right.So now I have start the model which is my LLM and this is basically connected to my tools.Now whenever I ask any question with respect to weather this model will definitely go ahead and hit the tool get the response and it will display the output.Now in order to run the agent it is very simple.I will go ahead and run the agent over here.And running the agent is very simple.Well, I will write agent.invoke agent.invoke.And let's say that I will go ahead and uh you know just write what is the weather like in New York.
I know this is not going to give me New York weather because here I'm just returning a simple string.But just imagine that here we had some API calls that was basically made in order to get the weather information and uh here we can display that particular information.So now if I go ahead and execute this clearly you will be able to see that I'm getting one error.Let's see uh expected dictionary.Okay.So this is not the right format to give it.The simple reason is that we need to give it in the form of a messages.So I will write messages colon.Okay.And then I will give it in the form of a role.like role is like user because it is a user message human message.We will talk more about these different types of messages as we go ahead but right now I just want to show you how you can go ahead and run this particular agent.
So role is equal to user and content we are writing what is the weather like in New York.Now if I'm giving in this fun see the error is very simple over here that you have got expected dictionary.So whenever we are using this inbuilt function called as create agent for creating the agent in this particular scenario we have to give the input in the form of a dictionary wherein my dictionary key will be in theform of a messages.Okay here if I'm writing messages and I'm executing this.So here you can see I'm given the role is equal to user and content what is the weather like in New York.So if I go ahead and execute it now you'll be able to clearly see the response.See guys, I'm showing you the error.I will not cut that particular error part because I want to show you each and everything.
Okay.So now what is the weather like in New York?So first of all, this was the human message that has gone.You can also give it in the form of human message.We'll discuss more about the messages as we go ahead.Then here you can see the AI message is making a tool call.So somewhere here you'll be able to see that it has made a tool call.So let me just go ahead and see it.uh somewhere here you can see that it has made a tool call and it also knows which tool to call right get weather because it has this particular information.Now the question arises that how does LLM model knows that it has to make a get weather tool call because when we define this particular function get weather we have also put a dock string right and when we
are assigning this tool to this particular agent this dock string it the LLM will understand which is the dock string over here like get the weather for a city now it knows that it will go ahead and callthis particular function right so it made a tool message so here you can see the weather in New York is sunny it has just taken this particular uh city data and it is basically giving you the output likesunny right and then finally you can see the AI message it's sunny in New York right so once you get the context from the tool the model will be displaying the output right so if you want to alsodisplay the output over here you can just go ahead and write response is equal to agent this one and then I will just go ahead and write response of messages messages right so you can see messages and then
you can just go ahead and take the last message dot contain and here you should be getting the output right so when you write messages last one you'll be getting the last output if you remember if you removethis also you'll be getting the entire conversation and all right let me also show you one more way you can also directly go ahead and write like this agent do invoke and here you can write in the formof messages and here you can just go ahead and Write something like this.What is the what is the weather in New York?So let's see whether we'll be able to get the output or not.Like this also you can directly write.You don't need to even specify that whether it is an human message or not.It will automatically identify it.Okay.So now here you'll be able to see that and there is a small spelling mistake and here also you can see that I'm getting a output.
Okay and this is really really good even though I made a spelling mistake it is being able to give me the right output also.Okay so that's the most amazing part out there.So I hope you got a very basic idea of how to create an agent.What was an agent?We basically say this as an autonomous agent because based on the input the model is taking the decision which tools to call get the context and give you the output right so everything is happening over here but aswe go ahead we will be creating multiple tools so this is one of the tool like that we can go ahead and create any number of tools as we like okay so this was just a basic way ofcreating an agent with a recent version now which version we are talking with right so I'll write import lang chain
and import lang chain and I will just go ahead and print lang chain version right so it is 1.1.0 So I hope uh in this video we have understood about agents basic agents right uh agents are like youknow autonomously it will be doing this specific task that is assigned to it.So yeah in the next video now we will see how to integrate different different models we will talk about different kind of messages each and everything and uh as we go ahead like in this series we will bediscussing about that.
7. Model Integration: OpenAI, Gemini, Groq
Integrating different LLM providers using init_chat_model as well as ChatOpenAI, ChatGoogleGenerativeAI, and ChatGroq classes.
So let's go ahead and discuss the next thing that is model integration.So guys, now we are going to discuss about model integration with your LLM application or with your generative AI application and uh we will see three popular models that is open AI, Google geminy and gro you know ingro you have various open source models Google geminy whenever we talk about you know there are different geiny models and open AAI like you have GPD models you know 4.5 whichever you want to specifically go ahead and useit okay now what we are going to do is that we I will just go ahead and show you with the recent updated langen like what are the different ways of invoking a specific model.Okay.So first of all I will go ahead and make a code sale you know and if you remember in our env file we have all the three API keys loaded over here.
Okay.So first thing is that what I will do I will just go ahead and write import OS and then from env import load env right and I will go ahead and initialize the load env so that we loadall the models right and then we are going to set our environment variable from the open AI API key so open AI API key is equal to os get env key and here also we are going to usethe openi API key.Similarly, what you can actually do is that you can also load different different API keys like how you have seen over here.Grock API key uh you have Google API key and all right.So we will be using all these three models uh you know and uh we'll try to see that how we can go ahead and call them.Okay.So once I have initialized or once I have loaded all the environment variables specifically with respect to OpenAI API key, Google API key and gro API key.
First I will show you how you can load the OpenAI model.Right.So for this uh first of all I will go ahead and initialize from langin dot chat_models import init chat model.Okay.So init chat model is one of the libraries that we specifically use in order to initialize any kind of chat model itself.Okay.Then we go to the next statement.We will use a variable called as models.So let's say I will write model.And here I will write init chat model.And you know by default you can directly provide your model name.Okay.Now, since I want to show you with OpenAI, so first of all, I will go ahead and write GPT.Let's say I want to go ahead and try 4.1.Okay, 4.1.And here I will just go ahead and write models.Okay, instead of writing models, I can also go ahead and write model.
And now let's see uh what error I get.Okay, unable to inform provider for model is equal to okay, GTP I have written.It should be GPT 4.1, right?So I hope everybody knows different different models that are available in OpenAI.You have 4.1, you can have 4.5.Okay.So I will be using 4.1.So here you can see that now once I execute this, it gives me this information that it is a chat open AI model.Uh it has maximum output tokens all this information over here with respect to the model.Now comes like how do I go ahead and invoke the model?So let's invoke the model over here.Now in order to invoke the model uh with the help of init chat model or directly you can directly use this model.invoke invoke and let's say that I give a message saying that hello hello how are you okay
how are you now here you can see that clearly I've given a simple message this is a human message itself and I will be able to get the response now let's go ahead and display the response so thisis a simple like I'm giving this specific input this input goes to the model that is GPT 4.1 and it'll give us some kind of response okay now once I go ahead and see the response You will beable to see that I get an AI message content.Hello, I am just a program but I'm here and ready to help you.How can I assist you today?So this is the response from the LLM model that is GP 4.1.Okay, if I really want to just get directly see the content, I can also go ahead and write response.content.Okay, once I do this, this is the output of the model that you will be able to see.
So any kind of models that you have with respect to open AAI let's say I want to go ahead and try GPT 4.5 you can go ahead and change this whatever model you require or whatever model you reallywant to use from openAI you can change the model name and you can actually get it over here now comes the next one like how do I call a Google geminy model right so here I'm going to talkabout Google Germany model integration so let's try this also Okay.So for Google Germany what I will do I have already loaded the environment.So I will write from langchain from langchain dot chat models import init chat model.Okay.So init chat model and here I can use this.Okay.So this is a markdown right.So I will delete this and let me execute it over here.
lot of suggestions usually comes with uh Google uh this Google anti-gravity and I specifically use this I like it because for coding purpose it it becomes easy for me to quickly you know autocomplete all the code so uhnow what I will do is that I will go ahead and just use this specific code now see this code so I'm using from langen chat models import init chat model okay here we are loading the Google APIkey and then we are using init Chad model but to specify this Google Germany model we just have to write google genai colon whatever model name you are specifically using from Google gy right there may be different differentmodels so I will use google genai colon geminy 2.5 that will be model and I've just written modelinvokes why do parrot talk you know so this is the question that I have given up from the human I get
the response and I will just go ahead and display the response so once I display the response.Now you should be able to see that the output that you're getting will be from the Gemini 2.5 flashlight.Okay.So I have already initialized I have already loaded the Google API key.For the first request I think it is going to take some amount of time but after that uh if my API key is absolutely working I'm actually going to get the response.So this is how you can use init chat model and integrate with Google API key.So here you can see that I have got the answer.Parrots don't talk in the same way human dos with understanding intent behind every word instead they are remarkable something like that right so this is the output from the Google geminy 2.5 flash slide now I also want to
show you instead of using init chat model we can also use one more way okay and that is basically by using chat open AI chat open AI now in order to use chat open AI what I will dofirst of all I will go ahead and see in my requirement txt okay requirement.txt txt do I have the necessary library that I'm actually looking for okay now you may be thinking kish what kind of libraries that youspecifically require right so here we have already have lang chain open aai you know so langchain openai is basically installed or not so first of all you have to probably go ahead and check that so if that isinstalled I think you are good to go over here right now for chat openai if I really want to use what is the library that I need to import right so here I will go ahead and write from
langun _ openai input chat openai then we will go ahead and initialize chat openai and here I'm just going to go ahead and give my model name so model is equal to and let's say I will just goahead and use gpt 4.1 okay so this is my model is equal to and then if I go ahead and just write response is equal to model.invoke invoke invoke let's say I go ahead and write hello how areyou I should be able to get the same output like how we got it over here okay so using init chat model basically gives you an option of indirectly using this chat open see here also when you seethis specific model it is nothing but chat open AI so there is also one more way of basically calling this particular model now since you have chat open AI and in the requirement txt you have also installed lang
function Google gen AI.So here also you have an option of something called as chat Google generative AI.Okay.So if I go ahead and paste it, you can see from langchain Google genai import chat Google generative AI.I've used again Germany 2.5 flashlight to pirate stock.If I go ahead and see the response uh you know this kind of suggestion will come.So don't get worried about it because we are not going to use the suggestion over here.Okay.So here is my output from this specific uh Google um means Google Germany integration.Now uh these are the ways you can either use in chat model, you can use chat open AI.If you if you're specifically using OpenAI models, if you want to go ahead and use uh Google Germany models, then you can use chat Google generative AI or within the init chat model, you can go ahead and call
the Google uh Google models itself, Germany models.Now the third one that I'm going to use is Grock model integration.Now similarly Grock model integration will also be very very easy.Okay.So again two ways.One is by using init chat model.So here you can see now uh I am imported init chat model.I have my environment variable set up for grock API key.And then you can see I'm using init chat model with my gro.Now this time I'm writing grock over here.See before I I wrote what over here Google genai and the model name of Google Germany but here this time we are writing grock colon whatever model we want to specifically use from grock right you that quen isthe recent model that has been uploaded over this I used this and then we are using model invoke why do parrot talk I'm able to get the response okay now you have init chat model so there should also
be an option of chat gro okay so that will be my next one to show you so Here you can see that I'm getting the output.Okay.So why do parrots talk?Let me think about this.I know parrots are mimicking human speech and all and all all the information is over here.Now one more way that how we can basically call chatgro.So here you'll be able to see we can use lang grock.So again in the requirement.txt you can see we have imported lang grock.So I've imported from lang grock import chat gro.I'm calling the same model and I'm able to get the response.Okay.So here you will be able to see that I'm able to see the output with respect to the same thing.Okay.So this is uh pretty much clear I guess with respect to the model integration.
I think uh we have done a pretty good job uh with respect to this and uh the all the integrations specifically uh one two ways of simple integration of calling the loading the model is from init chat modelor let's say if you are using open AI then we use chat open AAI if you're using Google Germany let's say inside the init chat model you just write Google geni and then you basically write the model namewhichever model name you so this you can change I can also use uh geminy 2.5 flash.Let's say I want to go ahead and use this flash.So here also I should be able to generate the content.It's like a very very easy approach of calling any kind of model specific to the LLM providers.Okay.So here you can see all the outputs you are basically getting.
Okay.So this was about model integration.Now in my uh as we go ahead in this series, we will also be talking about the message structure, the streaming structure and all.Okay.uh so probably in this series now we should also go ahead and understand the streaming structure.So let's go ahead and discuss about that.
8. Streaming and Batch Processing
Demonstrates streaming LLM output progressively with model.stream and sending multiple parallel requests efficiently using model.batch.
So now we are going to discuss about this two important topics which is called as streaming and batch.Okay.Now why streaming and batch is important.So let's say that I go ahead and write model.invoke.You know how to invoke a specific model right?And let's say that I say hey write me a 200 words paragraph on artificial intelligence.So let's say if I'm asking this question to my model or to my LLM right and here you'll be seeing that we have to wait for the response to get generated and be displayed over here right.So this usually happens in invoke right but it is always a good practice that we try to stream the output as soon as is soon as it is generated from the LLM right so and that is where streamingcan be very very handful so here you can see most model can stream the output content while it is being generated now in this particular case we had to wait till the LLM completely generated the content and then
finally it displayed the output but in the case of streaming what we do is that we can also stream the output of the LLM model while it is being generated.So by displaying the output progressively streaming significantly improves user experience particularly for long responses.So for this we have to use this function which is called as stream.Okay, this returns an iterator that yields output chunk from the LLM and they also display it over here.So let's try to see that how this stream will basically work right now in order to do or work with streaming we will be using this inbuilt function called as model.stream stream.Okay.And let's say now I go ahead and ask, hey, write me a 200 words paragraph.Okay.On artificial intelligence.So let's display this right now.Okay.Let's execute this.So here you can see that it is creating a generator object.
But our main aim is that this is of a stream type, right?We also need to display the output from the stream.So what I will do?I will use a for loop.So I'll say for chunk in model.stream and let's display sorry let's display the stream output.Okay.So here I will go ahead and print and I'll just go ahead and write chunk dot text.Now let's display this.Now here you can see that once we go ahead and execute this it did not wait for the entire content to be generated.So what we have done is that as the content is being generated from the LLM, the LLM is giving you the output.It is also getting displayed over here.Okay.In a much more better way for you all to see, what I will do, I will use some special character to just you know to just show you the content that is basically generated.
So I will use this two parameter end is equal to that basically means I'm using some kind of delimiter over here.as soon as any token is generated from the llm and we also going to use flush is equal to true.Okay.Now see the output I have written write me a 200 work paragraph and here you can see that we are generating this particular text and this text is basically getting generated over here.Okay.Now let's try some more uh some more good things inside this uh instead of just writing like this you know I will also go ahead and uh you know just try to display something over here so let's goahead and do this and here you can see that I'm just writing why do parrots have colorful feathers okay feathers so now it is going to print the chunk text and here you can see that paragraph by paragraph
as the content is basically getting generated it is also being displayed in the output.So this is an example of stream and the main thing is that you can stream the output from the llm while it is being generated.Right?So we don't have to wait till the entire text is generated.Now if I go ahead and ask the same question over here.So let's say I go ahead and ask the same question and here instead of you know why do parrots have colorful feathers?If I just go ahead and use model.invoke invoke.So here what I will do I'll remove all these things.Okay, I will remove all these things and we will try to generate it by using model.invoke.Now see we have to wait for the output.Okay, model.invoke it is giving me some syntax.No worries I will fix it.Now see I'll wait for the output.
I'm waiting waiting waiting and then finally the response gets generated.Right?Once the entire response is output is created then only it'll get generated.But in this case of streaming as it is generated we are also able to see.Okay.Now similarly there is also one more concept which is called as batch.Okay.Now batch is a collection of independent requests to a model which can significantly improve performance and reduce cost as the processing can be done parallel.Now there may be scenario that you may have multiple inputs.So let's say I will go ahead and create some kind of response.See, I'm using model.batch function.Inside this, I have a list of inputs.Like my first question is why do parrots have colorful weathers?I'm writing how do airplane fly?What is quantum computing?Now, I have three different questions and I want to send all this question as an input to the LLM model in a parallel way, right?
I want the output parallelly, right?So that is what it is over here.You can see batch is a collection of independent requests to a model which can significantly improve performance and reduce cost as the processing can be done parallel.So if I'm giving three inputs, this will go parallelly to the model and generate the output.So let's go ahead and see the output.Now here you can see all these three questions has gone together by using this model.batch and automatically you'll be able to see all the output all at once.Okay, three responses it will generate and you are able to see the output all at once.Similarly, I can also set one more parameter inside this which is basically called as max currency.Right?So there is a config parameter which you can basically add along with this model.batch functionality which says that how many parallel calls you can actually make.
So here you can go ahead and set it max concurrency is equal to five and then probably go ahead and do it right.So anyhow my questions are three if I'm giving 10 10 different questions all at a time.So it'll take five five and then it'll probably send it to the LLM and generate the output.Right?So I hope you got a very clear idea about streaming and batch and this is necessary because if you are working for any company developing chat bots most of the time you are definitely going to use streaming butthere may be scenarios that you also want to probably go ahead and use batch functionality.So I hope you like this particular video.So I hope you have understood this.Now let's go ahead towards the next section wherein we are going to understand about tools creation.
9. Tool Creation and Tool Execution Loop
Creating tools with the @tool decorator, binding them to models with bind_tools, and implementing the manual tool execution loop.
So guys till now we have already discussed about streaming and batch and along with this we also saw the model integration like how you can go ahead and integrate different kind of LLMs with the help of two importantfunctionality or two important libraries.one is initate chat model and you can see that we have also used chat gro chat open AI and uh along with that we also had chat Google generative AI right now it's time that uh we move towardsone more step ahead and we talk about how to go ahead and work with tools so if you remember we had discussed about a simple agent right in an agent basically an LLM will be connected to a toolnow this tool is just some kind of functionality It can be a API request.It can be uh inbuilt tools.It can be news reporting tools.
It can be Google search engine tool.It can be any kind of independent functionality tool.Right?Now in this series of videos now we are going to understand like how we are going to go ahead and create tools.Right.So first of all what I will do I will go ahead and create a ipynb file.And here you can see tools definition is basically given.Model can request to call tools that perform tasks such as fetching data from a database, searching the web or running code.Tools are pairing of a schema including the name of the tool, argument and definition and function or core routine to execute.So here what we are basically going to do is that first of all I will show you how you can basically create a tool right in a simple way.So first of all as usual I will use one of my LLM model.
The LLM model that we are going to use is Grock Quen 332B.And here you can see that I'm also able to invoke the model.This we have already learned in the previous section.Right?So inside this response you will be able to understand like what is the response that you're getting from the LLM.But with this particular model I need to integrate some tool.Okay.Now in order to integrate what tool I will first of all create and what is the basic schema definition for creating a tool.So whenever we need to create a tool first of all I will go ahead and you know use a import function from langen.tools I will import something called as tool.Okay.Now this tool library that we are importing over here will be used as a decorator.So when we use this as a decorator on top of any function that function will actually become a tool in langin.
Okay.So here first of all we'll write add the rate tool.I will go ahead and define my function.Let's say this function is nothing but get weather.Now inside this get weather I will be using a variable which is called as location.And this will give you a string type.Okay.And here I will also go ahead and define.See if you see the definition whenever we talk about tool it is nothing but is pairing of schema including the name of a tool description and or argument definition.So here I am going to go ahead and provide some dock string.Now this dock string will play a very important role.I will talk about it.Okay.So I'll say at a location.Okay.So get weather at a location.Now this definition uh this schema that we have or this doc string that we have defined over here this is important because when we bind this tool with the LLM the LLM will be able to identify the functionality
of this particular function okay what exactly it is doing from this particular dock string okay so that's the reason we have written this dock string so now I will go ahead and say return and here you can writeany functionality that you want okay so let's I'm hard coding right now the temperature.What you can actually do is that you can go ahead and hit a API request or database request over here and get the information.So I'll write it's sunny in this specific location which location I'm actually using.Okay, by default I'm saying it's sunny.Okay, now this is done right.I have a tool over here.Now this tool needs to be binded with my model, right?So if you see over here, if I want to bind this LLM with this particular tool, how do I do it?Okay.So for that I will be using model dotbind tools.
Okay.So bind tools and here we are basically going to use this particular tool which is called as get weather.Okay.Get weather and here we can go ahead and write model_with tools.Now this is one way.Okay.The other way is that what we have learned right we can directly use this we can use this function right create agent give the model name give the tools and automatically this will get created right that we havealready shown and this is one of the functionality which we used to use before also that is nothing but binding tools okay now once I bind this tool the next thing is that how do I call this okaysee now in order to call it I will say model bit tools dot invoke what's the weather like in Boston and here now I can go ahead and iterate through this response tool calls see if I just go
ahead and print the response first of all you'll be able to see I'll print this response now when we are printing this response here you'll be able to see that the reasoning contain is the user is asking forabout the weather in Boston I need to use the get weather function see automatically now LLM is able to make a decision that what functionality needs to be called and here you can see that we also printing thetool calls that it is doing.So tool call of name is nothing but weather and argument it is basically requiring is nothing but location.Okay.So this is the most simplest way of you know working with a tool just directly go ahead and use a decorator provide some kind of schema or dock string and just go ahead and bind it with the tool.Either you can do like this or if you're directly creating an agent you would just define that particular schema means the function and then you use this create agent with the model name with the tool name and here
you'll be able to get it right.This is the most simplest way.Okay.Now I really want to show you one more important technique which is called as tool execution loop.Tool execution loop.Now see first of all inside this what I will do I will paste this code now see initially we set up a message from the role user saying that the user is sending the message what's the weather inBoston now we are using model with tools do invoke of message then here I will be getting my AI message and inside this message we are also appending this particular AI message and you know inside this AI messageit will be nothing but it will be a tool call right we are making a tool call which is nothing but weather data Right?We are making a tool call over here.Right?Now for tool calls in AI message.tool calls.
Now that get weather.invoke of tool call we are doing.See at the end of the day if you see whenever we make a tool call we are basically calling get weather and internally we are using this get weather.invoke of tool call so that we get the response fromthis.See over here if I go ahead and show you when we are making the tool call the tool call will go ahead and provide us the output that is nothing but the context and with the help of thisparticular code get weather.invoke of tool call we are getting the tool results and that also we are appending it inside our message and finally you'll be able to see the message text since we are using model with tool.invokeinvoke now see I will execute this step by step you'll be seeing the weather in Boston is sunny right and if you go ahead and just see this messages section messages section you should be able to see the
role the AI message that you got and the tool message like when the tool got executed it is giving this particular response at sunny in Boston so when model with tools do invoke it is going it is basicallygetting the context from the tool and it is displaying the output Right.So that's easy with respect to the tool execution loop.Okay.So I hope uh you got an idea with respect to tools.Very basic way of creating this.Now the main thing is that internally you can write any definition you want to use inbuilt tools that are available in lang chain.You can directly go ahead and write the code.The most important thing is that what response you are basically generating out of that particular tool.Right?So this was a quick revision on understanding about how you can actually specifically work with a tool.
So now as we go ahead now we are also going to discuss about one more uh important thing that is called as messages.Now what are the different types of messages there is something called a system message AI message human message.So that part we will go ahead and discuss it.So yes uh let's go ahead and discuss about that.
10. Message Types: System, Human, AI
Introduction to messages as context units, covering text prompts vs message prompts and the roles of system, human, and AI messages.
So guys, till now we have covered various topics specific to tools and how you can integrate tools with the LLM models um and probably go ahead and create a generative AI application.Now we are going to move towards our next topic which is called as messages right and messages uh in short are a very important data structures that can be specifically used with langin.uh I will for I have written the definition I will go ahead and write the code in front of you each and everything we'll discuss step by step so first of all the messages are the fundamental unit ofcontext for models in langen they represent the input and output of a model carrying both the content and metadata need to represent the state of a conversation when interacting with an LLM messages are object that contain role contentand metadata role is super important.
Okay, role basically identifies the message type.Now first of all what I'll do is that in order to show you the messages till now we have discussed in various places right you can see that I'm getting an output with respect to tool.So this is one kind of message whenever you see an output from a specific model right like here we have written model.invoke invoke on a specific question.The model when it is giving its output will be in the form of a message.So whenever a model gives an output, it is basically a AI message.Whenever a human is giving an input, it is nothing but a human message.So there are different kind of message structures that we are going to see.There are specifically three types which we are going to discuss one by one.Okay.So first thing first, what I am actually going to do, first of all, I will go ahead and initialize my model.
Okay, now you know how to initialize your model.So I have imported OS from langchin.ch_model.Import init chat model.I'm using the gro API key as my environment variable.And then we have used init chat model with this quen model from grock.Okay.So I'll go ahead and execute this.Now see this is really important.Okay.Whenever I go ahead and write model.invoke on any specific input.Okay.So let's say I'll say uh please tell me what is artificial intelligence.Okay.So this is my question.Now by default when I give this specific input to the model this is treated as a human input or a human message.So once I execute this this as an input to the LLM is going as an input which is nothing but a human message.And when I want to see the output, I'll just go ahead and execute this.
Now my output will be basically an output from the LLM which is nothing but an AI message.And the content that is inside this is the output from the LLM model.Okay.Now this is what a simple message basically looks like.Now two things we have discussed about human message AI message.I will deep dive more into it and probably talk more about it.Okay.But first of all before going to human message AI message we will start with a text prompt.Okay.So text prompt are nothing but they are strings idle for straightforward generation task where you don't need to retain conversation history.Okay.Now here you can clearly see that whenever I'm writing model.invoke with some specific question.Okay.So here when I'm writing model.invoke invoke with some question.Let's say I'll say what is langchain?Okay.Now in this particular scenario, I have not specified anything to the model like how the model should behave, right?
I'm just providing a simple text, right?This text is treated as an human message internally.But I can also say this as a text prompt.Okay, so idle for straightforward generation task where you don't need to retain any conversation history.Let's say that I just want to give an input and get an output from the model.So in this particular scenario I will just go ahead and use this phenomena right.So when I say model.invoke what is langchain I will directly get an output in the form of AI message.Okay now use text prompts when you have a single standalone request.You don't need conversation history.You want minimal code complexity and all.Right now we will see in the different type like one more category which is called as message prompts.So here we have seen about text prompts.In text prompts I just specify my input.
I get the output from the model.So now we will try to understand how is message prompts different than the text prompt.Okay.Now here we'll first of all see the definition.Alternatively, you can pass messages in the list of messages to the model by providing a list of message object.Okay.Now you need to first of all understand if I want to provide a list of messages, it can be a human message, it can be an AI message, it can be a system message.Now you should understand what exactly is a system message.System message is just like an instruction like how the LLM should behave.Okay, again let me repeat it.What is a system message?It is nothing but it is a kind of a instruction to the LLM like how it should basically behave.So in the case of message types you have different messages like system message, human message, AI message and tool message.
First of all we'll understand the definition of system message.System message tells the model how to behave and provide context for interaction.Human message is nothing but it represents user input and interaction with the model.AI message is nothing but response generated by the model including text content, tools and metadata.Tool message represents the output of a tool call.Okay.So all this information is basically over here.So here you can see system message definition, human message, AI message and tool message.So let's go ahead and see this particular example.Okay.So first of all what I will do I will go ahead and import all these messages types.So in order to import I will use from langchain dot messages import system message human message AI message.Okay now I will create a list of messages.Let's say that I'm having a conversation history also.
So that's the reason I'm creating this list of messages.So let's say first of all I use a system message.Now this system message is just like an instruction to the LLM model like how the LLM model should behave.So I'll go ahead and write you are a poetry expert.Okay.So this is my first message.Let me go ahead and write human message over here.In the human message I will go ahead and say um this will be an input.I'll say write an write a poem on artificial intelligence.Okay, artificial intelligence because in chatbot usually this kind of conversation happens in a conversation history, right?There'll be a list of messages that will be happening.So let's say here uh I give the output or let's say I give this two information like a system message and a human message.Okay.So this is my list of messages.
Now I'll use model.invoke and I'll give this messages over here.Okay.Over here I'll get it and I'll go ahead and get my response.Now let me do one thing.Let me go ahead and print my response dot content.Okay.Now see this both the messages are basically going.Okay.First is the instruction to the LM like how you should basically go ahead and u act like I'm saying you are a poetry expert and then probably I've given the input and based on this input I will begetting my AI message as the output okay the user wants a poem about artificial and let me start thinking about the key themes related to AI creating aspects how human build AI then maybe do and all this informationis basically there and you're getting the output okay so this is what a simple you know a list of messages prompts look like okay here we can pass a list of messages in the form of a conversation history
here I can also go ahead and write I provide AI messages over here and probably go ahead and try it out okay now let's see some more important thing right here the kind of examples that you have seen
11. Detailed System Prompts and Tool Messages
Showing how detailed system messages improve responses, adding metadata to messages, manually creating AI messages, and using tool messages.
is with respect to a system message okay this was just a basic message itself right you just have a oneliner let me see one more example So here I've written system message I'm writing you are a helpful codingassistant.I've given this messages list human message as an input.How do I create a rest API?Right?And now you can also see this specific response.It will go ahead and try to create a rest API.So here you can see all the information.Okay the user is asking all this information is basically can creating a rest API invoid involves defining endpoints that handle this and that all the information is there.Okay.So that basically means we are able to get a good answer.Now till now the system message that we have specified is just a oneliner message.Sometime we want a detailed information provided in the system message so that we give more information to the LLMs.
Right?So what we will do I will show you one more example where we give detailed information detailed info to the LLM through system message.Okay system message.So let's see this example.So this example is also really good.So here now I will say like this.Now see inside this we have provided a system message.I'm saying you are a senior Python developer with expertise in web frameworks.Now more context is basically given here.Before that I've just told that hey you are a helpful coding assistant.We have not specified any specific programming language like Python, Java, you know it can be C, C++, anything as such right?I've just provided a generic information.The answer was also very generic.Okay.But in this particular scenario, you can see that I provided a detailed information.You're assistant senior Python developer with expertise in web frameworks.
Always provide code examples and explain your reasoning.Be concise but thorough with in your explanation.Now I wrote how do I create a rest API?The same thing.Now you see the response.The re response will be much more practical and it will be related to definitely Python.So if you go ahead and see this here you can see start the steps choosing flask install it the code example everything is over here and lot of messages are over here disable debug mode in production add inputvalidation and all right so you can clearly see that if we provide more information inside this system uh message we will be able to get more proper response okay now this is what a simple things is right nowI have also told you that whenever we provide the messages, we can also provide this three important information.One is role, content and metadata.
Role basically identifies the message type whether it is system, user or human.Content represents the actual content of the messages.It can be text, audio and documents.Metadata is some kind like an optional fields.Okay.So let's say that I want to go ahead and define some kind of human message over here.Okay.My my human message with some metadata.So here you can see content is hello name is Alice ID is message 1 2 3.So here you can see we are providing two metadata information one is for identifying for different users and one is uniquely identified for tracing.So this is basically for tracing you know so that we can go ahead and trace it.Now if I go ahead and see the response see if I go ahead and just use model.invoke on this human message you should be able to see the response.
So the user said hello.So I should be in a very friendly way.It'll be able to probably provide the response based on the metadata information also that we specifically have.Okay.Now this is just a specific idea about how you can play with system message, human message.Uh you know you can also have uh AI messages.You we have also spoken about the list of messages that you really want to work on.Right.Right.Let's see one more example.Okay.Now this example is also amazing.So here you can see I have written from langchen messages.I have imported AI message, system message, human message.AI message is that I'd be happy to help you with the question.Okay, create an AI message manually.We have created it.Okay, this is not generated by AI itself but we are creating our own message and we are assigning as label as AI message.
Now I am adding all the information into the conversation history.So say they say you are a helpful assistant.have written as a human input initially we have written can you help me AI message is nothing but I'd be happy to help you with that question human message great what is 2 + 2 now this entire listof conversation can be also understood by the llm and based on this it should also be able to give you the output so here you can see clearly how the output is right first 2 + 2 is fourthat's straightforward but may I should I explain this this so this is a reasoning model that we have specifically used right so That's the reason it is providing a lot of reasoning stuff and all.Now inside this can I also go ahead and see my metadata.So in order to see the metadata so I can write response dot metadata.
Okay or usage metadata.And here you can see that you'll also be able to get the information like uh how much was the input token, how much output token was generated by the LLM and what are the total number of tokens.So that you will be able to see all the information out there.Right?So this is also there.Now we have discussed about all the things.There is only one message that is remaining that is nothing but tool messages.Now already in our previous example we have understood about tools.Tools message is nothing but it's just like an output that is provided by the tools.Right?So whenever an LLM require a help of a tool, it will go ahead and make a tool call and whenever that tool specifically gets executed, it is just going to go ahead and give you the output.
Okay.So finally let's go ahead and talk about tool.Okay.And here I will be taking another example.Right.So here you can see I've used AI message and tool message.In the AI message I've empty content but we are making a tool call.Okay.The name of the tool that we are going to make is get weather.Argument is nothing but location as San Francisco and we have also used id.Weather result whatever we are basically getting we have hardcoded it.Now I'm using this tool message with content is equal to weather result and tool ID.Now see I've asked the question what's the weather in San Francisco then AI message is basically given from here.Okay.And then tool message is nothing but the output uh that we get from here after executing the weather result.So now if I go ahead and execute this and probably go ahead and see the response I should be able to get the output as okay.
Uh uh one more very important thing is that if you see this specific tool message okay so if I go ahead and see my tool message it is nothing but it is coming as a tool message okay andonce this tool message is there we are giving as an in uh input to the model so that is the reason model.invoke invoke of messages when we execute we are getting the response as a message.So I hope you got an idea with respect to different types of messages.You can go ahead and try it out.Explore more about it.You know u since this is the updated version of langchain uh my responsibility is to cover all the specific topics as the updates are basically coming up.Okay.Now uh as we go ahead we'll also be talking about different structured output where we talk about pentic we talk about nested structures we talk about typed deck.
Um so that part uh we will be covering now.
12. Structured Output with Pydantic Models
Using Pydantic BaseModel with field validation and descriptions to force LLM responses into a structured schema via with_structured_output.
So now we are going to discuss about structured output.Till now uh we have already seen messages.We have also got to know about the different type of message prompts like system message, human message, AI message and tool message.And we also saw multiple examples and how to implement it with the help of langen.Now in the structured output, why is structured output actually required?Okay.Now see guys uh we will definitely be using different different LLMs and we want this LLM models to be requested in such a way that so they provide the response in a format matching a given schema.So let's say that hey I am requesting a LLM model to write me an essay on some specific topic and I definitely want the response of that LLM model to follow some structure and that is where I woulddefinitely want some kind of structured output right so this is where we implement or we make the LLM to give a kind of structured output and we do it by using different techniques some of the techniques are like
pidentic we can also use type date we can use data classes and that is what we will be discussing in this particular section okay so over here you can see I have written a very detailed explanation about structuredoutput it says that model can be requested to provide a response in a format matching a given schema is useful for ensuring the output can be easily passed and be used in subsequent processes langchen supports multiple schema typesand methods for enforcing structured output So the first uh technique that we are going to use or first type that we are going to use is something called as pyntentic.Now pyntic model it provides a richest feature set with field validation description and nested structure.So I will show you one example like how we can create a structured output from the LLM specifically for the LM response itself.
Right?So first of all what I will do I will go ahead and import OS along with this what I am actually going to do is that I will also go ahead and the first step is obviously I haveto load my uh lm model right so I'll write from langin dot chat models importit
chat models right then I will write osen environment and here I'm going to specifically write gro_i is equal to os.get get env since I'm actually going to use my gro API key right so I'll write gro API keynow the model that I'm actually going to use is nothing but I will be using this gro model groan uh the model name is nothing but quen and we will be using quen 32 billion parameters model it's areasoning model right so this is the model that I So here you can see cannot import uh name in it chat models.Okay let's see what is the issue.So here you can see there is something called as init chat model.Uh we had made a different import but it's okay.We have actually loaded our LLM model.Now let me quickly show you that how with the help of pyentic you will be able to generate a structured output.
The best part about pyntic is that it also has field validation descriptions and also nested structure.So first of all in order to use pyntic we need to import one library which is called as from pidentic import base models.Okay, comma field.So this field is uh what we are going to specifically use in order to use field validation.Now here let's say I want my lln to give the output in a some kind of structured schema.Okay.Now what schema it will basically follow.So what I will do for that I will create let's say a class called as movie.And inside this movie we will inherit with this specific base model.Okay.The base model that we have imported over here.And if you see that it is nothing but it is a base class for creating pyic models.Right.and pying model has a very important property that it provides you field validation description and it also provides you nested structure.
Now let's say my structure output from the LLM needs to have different fields.Okay.So one of the field is nothing but title.So let's say this title should be of only type string.Okay.So here we are writing colon string.Okay.And this will be of type field.And here I can go ahead and provide some description saying that this title is nothing but it is the title of the movie.Okay.Now see my LLM needs to definitely generate some kind of output and it will generate based on whatever fields I'm actually creating over here.And we are going to make sure that this title should only be having string value over here.If it has a numerical value then it'll give us a error because pientic uh will do this kind of field validation also.Okay.the pyntic model.Now, similarly, my second field will be nothing but year.
Let's say my year is there and it will be of int type and I will go ahead and write field and here again this will be my description and I will say hey this is the year of thisyear.This year the movie was released.Okay, the movie was released.And then coming to the third important let's say that I want to also create one more field inside this.It is nothing but director string.And again I can basically say this is a field.Now see you understand what this field is right.If you go ahead and uh just hover over it and if you see what exactly field is this is basically providing you lot of different different parameters that you can set which represents this particular uh variable right theyear.Okay.So here I've just given that this particular field is nothing but this is the year the movie was released.
This information will be very much important for the LLM right because once we are giving this kind of descriptions we can also set some other parameters like uh you know we can set a liar this will be veryvery handy because it will help the LLM to know in which field it needs to place the output that it is coming from the LLM itself when we are displaying that in a structured output.Okay.So this is my uh director field.In the director field, I will also go ahead and write some kind of description so that it gives some idea to my LLM saying that okay, the director of the movie, director of the movie.Okay.Then I have my ratings.This is also one field that I definitely want.My rating can be a float value.Okay.It needs to be a float value because it can have different float value itself.
And then I have my description.Inside my description, I will go ahead and say the movies
ratings out of 10.Okay, out of 10.Now see this is the output that my LLM should be generating it.So that's the reason I've created a class called as movie and it is inheriting base model.Inheriting base model basically means it is it is just going to go ahead and if you just hover towards this base model it is it is nothing but it is a base class for creating pyic models.And one important thing is that this pyantic model has real validation description and all.Okay.Now let me go ahead and execute this.Okay.Now if I want my model to generate the structured output.So what I will do I will just go ahead and write model with structure output and we will give like what structure output it needs to give of this particular movie class.Okay.So this movie class is over here and here I will go ahead and define model with structure.
Okay.Model with structure.So this is what uh my uh important model way is you know now see as soon as I go ahead and execute this.Okay, I go ahead and execute this and if you go ahead and just display it what is this model with structure, it shows that it is a runnable binding.It has uh information from Chad Gro model and then it also has this py tool parser.Okay, now this is really important because now I'm going to display how the output will get displayed whenever we ask any question to this particular model with structure.So for that I will go ahead and write model with structure dot invoke and here I will go ahead and ask a question provide details.Let's say I want a details about the movie movie inception.So if I go ahead and use model invokework if you remember model is nothing but it is not having any schema attached right.
So here if you are attaching any schema or any structure output it is nothing but model with structure.So if I just go ahead and write model.invoke and I say hey provide me the details of the movie inception.So here you can see this is how is the default output we will get.Okay once we execute this see this is my AI message.Okay I need to provide a detail about the movieception.The inception probably has to do a concept of planting an idea.So it is probably providing all the details but I don't want all these details.I want the details in this structure output.I want it in the form of title, year, director, rating.Right?So I should be able to get that.Now if I go ahead and use this model with output dot invoke and now I want to go ahead and create I'm asking the same question.
See over here I'm asking the same question response.Now if I go ahead and display the response, you should be able to see that I will get in this structured output.Right?So here you can see title is nothing but inception.Here it got released on 2010.director is nothing but Christopher Nolan rating is 8.8 eight right so sometimes now this information I can use it anywhere right this is a vague information it has all the information probably from the internet data that it hasbeen trained with but if I just want some kind of structured output which is important for me because if I'm able to generate this output I will be able to use this in the same structured manner for someother purpose right so our main aim over here is that where models can be requested to provide the respon in a format matching a given schema and here my given schema is basically following this.
Now there is very much one more very important thing.Okay.Now see I'm getting the output over here as inception which is in the form of string integer Christopher Ner and rating.Let's say one very important property about pyic is that if if this title has some integer value will have some integer value then it is definitely going to give us an error and that is what this field validationis supported in pentic.Okay.Because of this field validation you always need to have values of this title as a string only.For this year you should have it in the form of integer.If in this director field you need to always have a string and in this rating you can either have integer or a floating value.If you have some other values it is going to give you an error.Okay.So that is the most important property about pyntic with respect to field validation.
Okay.So now I hope you got an idea uh about how does a pyic basically work.
13. Raw Output and Nested Pydantic Structures
Demonstrating include_raw to get raw and parsed responses together, and building nested structures with lists of actor models inside movie details.
Okay.Now what I will do I can also go ahead and create a message output.Okay, message output alongside alongside pared structure.Okay, parse structure.So let's see this example.Now you may be thinking what exactly this is.Okay, so here you'll be able to see that I will just go ahead and do the same thing.If you can see over here from pyentic import base model field I've created a class movie here this is just like an optional field okay and then I have put the description all the information over here and modelwith structure I have written model do with structure output movie and I have written include raw is equal to true see one of the feature include raw is equal to true now what this actually does you'll try tounderstand it okay what this feature will actually do so now if I just go ahead and execute this I'll create some more code and see the response model with structure.inote input will provide a detail about the movie Inception
and remember we have kept this parameter as include to raw is equal to true.Now once we get includes raw is equal to true by default how the raw message will come that is also displayed over here right the initial raw message this raw message like how it is basically getting displayed thatwill also get displayed over here and this is my parsed message right based on the structure so I can also display that also and there is also option by including this particular parameter okay now along with this thereis also one more important thing which is supported in pyntic which is called as nested structure.Okay.Now let's see or let's understand what exactly is nested structure.Let's say I am importing pentic and I have this class actor.Okay.So inside the actor you have two variables name and role.Obviously every actor will have a name and role and it is of type string.
Okay.Now inside my movie right there may be multiple actors right.So what I can do I can use this direct class inside this.So here you can see I have written class movie details base model title this is the movie title year the movie release date cast will be the list of actor see this is the same actor over here andhere I can have list of actors so that is the reason we are saying next structure okay John Jonner's list of strings it can also be a list of jonors right and budget is nothing but a floating pointand here you can see that I've created uh by default none okay otherwise we specy specifically provide some kind of description budget in million USD.Okay.Now this way we are using a nested structure that basically means inside the movie details we are using this particular actor.
Okay.Now if I go ahead and use the same thing and ask the same question model with structure output and this time I have written movie details right over here.Now if I just go ahead and ask the same question from this particular structure output saying that hey model with structure.invoke Invoke provide the details about the movie Inception.I should be getting the response in this specific way and in the cast I will be getting a list of actors.In genres I'll be getting a list of genres.Right?So here you can see I will just go ahead and display this.This is amazing.See in title I got assumption year 201 cast actor name Leonardo Darpo role Dom Cobb.Right.Then the next actor is nothing but Joseph Levit role is Arthur.actor name.So here you can see multiple actors are there.Jon also you can see the list of this is there science fiction action and budget is 160.0 um um 160.0 zero based on the millions uh budget in millions USD right so 160 million uh dollars were actually spent
in this so I hope you got a specific idea about paidentic the main aim is that you're providing field validation and you're actually making the model to provide the response in a format that matches your given schema basedon the schema that you have actually designed so I hope you have understood about uh pentic now In uh as we go ahead we'll also be discussing about one more type which is called as type deck and thereis also one more type which is called as data class.Okay.So we will see both of them as we go ahead.
14. Structured Output with TypedDict
Using TypedDict with Annotated descriptions as a simpler alternative to Pydantic when runtime validation is not needed, plus model profile inspection.
So guys now we are going to continue the discussion for the structured output.Uh we have already covered how we can make an LLM to you know provide a response in a format matching a given schema using pentic model.Uh now the same thing we will try to do it with the help of typed dick.Now typed dick provides a simple alternative using python built-in typing idle when you don't need runtime validation.So whenever we are trying to uh use typed deck there runtime validation is not there as how we had in pentic models.Okay.So now we'll try to do the same thing uh like how an LLM can provide a response in a specific schema wherein runtime validation is not required.Let's say if I'm actually creating title and we are saying that it is of type string it if integer is also getting displayed in the output it is fine because there we do not focus much on runtime validation.
Okay.So first of all uh to do this I will go ahead and use from typing extension import type deck.Okay.So we are going to use typed dict and along with this I'm also going to use annotated.So this two uh are the important libraries that I'm actually going to use.If you see type dict it is a simple type name ses at runtime.It is equivalent to a plain dictionary.It is just going to create a simple dictionary in short.Right?So that is the reason we don't need runtime validation over here.Now I will try to use the same kind of data.Okay.So here I will say hey let's create a class which is called as a movie.Okay.So now I will just go ahead and create it.Now here you can see I've created a movie dictionary and this is this time inheriting type dict instead of pentic.
Right?If we inherit pentic then this all will have a runtime validation but we right now don't require it.Uh we are saying that hey we are going to probably go ahead and inherit with uh pent type dict itself.Okay.And here first of all my first field is title and we are annotating it saying that it is a string and the description is this.These are some optional fields which we can keep it as empty.Okay.So the next field over here year it will be of type.We are annotating it as int.And here you can see the description is mentioned.Similarly I have director and ratings.Okay.So uh this is how we actually uh create this particular structure.So now once I have created this schema now it's time that I will call my model and I'll use with structure output and and I apply this particular schema that is movie dictionary okay which we have created it
over here and I will just go ahead and say this is my model with type dick structure okay with type dict with type dict okay I'll just go ahead and write this then the next step will be thatI will use this model with type dict dot invoke and I'll say please provide the details of the movie Avengers let's say this time I'm going to take the Avengers movie okay and then if I go ahead andsee the response okay and then you will be able to see the response over here so here you can see director Jos widen rating a title Avengers year 2012.Okay.So now you can see the response over here.Now what I will do I will also go ahead and create a next structure and this time instead of using base model I will just directly go ahead and use my type dict.
Let's say I will go ahead and use my type dict over here.I'll use my type dict over here.So we can also go ahead and imple uh implement the nested structure but and over here the validation will not be compulsory.Right?uh let's say if the directory is having string if I give an integer then also it is fine so here the input validation will not happen like how it happens in pentic so if I go ahead and executethis so here you can see I'm able to see please provide me the details about uh the movie inception so 16 millions 160 million all the information is there let's say I want to go ahead and try outfor Avengers so you should be able to even see the response okay so this was a brief idea about how we can quickly use the type deck all we are doing is that whatever schema we are actually creating
we are inheriting that specific module right in over here we are using typed deck in the previous stage we used base model which was specifically for pentic itself okay and this gives you a clear idea like how wecan actually go ahead and use uh pentic over here and clearly and how we are able to see the output now along with this there is also a very important property which is called as profile so if Iwrite model with structure dot profile or instead of writing model with structure I'll use model type dick.profile and if I just go ahead and display it here you can see runnable se sequence has no attribute profile okay sothis is what is the error that we are getting now whenever we try to create some kind of structured output there we should not be able to see the profile but if I go ahead and write model.profile profile
which was my base model.Here you can see that all the necessary information like how many maximum input tokens are there?Maximum output tokens.This specific model can actually do image input does it suppose image right the answer is false audio inputs false video input false audio input false reasoning output true tool calling true.So these are the information which talks about like what all things the model is basically supporting and we have used quen 3 model over here.So, Quen 3 model actually specifically has all this particular uh supporting tools or supporting features which you can actually understand about the model also.Right.So, now we have understood about typed date.We have understood about pyic.Now the next thing that we need to understand about one more uh way like how we can go ahead and apply this kind of schema that is called as data classes.
15. Structured Output with Dataclasses
Comparing structured output approaches by using Python dataclasses as response format in create_agent alongside Pydantic and TypedDict examples.
Okay.So now let's go ahead and discuss about this data classes.So now let's go ahead and discuss about data classes and how we can actually go ahead and how our LLM can create a structured output based on a specific schema with the help of data classes.We'll be discussing about that.Now see data class has already been there from Python 3.7 version.Okay.So a data class is a class typically containing mainly data although there aren't really any uh restriction like data validation nothing as such input data validation but you can create it by directly using this particular decorator.So let's do one thing quickly.Uh let's take one example.First of all, we'll start with Pentic.Okay, because we have already know about Pentic now.Okay.And here we are using GPT5 uh for creating the agent.So what I will do?I will just go ahead and write import OS uh and I'll say OS.
Environ okay in run.And this time I'm just going to go ahead and use my OpenAI API key.Open AI API key.I just I'm using this just to show you how we can actually go ahead and create our agents also.Okay.Uh open AI API key.Perfect.Now this is done.Okay.And here you can see that uh I have imported pentic import base model and you know uh already in this series we have covered how to create an agent how to create a simple agent.So from langin.tagents we are importing create agent.So first of all I have this particular schema contact info.We are inheriting base model.Whenever we inherit a base model of pentic that basically means we have some kind of input validation.Name should always be string.Email should always be string.Phone should always be string.Okay.Then we are creating this agent over here.
So here you can see create agent uh and the response format.Okay.This time I'm not using this with structured output.Instead what I'm actually doing I'm directly showing you how you can integrate with the agent itself.So in create agent model is equal to GPT5.We are using this model and we are writing response format is nothing but contact info this specific class.Okay.So whatever agent this is basically there we are going to always get the output in this particular schema.Okay.So here we are written agent in invoke message role with user contact extract contact from John doing john at the rate example.com with this particular information.So here this is my entire content.Okay.And I have written extract contact info from this particular information and this information is going to my agent.Now agent what it is basically going to do based on this particular format.
It is going to take the name over here, email over here, phone number over here, right?And then we can go ahead and print the result structured response whatever response we have.Right?So let me do one thing.Let me first of all just directly go ahead and display the result.Okay.So my result is nothing but over here.You'll be able to see quickly after I use this particular model.So here you can see message human message extract contact info from this AI message is over here and structured response is over here.So if I just go ahead and write result of structured
response.Okay.So here you'll be able to see this is my contact info.The name is John Doe.Email is johntheample.com and this is there right?So based on this specific schema we are able to get this that is the useful property about pyic over here.Validation is applied on every field.Okay.Now similarly if I want to do it type dect type duct is very simple which we have already discussed.So this is nothing but with the help of type dict because I really want to make that comparison.So from typing extension import type dict then we are using from langchen.tag agents create agent.This is my schema.This time we are inheriting type deck.Over here the data input validation will not get applied but definitely we have provided a schema wherein we are saying the name should be string and all.So here you can see create agent.
I will remove the tools.I don't want the tools right now.So create agent with model GP5 response format is contact info.Now I have written contract extract contact info from this information and I will just go ahead and print my structured response.So here should also be able to see that I'm able to get the output which looks something like this in the form of a dictionary pair right like it will be in the form of a dictionary.So that also you will be able to see it.Uh so here you can see name John do email example and all.Now I will show you how with the help of data class you can do the same thing.Okay.So now I will show you with the help of data class.So with the help of these are just different ways you can use any one of them.
So first of all what I'll do I will go ahead and import from data classes.import data class.Okay.Then I will go ahead and import from langchain agents.Agents import
create agent.Okay.And then I will write add the rate data class.I will create the class as contact info whatever class I have.So this will be my contact info class.And how we define a variables inside my data class.So it will be nothing like this.We just specify uh the information over here.Right?So this is my data class.So let me write it properly because of the validation.So here you can see that I've used name is equal to steer str.name of the person, email str, phone number str okay now the next thing is that I will just go ahead and use my create my agent here you can also call tools if you have any kind of toolsI don't have any tools so I'll remove this but the response format will be in the form of contact info and finally I will just go ahead and display the response like how we display the result itself right
so with the help of data class also you can actually do the same thing okay now this is really important and I hope uh you got a very good understanding that how you can actually work with data classyou got work with structured output uh you work with type dig you work with pyic and here the in the data class we have discussed about all the three examples right from type dick to data classes and allso yeah uh I hope you have understood this particular section now uh the next section that uh we will be discussing about is like streaming we'll be discussing about uh sorry we have discussed about streaming uh we'll be
16. Middleware Concept and Built-in Middlewares
Explaining middleware using an airport security analogy, covering hooks/trigger points and surveying built-in middlewares like summarization and human-in-the-loop.
discussing about short-term memory and other things right so let's continue the discussion so guys now we are going to discuss about middleware now this specific topic is a very meaningful topic that has been included in languin and ithas some amazing functionalities uh what we'll do in this section is that we'll talk talk about middleware uh how you can implement middleware by different different uh inbuilt functionalities that are available in lang uh we'll take some gooduse cases in making you understand.So first of all we'll try to understand the definition.Okay.So let's say over here the definition is written.Middleware provides a way to uh more tightly control what happens inside the agent.Middleware is useful for the following.It tracks agent behavior with logging analytics and debugging.Transforming prompts tool selection output formatting.adding retries, fallbacks, early termination logic, apply rate limits, guardrail and PII detection.
Now just by seeing this definition uh I know many of you will be specifically confused.So it is always better that I try to show you with a very good example.Okay.So let's consider one example over here.Let's consider an example wherein we take something like airport security.Okay.So I hope everybody may have been to airports.Okay.So in the airport security if you go ahead and see that right.So in the airport security when you enter the airport right when you enter the airport you let's say you are the passenger.So let's say if this is your boarding gate or this is your flight right the boarding gate is somewhere on 18 number right now to go to this boarding gate you have to when you're entering the airport youhave to cross to various stages right so you need to cross through security check so let's say there is a security check over here then after crossing the security check you may have to probably go to the immigration
After going through the immigration, you need to go ahead and board the flights and then finally you go to this particular gate number where you catch your flight.Right?Now in every of this step in the security check what happens you know we go ahead and apply or over here what will happen in the security check they will probably go ahead and see your luggage what isthere in the luggage and all like you should not be carrying any batteries that kind of check will happen so this I can basically say this as my middleware one okay so I'm going to probably go ahead andimplement one middleware over here okay let me write it much more properly so that you should be able to understand right.So here what I can do I can go ahead and develop my middleware one over here and this middleware one functionality is that it will go ahead and do all the necessary check that is required so that with
respect to luggage with respect to other things.Now the second thing over here in the immigration counter right in the immigration counter what immigration people will do basically uh they check your passport whether your passport valid date is there or not each and everything.So that kind of checks can basically happen in my middleware too right and before boarding you know here we will probably go the the people will go ahead and see your boarding pass right and see whether the boardingpass is right or not.So here we can go ahead and develop our middleware three.Now just by seeing this example before any important let's consider that this is my agent one this is my agent two this is my agent three before the agents we are doing something we are doing we it canbe a normal check it can be logging it can be exceptional handling it can be model calling right it can be anything as such so that's the reason we have given this specific definition here let's say it provides
a way to tightly control what happens inside the agent now here We are considering this as a agent and within this particular agent we can do multiple things right.We can create middleware 1, middleware 2, middleware 3, right?And here we can track agent behavior with logging analytics, debugging, transforming prompts tool selections.We can do multiple things in short of or different kind of functionalities over here.Right?So uh this is what it is.See this can be considered as a very good example.So before we have let's consider this is my agent inside this agent I have my model I have my tools okay and this is nothing but this is a react agent right so model will when we once wemake a request to the model the model will see whether that request needs to be passed to the tool then the tool will execute it give it give the context back and finally we get the result right with
the help of middleware now my agent will look something like this so agent with middleware so So in agent with middleware here we will be able to see that there will be different different triggers.Okay.So clearly you can see over here what what is the best thing that is available this middleware right?It exposes hooks.We basically say it as hooks.Okay hooks means what?Hooks means trigger points.Before the agent we can add something.Before the model we can add something.This uh tools calls you can see you can add something.After the model call we can add something.After the agent we can add something.It can be logging.It can be summarization.It can be multiple things in sure.So here in short we are adding some kind of hooks.Okay.And we are adding these hooks so that we can do something over here.
Right now the best way is that uh we will see first of all some built-in built-in middlewares.Okay that is available.So we'll see some built-in middlewares.One of the middleware which is very commonly used is something called a summarization middleware.Now this summarization middleware is a uh kind of a middleware that we can use in the agent and it task is only to summarize.So let's say if this is my LLM model or this is my agent.This is my agent and let's say this agent is basically connected to a tool.Okay.And this tool is return connected.And here we get the output.Now here you can see that what this summarization will do.Okay.What this summarization will be specifically doing is that we add this middleware over here.We add this summarization middleware over here.So whenever we give any input and once we generate the output let's say after some number of messages after some number of input and output messages you know that this messages list will keep on growing.
So if I apply this summarization middleware what it is going to do it is just going to summarize this entire list of messages after it reaches some some number let's say after it reaches some count after after 10messages I want this to summarize right all these 10 messages I want to summarize then what we can do we can apply the summarization middle layer within the agent and it task will be that once it reaches 10when once the count of the message reaches reaches 10.We are just going to quickly summarize the message and this summarization of the message will be taken care by the LLM.Right?So this kind of middleware we can add it over here.Okay.Similarly there are other middleware.One of the middleware example is human in the loop feedback.I can basically say human in the feedback.So this summarization also this middleware also I can add.
There is a model tool calling.There is one more uh very good uh built-in middleware and there are list of middlewares which you can basically use it like model call limit.Okay, model call limit basically means uh what limit the number of models to prevent uh you know excessive cost.So there there are many okay I'll just show you the I'll just show you the documentation.So here you can see I have summarization middle where it automatically summarizes conversation history when approaching token limits human in the loop.It saves pause the execution for human approval of tool calls.Then you have model call limits limit the number of model calls to prevent excessive cost.Then you have tool call limit control tool execution by limiting call counts.You have model fallback to-do list LLM tool selector tool retry.So many different options are there.Okay.
So we I will now go ahead and show you that how you can go ahead and apply this middleware itself.
17. Summarization Middleware with Message Trigger
Implementing the summarization middleware in an agent with a message-count trigger, using threads and checkpoints to verify automatic conversation summarization.
Right?So first of all what I will do I will go ahead and quickly open my Jupyter notebook.So this is my uh some middleware over here.You can see I will close this.Okay.This is my middleware code.So first of all we go ahead and import or we go ahead and load our environment variable with open AI API key.Okay.Now the next step is that we will go ahead and write our code.Now writing our code is very simple over here.Okay.Here first of all we will go ahead with our summarization summarization middleware.Okay.Summarization middleware.Again it is not possible to cover all the different types of middleware that is available over here.But I'll try my level best to cover some very important so that you can independently do all the things uh you know after seeing some examples.
Okay, because at the end of the day it's up to you for what kind of use cases you are specifically using this.Okay, so let's go ahead with the summarization.Now summarization middleware I will also go ahead and probably provide you some definition over here.Okay, so here you can see it automatically summarizes.So let me see I will try to provide you a material which will be very meaningful and you should be able to learn read it later on.So summarization middleware is nothing but it automatically summarizes conversation history when approaching token limits preserving recent messages while compressing the older context.Okay.So what it does is that it compresses the older context and it just use the recent messages whenever the token limit is reached.Summarization is useful for the following longunning conversation.So specifically in a chatbot when you have a longunning conversation it is always good that we try to summarize the previous context multi-turn dialogues with extensive history application while preserving full conversation context matters.
Okay.So now let me quickly go ahead and show you one example that how you can go ahead and implement this.Okay.So first of all what I'll do and uh we can use different different triggers also.Okay.I will show you in summarization there are multiple triggers which you can actually use.Uh there is a token trigger there is uh uh messages trigger and all.Okay.So first of all what I will do I will go ahead and show you how we can go ahead and create an agent.So from langin uh dot agents I'm going to go ahead and import create agent.Okay.So this is the first one.Then from langchain dot agents uh dot middleware I'm going to go ahead and import summarization middleware.Okay.Then from langchen dot uh we are also going to go ahead and use checkpoint.Okay.
The checkpoint is required so that I go ahead and apply some memory also.So I will go ahead and say memory.Okay.from langin dot checkpoint dotmemory import inmemory so I'm going to also go ahead and apply in memory so that I can go ahead and apply checkpoints uh within my chat bots right then from langchin core dot messages I'mgoing to use uh human message and then I'm also going to use system message system message.Okay.So these are the basic libraries uh that I'm going to use.The first example that we are going to do is that message based summarization.Okay.Message based summarization.So I'll go ahead and create my agent.My agent is equal to create agent.And inside say this create agent.First of all I'll go ahead and use my model.Let's say the model that I use is GPT 40 mini.
Okay, 40 mini.So this is the model that we are going to use.Uh tools, you can go ahead and define your tools but right now I did not define any tools as such.So I'm just going to go ahead and keep like this.Then we going to use checkpointter.This is for my checkpointing uh the whatever conversation history is there.I'm trying to save it within my local hardware like in my hard disk itself.Okay.Now to give the middleware as an option inside this agent.See our main aim is that I want to add a middleware inside this agent.Right?So here you can see I've given model information.I've given checkpoint.So here you can also go ahead and give your summarization uh sorry middleware as a parameter.So inside this middleware you can give a list of middleware like what all middleares you really want to apply.
So now here we are applying the summarization middleware within our agent.So inside this particular agent we are applying summarization.But when do the summarization actually happen?Right?That is the major question.Right?So inside the summarization, we have an option to give multiple parameters.First of all, what LLM model we are going to use in order to do the summarization.So let's say I want to go ahead and it's always a better idea that we use uh models that cost less for the summarization because uh whenever the message expands uh up to a certain count we are againgoing to do this uh summarization in short right so it is always good that you try to use a model LLM model which has lesser cost you know with respect to tokens then I want this summarization to triggerright so there will be another parameter which is called as trigger And inside this trigger what we are going to do we are going to put our condition like when I want the summarization to happen.
So here I will say when my messages length is becoming 10 at least okay my input output all the messages that is which which is getting generated uh whenever it becomes 10 usually whenever you create a chatbot thisnumber is a bigger number right but just to show you in this use case we are going to set it as 10.Okay, then I'm also going to say that at this point you go ahead and trigger it.But when you trigger it, you summarize the previous contest and keep the recent top four messages.Okay, recent top four messages like that, right?So that we get the context and we go ahead and apply it.So here what you can do this is just one of the summarization which I have actually applied.Now you can keep on adding any number of summarization, any number of middlewares, right?
You just need to put comma over here.Then you go ahead and define your next some next middleware after this.Right?Any number of middleares you can actually go ahead and add it.Okay.So now this is a basic agent that I've actually created wherein I have added a middleware of summarization middleware.Okay.So now once I execute this cell my agent is ready.Okay.Now all I have to do is that in order to test this out right whether this summarization is happening or not let's check it out how we can actually do it.Okay.So first of all before I invoke anything with this particular agent I want to go ahead and create a thread.Okay.So I will go ahead and run with a thread ID.And for this I will go ahead and create my config.Inside my config I'm going to go ahead and create my variable called as configurable.
Okay.And then I'm going to go ahead and create my thread ID.This will actually uniquely identify a user.Okay.So here I will say test one.So this is my unique user.Let's say this particular thread is my unique user.And I'm going to go ahead and do this.Okay.Now let's create some kind of test data.Okay.So let's say these are my convers.These are my human questions I need to ask the agent to this particular agent like what is 2 + 2 what is 10 * 5 what is 10 100 divid by 4 what is 15 - 7 and thenmy llm will also keep on my agent will keep on generating the answer so here what I will do I will say for Q in questions okay and I will go ahead and generate my response my response willbe using this agent invoke agent invoke and here we are going to go ahead and set this in the form of a messages because we need to provide in the form of a message and here I'm going to
go ahead and use my human message.My human message is nothing but whatever questions I have which I'm reading in this Q variable I will be giving it over here.Right?And then I will have my config variable.Clear?Then what I'm going to do, I'm going to print whatever response I'm actually going to get.And along with that, I'm also going to print the length of the response messages.Okay, the reason why I'm printing the length of the response messages to show you because here we have set up that whenever the message size increases more than 10, the summarization should happen.And when the summarization happens, this message length will get reduced.Okay.So here you can see I'm testing all these messages.So first of all first question will go what is 2+2 and uh uh you know my llm my agent will uh provide me the answer 2 + 2 is four.
Then we are going to print that entire response and then we also going to see the length of the message response.Okay.And when this length of the message response increases more than 10 automatically the summarization will happen with this particular LLM model.So let's go ahead and try this out.Okay.So here you can see message message 2 message 4 message 6 message 8 10.Now automatically my summarization should happen over here.See now it has gone message 6.And here is the content.Here is the summary of the conversation to date.Human asked several arithmetic question.What is 2 + 2?A responded 2 + 2= 4.Uh what is 10 * 5?10 mult* 5= 50.So here the summarization has happened.Why it has happened over here?because when my message length got triggered to 10 right triggered to 10 then it is going to go ahead and do the entire summarization and that's the very important property of middleware right I hope you are able to
understand the power of middleware right let's see one more example see one of the trigger is through this way right where we have what we have done is that here I've applied this trigger based on the message lengthright 10 now there is also different way.Uh one of the way is basically based on token size, right?So let's go ahead and do based on token size.This was based on the length of the message.Now based on token size also you can actually do it.
18. Summarization Triggers: Tokens and Fraction
Configuring summarization middleware with token-based and context-fraction-based triggers, observing compression when thresholds are exceeded.
Now let's go ahead and do it.Now here what I'm actually going to do, I will first of all import all the libraries.So these are all my libraries that I'm actually going to import.From langin aents import uh create agent.Then from langin.tagents.middleware import summarization middleware then we also going to create tools uh over here we used human message in memory and then this is the tool that we have created let's say that this is my search hotel functionality andhere I have hardcoded some things okay hotels in this and these are all the possible hotels that are available let's consider that this is probably returned from some API okay now what I will do I will go aheadand create my agent and this time my trigger will be token count okay token count So uh token count basically means how many tokens has been generated by the model.
Right?So here I'm again going to use agent create agent.Okay.And then we are going to go ahead and use model is equal to GPT 40 mini.Okay.And then I'm going to go ahead and use my tools.My tools will be nothing but let's consider that I'm going to use search hotels over here.my checkpointer.
Let's see whether I've imported checkpointer or not.Checkpointer is over here is equal to inmemory saver.And then I'm going to go ahead and apply my middleware again.And this time the middleware that I'm going to apply is nothing but summarization middleware.And here I'm going to give my parameters.Let's say the first parameter is my model which is nothing but GPT 40 mini.This time my trigger will be not based on messages but based on tokens.So now I'm going to specify tokens and token length I'll keep it to 550.Let's say that if it increases more than 550 then what I'm actually going to do the summarization will happen.And when the summarization is basically happening, we are going to go ahead and keep the recent 200 tokens.Okay.So recent 200 tokens.These are the parameters that is available out there, right?
And inbuilt parameters, right?So this is done.This is my summarization that is basically going to get applied.Let's see.Did I miss out anything over here?This should be trigger is equal to.Okay, perfect.Now this is my agent that has got created.Now what I will do I will go ahead and create my config.Okay config will be nothing but this config so that we apply for a specific user and uh just to display or print how many tokens has been generated.I will create this function called as count tokens.Total character is equal to some length of whatever content is there.Right?That length and we are saying that we are considering okay four characters is equal to one token.Okay, four character is equal to one token.So this is what is basically happening.Okay, so now I'm getting an error.
Let's see.Unable to find GBD 40.I've written 40.It should be 4 ohm mini.4 mini.It's okay.Uh please specify model directly.Okay.GTP I have written it over here.It should be GPT.GPD.Okay.Now done.This is done.Okay.Now we are going to go ahead and run it.Okay.And we are going to run this test for the so here you can see I have created cities like Paris, London, Tokyo, New York, Dubai and Singapore.And this is my question.Find hotels in this specific city.Right?And we are doing agent.invoke.Then we are counting the total number of tokens from this response dossage and I'm printing both these things.Now here you can see one very important thing is that when the token size increases 550 more than 550 then the summarization will happen right so now let's go ahead and execute this this is good okay you'll be
able to see the response so here 149 tokens is there four messages okay now this will increase 302 then 456 then when see it increases to 550 so see now from 450 56 it has become 396 that basicallymeans uh over here after this 550 had expanded.So we are able to do the summarization.So after 396 again it went to 232 that basically means summarization has happened here also.See here is a summary here is a summary and here also summary right.So the summary is basically happening over here right and based on this you are basically creating the response.Okay including the grand hotels all this information.So summarization is specifically happening once your 550 tok to tokens is getting over.Okay.Now this is one more way and one more way I want to go ahead with uh you know which is basically called as based on fraction.
Okay.Now what is based on fraction?How based on fraction it is going to apply.Okay.Here this time I'll copy and paste some code and you you can just go ahead and see to it.Okay.So here you can see I have my search totals.This time the trigger will be based on fraction not on token and fraction I have given 0.005005 005 0005 this is this fraction is based on the context of the LLM model right so if the LLM model isable to accommodate 160k tokens right uh if I give the fraction as 0.5 that basically means 0.5 of six of that many number of tokens is equal to 640 tokens that is what I've given as an example okaywe can also convert that so it is based on different different LLM context size here we are going to use fraction okay so fraction is 0005 that basically means 0.5% 02 that is nothing but 2%.
U and here again you can see I'm counting the count tokens everything is same and here we are using config and here you can also go ahead and see the fraction so whenever the fra this fraction increases 0.5then we are good to go see 9 here 133 tokens.15
21 whenever it reaches 0 five okay 5%.You can see if it does not reaches 0.5 that basically means summarization.So here it has increased.So here you can see summary of the conversation it has increased from here to and uh what we have done is that here the summary has been created.Right?So that basically means that percentage of the token has got uh the fraction has got increased right.So this was just about summarization and three types we have learned.One is based on token size, one is based on u you know the number of messages and all right and uh an amazing uh summarization technique and if you go ahead and see this is the summarization over hereyou can see some examples but I I have probably given you a very good example and there are also other built-in uh middleware now you can use any of them like tool call limit you know how to apply
it so inside the middleware you go ahead and apply it like this right and uh let's say you want to probably go ahead and apply model fall back right so model fall back basically means from one model ifsome model is not there you can fall back to the other model right let's say if this API cost or API key is not working then it will fall back to the other model right so what I willshow you is that in the next uh section I will show you how you can also go ahead and apply human in the loop a very good example because human feedback is always required right whenever a task isbasically happening in the agent and that is what we are basically going to go ahead and discuss but I hope you got a clear idea about summarization middleware.
19. Human-in-the-Loop Middleware and Interrupts
Explaining why critical tasks need human approval, building an email agent with interrupt_on for send_email_tool, and handling interrupts with Command.
So now we are going to continue a discussion with respect to middleware and uh we are going to discuss one more type which is called as human in the loop.Okay.And this is a very important uh functionality in terms of middleware.So here uh what this does is that it pauses agent execution for human approval, editing or rejection of a tool call before they execute.Human in the loop is useful for the following.High stakes operation require human approval like database rights, financial transaction, compliance workflows where human oversight is mandatory.Longunning conversation where human feedback guides the agent.Okay.Now let me just open my scribble notebook and let me talk more about it.Let's say that I have a specific agent and my human in the loop is actually required.Let's say this agent uh does some kind of task.Okay.And whenever we talk about agent these are basically autonomous agent autonomous agent when we say autonomous agent that basically means without much human intervention it'll be able to do some specific task let's say this agent actually does a
work and uh it is a critical work let's say with respect to financial transaction okay financial transaction now when I say financial transaction let's say this agent helps me to buy stocks Okay.Now let's say and see this is definitely a very critical task.I hope you agree with this.This is a critical task.We cannot just directly uh we cannot uh you know completely be dependent on the agent to do this specific task.Some kind of human intervention is definitely required.Let's say for the next day the agent is going to probably go ahead and buy a stock and uh you know automatically goes and does some kind of mistake.So there may be a huge loss of finance in this side.So we cannot be completely dependent on the autonomous agent.What we can actually do is that we can add a human over here, right?
And we can make sure that whenever an agent takes any decision in this kind of critical task, first of all, it will go ahead and request this human to provide a confirmation, right?And that is the reason we say human in the loop, right?We always asking feedbacks to the human being because at the end of the day uh unless until this feedback is not given to the agent this kind of task will not get completed right and this is really importantbecause for any kind of critical task we need to have human intervention intervention because there may be mistakes that may that agent can make that an LLM can specifically make right so now we are going to understand howwe can actually go ahead and implement this kind of middleware.Okay.So here you can see I have I'm I'm actually working in the same notebook.
Okay.What I will do is that I will go ahead and import some of the libraries.The first library is that with respect to create agent.The second library I'm going to import is from langen.agents.m middleware import human in the loop middleware.Before we just using summarization middleware right then we are using checkpoint dotmemory in memory.Right now let's say that I want to do a specific task which needs to be done which needs to be intervened by the human being again and again.Basically my agent should go ahead and ask continuous feedback you know with respect to any task that it does right now what I will do I will go ahead and create two important function let's say one of myagent work is basically to send emails okay so here you can see that I have two different functionalities one is read email here we give the email id email content for ID this one is there where we are
reading the email then second is send email tool okay So this basically sends a email right here.I know I've just written some kind of dummy information saying that email send to recipient with subject this subject.Okay, this is what is my basic thing over here.Again, if you really want to implement a end toend email thing, you need to use SMTP server and based on that you can actually do it.But the core idea over here is that I just want to show you to do this particular task, I want my agent to be always intervened by human beings.Okay.So these are the two functionalities that I have like kind of a tool.Now what I will do I will go ahead and create my agent.My agent will be nothing but create agent.Here the first thing that I'm going to use is model.
So model I'll write GBD40.Okay.The second parameter that I'm actually going to use is tools.Tools here I'm going to go ahead and provide my tool called as read email tool.Send email tool.whatever tools I have written over here on the top because my agent work is basically to send a uh email right then here I'm going to use a checkpointer this is for my memory so inmemory saver in memoryinmemory saver I'll go ahead and initialize this now I'm going to go ahead and add my middleware okay middleware as I said you can also add summarization middleware over here but this example I want to So human inthe loop middleware and inside this human in the loop middleware way I will have multiple options.One is interrupt.So I can go ahead and use interrupt.So I will uh go ahead and use something called as interrupt on.
Okay is equal to now where I need to interrupt right that is what we really need to understand where we need to interrupt it on what kind of action I want to interrupt it.Now in this particular scenario if my agent is sending a mail I really want to make a confirmation from the human being or get an approval before the human being before sending the mail right so here what I'lldo interrupt on I will write okay this functionality which is called as send email tool so whenever this functionality or this tool is basically getting called I need to go ahead and ask for the human permission right whetherwe should allow it or not so here I will say allowed decision which you can hardcode it Okay, decision and here I will say I will have three important things.Okay, three important thing.
One is approved, edit or reject.Okay, so I'm saying that there are three important options that you can basically interrupt on and human can basically approve it or edit it or reject it.Okay, either it can approve okay go ahead and send the mail either it can say no no no don't send the mail to this email id to some other mail email id that is reject edit and third oneis something called as reject okay so this on send email tool I definitely want um I definitely want a kind of interrupt right now with respect to read email tool I don't want anything so what I will dofor this particular tool I will go ahead and say hey go ahead and make it false.So whenever I'm making this particular tool call for this particular tool call I definitely go need to go ahead and take an approval from the human being.
The human being can provide three options.One is approve, edit and reject.Okay.So this is done very clear.So I will go ahead and execute and create my agent.Now once I have my specific agent over here, now the next step is that what I will do?I will just go ahead and create a config file.See config over here.I'll say test approve.Let's go ahead and do the test approve with this thread ID.Thread ID indicates unique ID.Okay, I'm using message.invoke messages human message and I said send email to [email protected] with subject hello and body how are you?Okay, so this is my input that is given over here.Now once I give this particular input the agent will know okay it has two tools.One is read email tool and one is send email tool.So it will first of all go ahead and execute read email tool. Read email tool is nothing but it goes and uh read the email by its id and send email is nothing but it mock sends mox function to send an email.Okay.Now while reading this particular read email tool it will not do anything but once it goes to send email tool it is going to create an interrupt.Okay.So let's see this.So I'll go ahead and execute it.And now I will go ahead and see my result.See there is something called as interrupt.Now why interrupt is basically happening over here?It is very much clear because we have created a trigger over here right in this particular middle uh in in this particular middleware wherein wherever the send email tool is basically executed we need to go ahead and takea permission from the human being.Now what is basically happening for this send email tool now we need to take a approval from the human being.
Now for the approval process it is very simple.I will go ahead and write this particular condition.Now see this I will write if interrupt is present in result print pause approving then I will say agent.invoke invoke.Now see human needs to see give the confirmation.Okay, go ahead and send the mail, right?Then how that execution will basically happen.For that we use this particular uh uh this particular library which is called as command.
20. Approve, Reject, and Edit Tool Calls
Demonstrating the three human decisions—approve, reject, and edit—on interrupted tool calls, plus a tour of other built-in middlewares to explore.
Okay.Now this command what it does is that it executes a command.Okay.Now what command it basically executes?It executes says that hey execute the workflow resume the workflow and there the decision type will be approve.Now this approve if you remember it matches this right so we are saying approve right so here we are saying approve right and for the same config then we will be able to see that the mail will besent so this is the code wherein the human is approving right if you instead of approve if you write reject over here it'll get rejected right so this is the human approval that is basically happening so once Iexecute this I'm getting an execu error saying the command okay command is not there we need to probably go ahead and uh you know uh import the library which is basically called as command.
Okay.Now command libraries uh will be available uh let me just open my browser and here I will search for langchain command.Okay so lchain command let's see there is interrupts.So interrupt command command command rumé.So here you can see from lang graph.types import command.So I'll go over here.I will paste it here itself.Okay.So here you can see that I'm basically pasting it over here.I'll execute it.Now this should basically execute it.Now here you can see the email has been sent to [email protected] with subject hello.So before my result was this.Now if I go ahead and see my result, it will basically have the tool message which is nothing but email sent to this because this is the tool that is basically getting called right the send email tool.This tool is basically getting called and that has executed wherein it has said that okay we have sent a email to this and finally the AI message is saying that the email has been sent to John test with subject hello.Okay.Now similarly let's say you want to do it for reject.Okay.So how do I do it for reject?Let's say the human wants to reject this.Okay.Uh uh it does not want to continue with this, right?So for reject again I will use the same code.Let's say this is my agent entire thing.Okay.I will execute this.I'll open more code cell.Now I will go ahead and set my config.Now here we are basically saying that okay fine agent.invoke.Okay.I have to basically close the brackets.Okay.Now I'm using this test do- reject for this particular thread.I'm using this unique.And then for rejecting I will just go ahead and update my code.Instead of making that decision type as approve, I'm going to use this as reject.So this reject and this reject are matching.
Right?And then I will just go ahead and execute it.Pause approving.You can see it seems that there is was an issue with sending an email.Now if you go ahead and see the result, you'll be able to see that user rejected the tool call.Right?Very simple.Here we are using this command.Okay, this command is really really important.It's just to execute something in the specific workflow.Right?And finally, you can also do it for editing.Right?Let's say that I don't want to drop a mail by mistakenly have given some other email id.I want to change the email ID.Right?So everything is same over here with respect to creating an agent.I'll go to the next step.I will go ahead and create my config.Let's say I go ahead and send an email to wrongthe ratemail.com with subject text and body hello.
If I go ahead and execute this, I will go ahead and show you the result.It'll be interrupted waiting for the human feedback.Now the human can basically say hey go ahead and execute the type edit.So here you can see if interrupt in result agent.invoke Invoke command resume is equal to decision type edit and edited action we have said that okay name send email to we are changing the argument recipient subject and bodyokay so this was edited by human before sending and I'm giving the same config if I go ahead and execute this you should be able to see what is the output that will be the email has been sentsuccessfully now if you go ahead and see the result you'll be able to see that the email send to correct at the rategmail.Right?So here we have edited right.So for edit you have something called as edit action.
So this is basically with respect to the human in the uh loop uh middleware which you can go ahead and try it and do it from your side based on your requirement.Okay.Now the next thing is that you can still go ahead and explore all the other built-in built-in middleares like model call limit.Let's say you want to have the limit the number of model calls to prevent infinite loops.You can go ahead and use this thread limit run limit.You can go ahead and see what are the configuration options.So this entire page you can go ahead and explore it by yourself and you can do multiple things.You can do LM tool selector option is also there right.So here you can see tool selector middle middleware you can see agent with tools where most aren't relevant per query reducing token usage by filtering.
So for different different task you definitely have these amazing middleares okay which you can actually use.So I hope you have understood about middleares.