Pydantic Crash Course - Build Reliable Python & AI Applications
1:22:22

Pydantic Crash Course - Build Reliable Python & AI Applications

Dave Ebbelaar 28.01.2026 15 593 просмотров 500 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
Learn Pydantic in this complete 90-minute crash course covering type hints, data validation, nested models, and structured output with LLMs. Get the free bonus resources and community access: https://go.datalumina.com/M2YfRW3 Learn the system I use to find freelance Data/AI projects: https://go.datalumina.com/GGl48wN 🔗 GitHub Repository https://github.com/daveebbelaar/pydantic-crash-course ⏱️ Timestamps 00:00 Introduction to Pydantic 10:38 Understanding Type Hints 20:02 Creating Your First Model 29:15 Validation and Fields 1:02:45 Nested Models 1:03:57 Pydantic Settings 1:10:17 Structured Output with LLMs 1:20:18 Course Summary and Next Steps 👋🏻 About Me Hi! I'm Dave, AI Engineer and founder of Datalumina®. On this channel, I share practical tutorials that teach developers how to build production-ready AI systems that actually work in the real world. Beyond these tutorials, I also help people start successful freelancing careers. Check out the links above to learn more!

Оглавление (8 сегментов)

Introduction to Pydantic

Welcome to this complete pyantic crash course. We're going to cover everything that you need to know and we'll build up in complexity over seven chapters. And along the way, I will show you very simple isolated examples that you can follow along with to fully understand everything. And if you're new to the channel, welcome. My name is Dave Abal. I'm the founder of Data Luminina, which is an AI development company, and I've been working professionally with the Python programming language for over a decade. All right, so let's dive in. We are going to be working from this GitHub repository. link will be in the description. So, I highly recommend you to clone this to follow along. Before we dive in, let's set up your working environment because this is not going to be a passive course. If you just watch these videos, yes, you'll learn something, but I highly recommend you to follow along. So, when you open up the repository within your favorite IDE, I have it open in cursor here for example, but you can use whatever. There is a pi project. l file. Now I am going to assume you're already familiar with using UV. If you don't know how to work with UV, I will reference my complete Python fori beginner course that will teach you all the fundamentals. So pretty much what we can do right now because we have UV installed, we have a pi project atml. What I can do is I can simply run u sync and it's going to set up the entire project for us. Uh you should make sure that you have the virtual environment created that it is active within your editor. So you can see over here I'm running the virtual environment and then what I can do from paid we're going to import the base model. So let's do a quick check to see if this runs. Now I will be using the Jupiter interactive session throughout this tutorial to quickly and visually show you these examples. You can also follow along with that or simply run the Python code and send it over to the terminal. That also totally works. So that's the foundational setup that you need with that. What I'm going to do now is I'm going to continue go back and forth between the repository where all of the chapters and all of the instructions are. So I will be constantly switching between a little bit of theory and then showing you the code examples line by line so we really get a feel for how this works. Now this is where I want you to follow along. So the nice thing that this is a GitH repository and a markdown file. You can come in here, you can simply copy paste all of the examples and then swap it in here. You can just work from this single main. py file which I will also be doing within this project and then we can run it and we can just override everything. So with that setup out of the way coming back to the main readme file to tell you what we are going to cover. So this crash course is going to be it's split up in seven chapters where the final one the last one is the summary. So, we're going to start with the introduction. Always important, right? Then we're going to talk about type hints. You need to understand Python's basic type hints first before we can get into actual the functionalities of Pentic. Then we're going to create your first model. We're going to cover validation and fields, nested models, pentic settings, and then finally structured outputs using large language models. And throughout all of the course modules that we will walk through, I will also give you some sneak peeks of some projects that we are working on. So some actual production examples of where we apply it and how and what that looks like. So by the end you should really have a total understanding of what to do with this library. It's super fundamental. Like I've said, in my opinion, it's one of the most important Python libraries of the ecosystem. and you only really need to know literally what I'm going to share in this course and then you'll be good to go. So let's dive in. We're going to start in the docs folder and let's dive into the introduction. So Pentic brings runtime data validation to Python using tipits. That's the overall summary of what this library is about. And in order to understand what that means and understand the importance of that, we first have to dive and zoom in on a little bit of a kind of like a problem that Python has. It's a problem, but it's also a nice feature. It's really by design, but that is Python is dynamically typed. And this means that when you are working with variables, and I'm going to switch to the code editor over here and run this. I can pretty much say look if we have an age as a variable I can set that to 25 which is an integer totally fine. I can now override that and make it a string 10 25 totally fine. Python allows to do that or I can now say look it can also be a list and again no issues whatsoever. This is what we mean when we say Python is dynamically typed. There are also other programming languages who are statically typed. For example, C, Java, Go. And in those languages before you declare a variable, you specifically have to mention, look, this is a boolean, this is a string, this is an integer, this is a float. So, in that sense, it's more static. Python is dynamic. So, Python really doesn't care and does not give us errors if we start to mix and match and just go on the fly and try to experiment until we get something that fits. So this flexibility is great for quick scripts. Like I said, you can iterate quickly. You don't have to think about it. But it can become a nightmare when you are building real applications and especially when you are working with external data. So when data is flowing through your system, you throw AI systems in there that now also generate output. The fact that variables can pretty much be set to anything allows data and different data types to go through a system mix and match and ultimately end up in errors when we want to do operations on them. So let me show you what I mean with that. So when things can go where things can go wrong. So let's say you're you have a system and you have an API meaning that your application is available and other systems or people can send data to that. Let's say we create a user. So the user has an ID, an email and the H. And in this case later down the line we want to perform an calculation on the H. So then when your application receives the following payload with H being an actual integer, everything is fine. But let's say the API sends the following payload where age is unknown and later down the line we want to use the h variable again to perform the calculation. So let's go to an example. Let's set age to unknown. So this is coming into our system and Python doesn't care because we don't perform any validation. And then we want to calculate the birth here. And this is where we get an error. Whereas if we set this to 25, you would get the ID. Now it would totally work. And we can perform the calculation. So this is where issues start to pop up. the code crashes but not necessarily when the data comes in but when the data flows through your system and when it gets to the final point where you need to actually use that information. So here's the real world impact of that. In any application, serious application, you are constantly working with API responses, data and information flowing between systems, databases, applications, front end, back end, external services, microservices, user input, and you want to never trust user data. So users that enter information into a field, for example, with the H. So let's say people don't want to mention their age, so they just type in a random set of characters instead of giving their actual age or configuration database records. Without validation, bugs hide until production. With Pentic, they surface immediately. That's one of the key things that P Pentic can help us with. So what Pyntic does is it validates data at runtime. So whenever we load it instead of when we try and use it. So you define what your data looks like and Pentic ensures it matches. So this is an introduction to the Pyantic library. In the next modules, we'll go deeper into actually creating these models step by step and go through everything. But I just want to show you the kind of like final example and then we'll build it up step by step. But here you can see what that looks like if we're using Pentic. So let's say we want to specify a user. And this is really the magic of Pentic and where we use Python's styins. We say look, we have an ID and we want this to be an integer. In this case, an email. We want this to be a string. We can even go further and even validate if it's an valid email. And H can only be an integer. Meaning that if we set up this model, if information flows in with the right information, ID is one, we have an email, and we have an H, everything works. Everything runs fine. If we don't, we get an error. I'll show you what that looks like. I'm going to import biantic from base model. Like I've said, in a bit, I'll show you exactly what the base model is, how to set it up. But I want to show you and teach you this with the end in mind to see what we're working towards. So, we define the class and then let's try and run some data through this, create an actual user. And here you can see we don't get any errors. We get a green check mark. So, this is all good. Python says this is proper data. Now if we run the second example where the age is unknown, what we'll get is we get an error and we get the following error. So let me see if you can see this over here. We get a validation error. Two validations actually uh because also we set the email to none. So there are two errors. So email input should be a valid string. Age integer. So this is where piantic comes into play. This is the magic of what pyntic can help us with. And this way we make sure that the problem is caught at the source and paid plays a huge role in the Python ecosystem. So many Python packages rely on pyentic under the hood because of this strong validation. The most popular one probably being fast API. All right. So then continuing to installation very simple in this project it was already set up in the pi project autotoml but you can add it to your python project like any other library using pip using uv or using whatever dependency manager you want to use and then you are good to go. All right so with that introduction out of the way let's go to the next chapter and that is type hints. So chapter two. So before we really get into the nitty-gritty, you should understand how typins work in Python and

Understanding Type Hints

this is very simple to understand because if you have some Python understanding, if you for example went through my Python 4AI course already, you have seen this but may not fully be aware of how this works. But type hints are the little notations that you see over here. So let's say you have a variable name and we set that equal to Dave. We can use the colon notation and then we can specify what's the type and the interesting thing is in the introduction we mentioned like look Python is dynamically typed so Python doesn't care right so why then do we use typins and what do they do well they are pretty much just documentation they don't enforce anything and here's what that looks like so if we come back to our editor and I'll show you the following examples over here starting from how we would normally specify a variable, right? We would say name equals Dave, which is a string. So, this is probably what you're familiar with if you've never seen typins. Now, we can now do the colon and then I can say, look, name is a string. This doesn't change anything. It runs the same. Name is still a string. It's just documentation. It's a type. It signals to our uh IDE as well as to like the programmer, the developer, look, this should be a string. But here's where it gets interesting. What if we let me actually get rid of this to keep it a little bit more focused. What if we now say, look, name should be an integer. And we run this. No problem. Python still says, hey, you want to be an integer? I don't care. String is totally fine. So that's one of the most important things to remember. We can specify strings, integers, floats, booleans, any of these core primitives and data types that we use within the Python programming language, but Python doesn't enforce them. It's totally fine. There's no error. The code runs just fine. So, why do we want to use them? Like I've said, it's for documentation, IDE support, downstream tools that leverage it can use them, but in the end, it's just documentation, similar to how you would add a hashtag and then write a comment. nothing changes about the way the application runs. So scrolling a little bit down, we can even add type hints to functions. So let me show you how that works. So that is done via the following notation. So let's say we create a function. So we do deaf, create a user, and then we have some input parameters in here. So we say we plug in a name which should be a string, email age should be an integer. And then look at this little arrow thingy over here, which is simply just a dash and an arrow. This says that this function whenever we return something it should return a dictionary. So not only can we give typins on the input parameters of what we do with this function but also the output. So in here I could for example start to create a user dict the name in here we set that to the name. Then we set the email we set that equal to the email. And then what else? We have the age. We set that equal let's make sure we put that in strings and then we set that equal to the h and then we return the user dict. So that's how typins work. We can use them at the variable level or we can even use them with function parameters over here and we can also use them for outputs of functions. And then if we look at all of the basic types that are or that we use within Python we start with four basics. So these are the strings, the integers, the floats and the booleans which I'm going to assume you are already familiar with. Now if we scroll down we get into the container types and this is something I think for a lot of you watching might be the first time you fully understand what this is about and how to actually use this. So container types mean is that we can create these nestedest kind of types where here you can see for example we have a variable we call it tags and tags we give the type in we say it's a list and within that list are strings and this pretty much means we expect a python list and in there we expect only strings so we don't expect any numbers in there booleans in there so this would be a proper example now similar We can also do this using integers. So this would be a list and we expect only integers in there. But we could also go a step further and say look if we have a dictionary we expect it to be a dictionary but then a dictionary has a key and a value and the key is always a string and the value is always an integer. For example, error equals 12, warning equals 5. But it can also be a dictionary with a string as a key and a string is a value. Team is dark, language is English. So you can see we can use these built-in types list, dictionary, set, tupole. And in this way we can also give even more specific typeins. And to show you what that looks like, it is literally the same. It doesn't enforce anything. It's just a way to create a variable, use the colon notation, and be a little bit more specific about the nested components, the nested types that we are using. But if I run this and I have a look at what tag is, it's still a list. And now this is important to understand because when you are starting out with the Python programming language, this is not how you naturally write your code. But if you ask AI for help, it will probably throw in a lot of these type hints all the time. And it's good to fully understand what it does and what it does not do, that they're simply just types hints. So that's why I wanted to spend some time here to make sure we actually help you to get started with the fundamentals and build from there. So we can also then look at optional values. So when we say look name should be a string we can also say it's an optional field meaning it can also be empty. It's totally fine if nothing is there. And there are two ways to do this. So we can import optional from the typing library which is native in Python. So no need to externally install this or we can use the pipe notation. So let's have a look at what that looks like. Let me clear this up and run this actually one more time. So we can from typing we can import optional. So again no installation and then let's say we have a middle name over here. Let me actually zoom in a little bit and we say look middle name it should be a string but it's optional. So we can set it to none. That totally works. But we can also set it to Dave. And again, nothing is enforced here. There's still just type hints. Let's put it back to none. And similar with the pipe notation, we say it can either it can be a string or just a pipe. It can be none. Both for are the exact same in terms of the notation and the meaning behind it. Pipe is just a little bit easier because we don't have to do the import. So those were the optional values. So now the last data type that I want to cover which actually a really common one is the literal types. This is super useful as well. So a literal we also import that from the typing library. We can be really specific about giving certain categories. So in this example the status we can say look it can either be a draft published or archived. That's it. Those are the options. So we go one step further than just specifying status should be a string. we say it should be a string and it should be either one of those. So coming back to our editor and plugging this in how that then works is from typing we import literal and then we define the status we do a colon we say literal and then we open with square brackets and then we give the options in here draft published archived and we set currently the default or we set the value to draft currently which should be fine. So in essence when we follow the typins status draft should be okay status published should also be okay but pending is not an option in here but again as you know by now Python is still totally fine right all right so that covers the data types that you need to know right now the most common ones that you'll encounter as the introduction really still to this crash course because now in chapter three we go to your first model and the mental model that you should really understand is Pentic is building off of Python's type hints, but now we can make them strict, we can actually enforce them off rather than it simply being just comments. So here we get into the library specifics. So in the beginning I already showed you a little bit of an example as to how this works, but now we're going to create one from scratch. So whenever you are working with Pentic, we start with the import. We do from p identic and generally you always want to start with the base model. So we do from pentic we import we do base model make sure to capitalize both the b and the m and we import the base model. This is pideantic's base class from which we're going to inherit new classes which then

Creating Your First Model

will contain all of the functionality that the paidic library has to offer. So how you use that is you create a class like you normally would. So you now create a class. Let's say we call it user. And now instead of just doing the regular approach that you would do with Python, what we now do is we inherit this user class from the base model. So we plug that between the parenthesis. Then we do a column. And now we can specify our data model. So now let's say we want to have a user who has a name and that needs to be a string. Then we have the age which should be an integer and then we have the email which should also be a string. This is now your first pentic model that you have defined. We can now downstream within our application we can start to use this model. So let's say we now want to create a user. We say user is we initiate the class instance and we need to plug in the parameters. So we need to say look name equals Dave. We for example age equals 31 and then we do the email equals let's do again Dave example. com. And we now have this data model this clause where we can now say user. name name equals Dave in this case. Do you see it? Yes. And we can say user. h. You get the idea. We can use all of we can access all of the attributes, all of the properties from this class programmatically. And we now know that it is validated through Pentic. How do we know? Well, let's make a change. Let's say we swap out the h and we just make that a string or whatever type of random value. If we now try to load the data, piantic will throw us the error. So once you understand this concept and having gone through the typins already, you can already probably start to connect the dots. We can now simply use Python's tipins, but now they are enforced. So this is the key idea of using the paidic library. But now let's do a quick comparison between Python's native data classes because this is something you may see occasionally. And we of course we made a step because before when we were doing the typeins we for example we were just saying name equals string right we would specify the variable and we would say this is day for example but now we have this data modeling notation. So there's a little bit of a jump there where you need to think about your variables and your data in a set of models. That's how we can keep information together, how we can reuse it and how we can also later down the line access it. Now this is something that you can also native natively do with in the Python programming language using data classes. So you'll find that the notation is identical. It's literally the same. But the only difference that there really is over here is that let me actually show you. We now from data classes import data class. This is native within Python. No in installs needed. And we create a class and we use decorator notation. And in this way we can create a similar type of class. We can create the user and we can also print the user H. But there is no enforcement. So, Pentic took this ID, this core concept of what you can already do in Python and said, "Look, we want to improve it. We want to make it strict. " But I wanted to show you all of these components, the tipins, the data classes, how it works in the most fundamental way so you understand how we got to this point and how the library was designed and why it's so awesome and why it's super native actually to use Pyentic within the Python ecosystem. if you are familiar with how to set up data classes. So we know that this runs right now with the data class without an issue. But now here's a good exercise. Let's turn this into a pyantic class. So we do again from paidic import and we do the base model and then we can get rid of this decorator and then we just need to inherit the b user from the base model. We can run that and now we get an error. So this is a good exercise for you to go through to get a little bit more familiar with the syntax, how to write it out, where to plug in the base model and how all of that works. Okay, so creating instances, this is what we just covered, right? This we perform class inheritance and we create an instance from the base model. This is Python's way of saying look, we have this class model already and this base model contains a lot of information. So here I can drill down into the actual paidic library itself. So here if you follow the traces it's a little small but you can see this is actually in the virtual environment. If you go into the pyantic library and then into the base model this is the actual implementation. So here you can see there is a lot there's a lot of stuff in here a lot of methods that we can use and we bring all of that functionality to our class by simply using this notation over here. So that's how we create the instance. So the validation in action, we already saw that scrolling down. So here's also one thing you should know. Pentic is smart about type conversion. We can use a more loose mode to default mode or we can be strict. But if we let it, it can convert com compatible data types automatically. Let me give you an example of what that looks like. For example, with a string that is actually an integer. So if we have the following example again base model user name H name should be a string age should be an integer string 25 the one you see over here this is not a string but pientic will still allow it look at this we can run this it will say hey this is a string but I can convert this to an integer without any error so this is probably what you want to do so pyeic can handle these automated type coercions that's something to keep in mind. Now, let's talk a little bit about required versus optional fields, right? So, we covered this with typeins already, but let's look at a couple of examples. So, we have our the following data model over here. Again, we're working with a user name required, email required, age, we use the pipe notation, remember? So, we this can either be an integer, but it can also be none, meaning it's empty. There's nothing. So what that then means if we create a user where we only plug in the name and the email. So we create the user no error. And then if we try to print the age we see we got nothing in here because if we let's see if we look at what that user is. So let's see moving a little bit to the side you can see our data model is the following. That totally works. Okay switching back over here. And in a similar way if we do provide it we have the user age and let's see now it is 25. So, Pentecially if you get into bigger data models that we will work towards and I'll show you some examples like I've said of the real world projects they these models can get really big especially if we're working with API responses. Okay, so that is the required versus optional fields but now in action with pidentic and enforced through strict validation. Then let's talk about the default values. So remember the default values is where we specify the type but then we also put an equal sign after it and we just specify a value. So let's run through the following example of creating an API config. So let's say we want to store all of the information that we have to configure our API and let's see let's run this and we create our API config and we have our API key which there's no default value but let's say we we're using an AI model and GPT4 is the default if the user does not provide an alternative we'll use GPT4 max tokens we'll set it to a th00and and the temperature 7 the equal signs over here that's how you specify default values and that's now also So how when you are creating this instance of this new model we can omit a lot of the information because we use defaults. So here you can see if we then create the config even though we only plug in the API key we still get the complete data model with all of the information in here. That's how defaults

Validation and Fields

work. So we can check the model max tokens. Now if you were to skip one of those default values let's say the temperature you just specify should have selected the whole thing then we don't get the error. So if we just have the temperature in here and then say hey we want to create the config now we get the error because now it says look we are missing a required field which is the temperature. All right so I'm taking my time here to go through these examples because I really want to show you them in action not just a theory. I want you to think about oh look default optional values how do I work with this in the day-to-day that should really become second nature when you work with this library so then here's another really cool feature of pientic that we get on top of the validation and that is that we can easily convert data models to either JSON dictionaries back and forth and let me show you what that looks like we can use the model dump method on our model. So if we have the following which right now should be familiar right we have the imports we create the user now what we can do is we can call user and then you do model dump. So let me show you what that looks like. So we remember right if we have the user itself and we look at that this is an actual piantic data model. Now if we then run model dump now it becomes a dictionary. So now with the user we can do user. name and we get Alice with the user dict we get a dictionary and now we actually need to select the keys within the dictionary in order to get the value from it. So this is something to keep in mind as you are building your applications and how you want to use the information. Now generally within my application I really like the dot notation of the pyentic models and usually just do a model dump to a dictionary or more specifically to JSON which I will show you in the next step whenever I want to send it via API or send it to an AI model. But because other than that I really love this autocomp completion because if I if you look at this because my IDE understand that user is created from a user. If I now do dot I can for example just get the H on there and we have the autocomp completion in here. So you can see everything that is available. So it also understand looks there is a name in there and with dictionaries that can be a little bit tricky because if I now have the dictionary key over here my IDE doesn't help with this. So I need to remember oh wait this is the model so the key should be a name. So this is also why coming back to one of the arguments right making your applications more reliable but also letting both you as well as AI agents better understand what the data is that's flowing through your system but we can easily move back and forth between the different versions of the data whether that's JSON dictionary or pyantic models so in a similar way we can do the model dump JSON so it's exactly the same but what we do right now is we do model dump and then we simply do another underscore and we do model dump JSON. So this is now the let's keep it at user dict but now this is JSON which pretty much means it's within a string. So if we now for example print this and print the user dict there we go we can see this is now a string and we can pass this along an API. So really helpful especially this one. Later we'll also see how you can use this to dump context into uh a large language model into the messages for example. Super useful to work with. So that's another extra benefit that you get out of the box. Now we can also do it the other way around. And so meaning we start from a dictionary maybe some information that's coming into our system. We load it from a database. we get it from an API and now we want to validate that against the paidic model. So instead of going through it line by line and saying hey we create the user the name is this the email is that like typing all of that out there's a better way to do it. So I'll show you the two ways that you can do this and this is super common so pay attention. We first set up our user model again which now should be familiar to you. Then we have our data coming in. This is now a dictionary as you can see. So let's say this is either loading from your database or this is what you're receiving from an API. There are two options. We can use Python's unpacking method by using the two asterisks. So we say look we want to create a user and what we want we just want to unpack the data in there. Remember data is the dictionary. Unpacking simply means we set name to Alice, email to the email, age to 30 in this case. And this works. So now when we run the user, you can see we can simply create a user by unpacking it. And this is already a lot less code, a lot less like manual actions that needed to uh that need to happen within your codebase by simply unpacking it. Now we can also use Pentics model validate. So we say user. model validate and then we plug in the data. It's pretty much the same. The only advantage is if you use model validate, you can see we have more parameters that we can work with. So you have strict which is a bull boolean. We can have extra values. So uh in a lot of cases this simply works. But if you need more functionality, model validate does the same. We end up in this instance with the exact same model. All right. So that's how you go from dictionary or from JSON back to a pyantic model. Okay. Now here we get to something interesting. This is something new and this is something you do all the time in the real world. This is where we are actually going to move beyond the regular typins that we've seen and we're going to use models as typeins. So what we can do in the following example beyond simple typins like hey this should be a string this should be even like a nested one a list of strings we can also say something like we have this user which should actually be of type user. So remember what's see what's going on here. We can do the type in notation. We do the colon and we can specify our own custom models. And in this way you can see that if we load a user in here this function we can output it to a user and then we greet the user. This is now all validated through pientic. So let me show you what it looks like if we put these two functions here in memory. So first we call our load user function. And that is now creating a validated user model. So we do valid model validate. And this is now very strict. Whereas if we change something in here, let's see, we get an error. So let's put that back and actually load the correct user. And then we can do a similar thing in a greed user. So this is now data running through our functions where we know this should be a user. This is validated data. So, super useful models as typins. Okay, scrolling down to a real world example. I'll show you something here and then I'm actually going to dive into a project of ours where I'll give you like a behind-the-scenes look of how this really works. But let's say we are working with this weather data API. Let's first you do the hypothetical example and let's plug everything in. So, what are we working with? We have a weather response. So, let's say we have an API endpoint. We can query that. We can ping that and we get the following information back. We get the city, we get a temperature, the humidity and a description. So let's now simulate this API response. And let's say it would look something like this. City's Amsterdam. Here's the temperature. Here's the humidity. Partly cloudy. Let's say we're working with this model and or with this API and our application depends on this weather data. So we want to process that. We want to make it available in an application. We want to send a notification to a user. We want to perform some calculations. Now, here's what we do. We take that weather response model. We call model validate and we plug in our raw API data that we get. Now, this is where it gets exciting because now within our Python back end, within our Python application, we can guarantee that we have a validated model and validated data that we can now work with. So now if we were to use this in our application, we could actually confidently say weather in Amsterdam and we would print the weather temperature and we can put the degrees Celsius in here and we know that is an actual number. Now it could for example be that the API at sometimes says unavailable or unknown. If we were to not handle that with Pidentic, it would load the data. It would process everything and then when we send a notification to the user, bam, our application would break. Similar for the humidity, we can now say, look, we know this is a number. So, we can actually put a percentage behind this. And we have the description as well, which is a string. So, here we have a beautiful notification validated and all. So, here's what that looks like in an actual application. This is a SAS product. It's running in production right now. So it has live paying users and when data is coming in from the web hook of the system that we integrate with we validate that in the following pyantic base bundle which we call the gorgeous event schema and gorgeous is a system that we're integrating with. So we have set up a web hook. So whenever something triggers within that ticketing system, our back end gets the web hook information and the web hook sends a big JSON schema and we want to validate that within our application. So we have our endpoint set up using fast API and again that is all beyond what this crash course is about but I want to show you how relevant this is really in the real world. So we validate all of our incoming data through our fast API endpoint by setting the incoming data to the event schema and here you can see this very large model that we have created where we start with the name email first name last name and then there's a message in there and a message also has an ID a channel a source so you can start to recognize all of these patterns that we've seen right we use the optional notation because sometimes information is missing we even used nested objects. That's something we haven't covered yet. I'll show you that in a bit, but that's al also something that you can do. But again, I want to show you how relevant this is because now every time information comes into our system, we exactly know what it is that we have and we can perform the validation. So downstream we can actually use these fields when they are available or use defaults values for example for the name, first name, whatever when they're not. And now, if you want to learn more about how to build these end-to-end AI applications, I have something cool for you. Don't worry, this is not a pitch. It's completely free because this is part of my free Python for AI course that I have on YouTube. It's the resource hub and community access. So, I will leave a link down below. You can come in here, plug in, just plug in zero. You can do any tip that you want, but zero is fine. I want this. You'll get access to all of these resources, but most importantly, you'll be invited to our data luminina academy. So, Data Luminina is our AI development company, and we have an academy where we share a whole bunch of free videos and courses similar to the ones you're watching right now, but now all in a sequential order to really teach you from scratch how to build endto-end AI and agentic applications using Python. So, if that is something you want to learn, make sure to check out the link in the description. Like I said, this is completely for free. We do have paid programs, but literally like the first eight hours or so is completely for free. So go check it out. So coming back to our example, we So this was an API example of the weather data and I've also shown you how we actually use this in the real world for our development company and the products we're working on. All right. And the final thing that I want to show you as part of chapter 3 is the strict mode. So remember earlier when we talked about the coercion, right? So taking for example 25 as a string and trying to force it into an integer. This is the default behavior. But we can use strict mode which as the name may suggest doesn't allow that. And how we do that is we need to import the config dict. So we do from padentic we import the base model but we also import config dict. And then when we specify our model we take the model_config and this should be exactly this. This is syntax of the library itself. We set it equal to the config dict. And here we can choose from a list of parameters. So scrolling down, if I hover on this, you can see all of the extra parameters that are in here. There are actually a lot. And to be honest, I really never use any of these. So that's also why this is really like a 8020 kind of crash course. There's a lot more to the Pentic library. So feel free to explore that. In my opinion right now strict mode is I think the only thing to uh keep in mind because what this will do if we have strict mode on so default is off. If we say we have strict user we will name Alice age 25 won't work because we have strict and it should be a valid integer. So even though we can convert it strict mode says not good enough. This won't pass the bar. Okay. So that was the final thing that I wanted to show you as part of chapter 3. So let's continue and next we go to validation and fields. So this is all now you already understand really the most important things of the pyentic library and what you can do with it. But beyond type just type checking we can go further because sometimes you want to be more specific. examples. Email must not just be a string, but it must be a valid format. Age m must not just be an integer, but it must be a positive number, maybe higher than or and less than. We specify a range. Username must be a string, but it must also be between three and 20 characters. Price can't be negative. These are all checks that we can also do within the pyantic library using the field function. So that's what we're going to cover right now. So let's start with some examples. So back to the code. As always, we now have a new import field from Pentic. We import base model and we import fields. So let's run it up and have a look at what's going on. So to let's see, let's make it a little bit smaller so you can actually see it on one line. And I think this makes more sense. So what's going on? Name should be a string. We're familiar with that. That's easy right now. But now we set it equal. Remember equal. What was that? Equal was the default value. Okay. But now we set that to field. What can we do with field? Well, we can again provide or specify a whole bunch of parameters. So if I hover over this, you can see alias priority. I can scroll down. Again, there is a lot there are a lot of extra things that we can do in here. I'll show you the most common ones. On a string field, we can say look, there is a minimum length and there is a maximum length. On h for example, which is an integer, we can use this notation over here. Greater than, less or equal. So, am I saying that right? I always Let's scroll down. I always mess these up. GT greater than GE greater than or equal. LT less than LE less than or equal. I think I said that right. Just for record, want to be sure. So these are all parameters that we can now add to our model as well to perform extra validation. So now let's see do we have an example over here? If I put this in here and run this, this now works. But let's see if we say h and let's say let's set that to minus one. Now we get an error. And here you can also see the beauty of the pientic library beyond the basic type hints. It not only says h should be an integer, it actually say h input should be greater than zero. So it really translates the field parameters and it translates it into the rule that is broken and then gives a human readable suggestion or hint as to what it should be. And that's why it's super useful also again for AI agents when they run in loops and try to course correct. So that is how we use the field parameter in here. So let's go through a couple more examples. So let's see we started with this one minimum length maximum length. We can do string constraints. So like I said this is we covered this. We can do a maximum length. We can even try and do a pattern. So we can use regular expressions to filter for something. And this is also the stuff where like AI is just super good at and why in my opinion is so a fundamental just understand the basics of this library and then you don't have to remember how these regular expressions work. You just need to remember oh look I think paid can also help us with that and then you ask AI whenever you encounter a problem you say look I want to validate this field and I think I want to use reg x for this can we check xyz and AI will just create a pattern for you. So I'm scrolling down a little bit here because you get the idea, right? Minimum length, maximum length, pattern, number constraints. These were the things we talked about, greater than, greater or equal, specific ranges. We can get really specific. The mental model that you should keep in mind here, every time I really want to validate something, I want to constrain something. It cannot only be a string, an integer, but even more constrainted. There is a way in pyantic to do it. So what if we want to do a combination of actually using the field but then also using the default values because that's what I said right we in the beginning we learned look if we use the equal sign for example like this that means we set the default value but then how does it work if you also want to do the field well that's where the default value comes into play so you can over here we can set a default and let's see we can set the default to 30 and now That works. So now in this example, we could get rid of H. Let's see. Let's run this. We could just specify make sure we have everything in memory. Now we can just specify the name and the email and it will work. Okay. So scrolling beyond the default values field descriptions. So look, we can also do the following. If we have the field, we can also add a description. And now while this out of the box for code runtime doesn't really add anything this can be it's just documentation but it can help for example when you generate JSON schema as an API documentation. So when you for example use fast API it leverages these descriptions and what's also really useful we'll see that in the final chapter when we work with language models and structured output these can actually be added to the prompts. So these become information for the LLM model to even better understand how it should interpret and fill in the fields. So that's the description. So just know that the field parameter if you hover on this there is a lot all of these parameters that you see in here can be added and have some type of influence on how it works. If you want to learn more about that I recommend going to the official Pentic documentation. Again, this really is 8020, the stuff that you'll use most. Okay. Now, the final thing that I want to show you when it comes to validator validators is creating a custom validator because you may even need to be more specific even than what we've just shown you. So greater than or equal, less than, maximum length, these are all kind of like default constraints, but you can go hyper specific and we can create custom validators. So let's have a look at the syntax on how we can do that. So what we do is again Pentic base model, we know that field validator this is a new one. So we import that from pyantic. Then we simply go about creating our model as usual. So let's say we just have a username which oh should be a string. Nothing new here. Now we do a field validator. So what we do we use a decorator notation. So we do the at symbol field validator and then we plug in the name of the field that we want to validate. In this case username this is all syntax. This is just something you need to remember. You probably won't remember it. So you either ask AI write it down somewhere or reference this again even I always like because I never I don't do this very often. So whenever I do this I simply ask AI hey I want to do a custom fields validator and it helps me to set up this syntax. So how does it work? This is the starting point which pretty much says look everything underneath this is going to check username that's the mapping. Then we specify a function. This pretty much can be anything. Doesn't really matter, but it helps to just use a descriptive name. But again, it doesn't matter. Then we use the class, comma, fee. So we plug in two parameters in here. This is something you just have to remember. Again, syntax. Why is that the case? The validator receives the class. So this is the class since there's no instant yet during validation. And fe the value being validated. That is what you need to plug into that function and how it works. Then inside the function itself, this is where you get to code your custom logic. What do you want to validate? And in this case, we are checking if there is a space present in the username. And then we can even raise the value error and we say username cannot contain a space and we lower the username uh we return the username in all lowercase. So let's show the default value where we say Alice Smith. So now what would be the return value of that? It would be Ellis Smith lowercase because that's how we validate this field. There's no space in here. It simply modifies the value. So we perform validation as well as some adjustment on that. So we have also altered the input really. Now what if we add the space in here? Well, I think you guess what's going to happen. We're going to raise a value error. What error? That's the cool thing. It's exactly the error we specified over here. One validation error for the user username value error. Let me see. You can see the thing over here. The username cannot contain spaces. So we can even specify our own custom logic and then also our own custom value errors to make sure we explain the business logic. We explain why that is not possible. Again, very useful for your future self, colleagues, but also AI when it's working with your codebase and trying to run unit tests, trying to run experiments and running into these errors. Very descriptive. It can just do another iteration and it understands ah username we don't we are not allowed to have a space in there. So, this can be incredibly powerful depending on the use case. So real world example, let's say you want to validate a credit card number, minimum length, maximum length, expiry months, expiry year. You can get really specific in here. So keep that in mind beyond the default type hints and even nested models. This is also possible. All right. Now, there are even some validators already available within the uh pyic library. For example, email string and HTTP URL are very common ones. So instead of saying look, email should be a string custom validator. It should contain an at symbol and then kind of like the whole notation of what makes up an email address. We can simply import email string. So let me show you. This is then what that looks like. It's all it's available within the Pentic library. And now if you try and run this, if it's not a valid email address, it will literally error. So either if it's missing like the. com, it's missing the ad symbol, it's missing something before, it will error. Similar with URL also super useful. Sometimes you just want to validate is this an actual HTTP or HTTPS URL. You can do it using this model over here. And let's see, final thing, constraint lists. This is also something we haven't covered just yet, but you can pretty much think about any combination you can really think of. And like I've said, paid can constrain it. So if we have the following, we say items, list, strings, and the minimum length should be one. What does this mean? Well, an order can simply not contain items with an empty list. So if I run this list should have at least one item. So if I then just plug something in there, let's say we have an orange, totally fine. So that is how you can stack it. Be creative with it. This is really where AI can help you as well. Simply tell it what you need and it will come up with the validation pattern for it. Okay, next up, JSON schema generation. So we already covered the model dump JSON, right? But we can also do model JSON schema. So this can also be useful when you are creating API documentation or integration with other tools. So instead of taking the actual instance of the class, we take the b we take the model. So as you can see we are not creating an instance over here. So this is the uh the thing to keep in mind before we first created a model and then we say look we have the actual data and we want that in JSON. What this does is it just creates a JSON schema of the model. So downstream applications for example understand what this is. So if I for example just put that in here you can see we now have the whole uh we have the whole schema in here properties name age minimum title type everything is in here. So this is also something that if you're creating API documentation or again integrations can be very useful to have. All right, scrolling down. We're actually yeah, we're actually at the end of chapter number four already. So congratulations if you're still with me. We are making great progress and you should already be a p be a paid pro at this point. Next, we're going to take that one step further. probably the most complicated that we can get and then I'll show you some really cool uh more real world examples and how you can use Pyntentic with AI models and using structured outputs. So let's continue nested models. And by the way, as you seen it on every of these uh module pages that we have, there's always learn more resources that pretty much go to either pretty much always the official Pentic documentation. So that's just good to know whenever you want to learn more. Okay, let's get into nested models. This is how you can handle complex data structures and again very common in the real world because the real world is messy and complex and it's often not as easy as we have an order and it's simply a list. There's usually way more that uh there is to it. So, real world data rarely comes flat. An order has items, a user has an address, a company has employees. Pentic handles this naturally. It's very similar to how you think about setting up your database models for example like relations objects. So what we can do and let me show you the following example to see what we can do. Nested models. What does that mean? Well, up until this point this is what we've been doing, right? Base model, order item, product ID, name, quantity, price. This is peanuts right now. But look, here's something new. Now we create an order and we do the same thing. We inherit it from the base model, but uh and we say we start with the order item, which is a string. But look at this item. This is now an order item. This is something new. This is a nested model because now instead of relating to any of the builtin types of data models that we can use, we specify our own. And this now simply means that when we want to create an order, we need to have an order item in there. So we can perform nested validation and be even more specific about this. And once you understand the uh the all of the context really in the foundation, it becomes really second nature because you can just think about chaining them, nesting them, combining them in any way possible. So now when we want to create an order, we plug in the order ID which is a string. But now the item we don't with just say product ID name quantity no we say this is an order item and in there we specify all of the information. So when we do this and when we print order items name we can see now we access the widget. So this is also very cool where we can now also use this nested notation. So the order is simply the entire object we created with all of the information in there. And we know that an order has an where we go item. So now we go one level deeper and we get to the product level and we know that an item has in this case a name. That's how we get to the widget. And now this is also how we set this up in some of our other projects where you can see we first have a gorgeous sender schema then we have a message the ticketing schema and we all use those together. So they can be nested where we have an official like ticket and that has a sender and in there can be a message and it can even be multiple messages. So that's how we bring all of that together and how it often works in the real world when you are creating these more complex nested data models. So this is a super powerful thing to keep in mind and something you'll be using all the time. Okay, so we can even do that from dictionaries, right? I'll go over this a little bit faster because we can even have a nested dictionary and then simply use model. validate again and everything still works the same. We can also have a list of models. So this is actually something I want to show you because this is also very common. So here you can see in the order that we were using, we say look an order has an item and that's just an order item. But if we look at the new example and we say we actually have an order item and then an order can contain multiple items. We can turn it into a list. So everything that we've learned up until this point can be combined. That's one of the cool things about paidic. So now the following we can do the following. We say look an order has an ID which is a string. It has a customer email and then we can have items in here and that is another nested model in here and we can add as many as we want in here. That will totally work because Pentic now understands that it's a list meaning that if we run this and I'll show you we have the uh we have the dictionary over here. So we use the unpacking remember unpacking with two asterisks to load it into an order. And then when we run over the print statement, we can see that we can access all of those nested sub items in here. So another powerful concept list of models that we can use and again all of these principles apply. So we can also make them optional. So here we can say in this example look over here we have a discount we have actually specified that as a pyantic model but it can also be none. We set the default value to none. All works. Deep nesting we can go as deep as we want. We can have a customer. We can have an address. Then we have an order. In there is a

Nested Models

customer. And again, the customer has an address. So we can go deep, deep. Really, you can go as deep as you want. Whatever really makes sense for your application. And that brings us to the end of chapter 5, nested models. Everything that I wanted to cover in here. So now we're going to do a little bit of a side step to Pentic settings which is also part of the Pentic ecosystem but it has a specific purpose and it does everything Pentic does and what we learned so far but specifically for loading environment variables and configurations and this actually comes in as a separate pip install library. So, UV at pyentic settings, but I want to add it in here as well because in my opinion, this is a super helpful library. And if you understand pyic, you also understand pyic settings. So, I want to go a little bit quick in here to show you what this means. So, if you've been following along, if you do if you did UV sync, you already have Pentic settings installed because it's within the pi project. l as you can see over here. If not, you need to add it to your

Pydantic Settings

project. So what this allows us to do is we can check whether for example an API key is available. We can set different parameters. We can use all of the same power of pentic but now do it with config. And this is useful and why because let me give you an example. If you set up an environment variable and let's say you're using OpenAI, so you load in your API key. When you don't validate your environment variable variables or API keys with something like pedentic settings, your application will boot up, nothing will break, but then as soon as a request comes in, it processes the data and it's about to hit the open API OpenAI endpoint, it will throw an error. API key is not available. While you could have known that already from the start because when you booted up the implica application, whether that's locally on a server or whatever deployment you're using, when you started it up, the application could have already known that the API key is not available. But if you don't specify it, you only run into the error later. So it's the same principle, right? You want to capture the errors as quickly as possible. So how to do that? If you run, let's see, scroll over here. If you use pideandic settings, let me show you what this looks like. So, I can come in here and let's see, I can create a settings file and I inherit it from base settings. So, the only difference really here is that instead of like from paidic import model, we do from paidic settings import base settings. And this gives us a little bit of a different interface to work with specifically for settings. So now I can say look our in our settings for our model application whatever I need an API key. We have a max connections and we also have a debug parameter that we can set to true or false. So when I come in here and run this you'll find that we get an error because we have not set the API key in here. So this will now not run. So if I for example now set the API key, uh there we go. We do whatever. Now we can safely access everything. So this is a way to set it up. Now usually what happens is when you're working with settings, you don't hardcode everything, but you're working with environment variables. So you can either set the environment variables in your shell, but generally I would recommend just using the environment variables file. So you just load them from ENV file. So I'm going to actually show you what that looks like by taking the example over here. What we're going to do is we are going to create a copy of the example env within this project. Then make sure to call this env. I already have one and I already have my OpenAI key in here. So, what I am going to do is I'm going to simply swap over here and just plug in the settings that I have from the documentation. There we go. And then we go back. There we go again. Okay. So, make sure you have your environment variables file in here. Let's close this out. Let's see. So, now let's walk through what this looks like. So, now what we can do is we can use the setics config dict. Remember this is similar to that config dick that we imported earlier but now just with the settings in here and we can specify our environment variable file. So if we now load this up create the class what you'll now find is that if we run this we can now I have a dummy API key in here. You can see that we can load this from our environment variable. So I can actually I remove the actual API key so we can have a sneak peek in here without you stealing my credentials. So this is a super useful pattern to use. So you have your environment variables. You load everything in here. You specify look what does the structure actually look like? Strings, integers, floats. Usually you don't have to get more specific than that. You just want to check are they present. Then you can load them in a settings variable. And then whenever you want to use that within your application, you can simply use settings. API key. And in this way you don't so you don't have to use for example uh python. n library because this is generally what you would do right you would do I'm not sure if it's installed in here but you would do from you would do and then the import load. So you would then load these environment variables and then get them from the OS. So this is now not needed when you use the settings because you have this settings variable that we can now use to access all of our credentials. And that is pretty much all you need to know for now about paid settings. This is just something you have to play with. There's a little bit more information. I I'll slowly scroll through it. Right. So we covered the following loading from environment variables. We can even use prefixes. So when you load it, you could say my app underscore and then it assumes everything in your EMV file starts with my app API key. Could be useful sometimes. Here's how that works. You can handle secrets. So you could actually say, look, this is actually a secret string, meaning that whenever you print it, it will simply show uh asterisks and it will won't actually print it, but the information is still used when you not print it or log it. So this can also be an added security step that you can use. And a real world example would really be setting up the whole configuration file, loading an API key, setting a base URL, and then a request timeout, maybe a database URL, max connection, pretty much anything that you put in your environment variables. We can add pentic validation on top of that. So like I've said, I'm scrolling down because all of the other things that we've learned work. If you want to learn more, we can either go to the official documentation, paid settings management, or you could scroll through the repository to learn more about it. But with that, let's go to the final section. This is a little bit of a wild card, but something I'm super passionate about because this is where we use Pientic really the most, and it's super critical. like what we're doing and how we are building our client solutions, it would not be possible without paid and structured output like

Structured Output with LLMs

this. And if you've ever worked with large language models, you know that the default is just returning text, right? They're super good at this. You ask something and it will, for example, say product is a laptop. It costs uh $9. 99, the brand is Apple, pure text, but you need structured data. Now, this is not going to be a full introduction on how to work with LLMs and structured data. I have lots of other videos on that. So, if you're interested in that, make sure to check out my channel. But I want to show you how Piantic shows up here as well. So whenever we want to create applications around large language models and for example actually want to do something with the responses from these AI models beyond just sending them back as text to the user but making decisions storing records in a database triggering actions calling tools we need structured data. So we need a way for the model to say look here's the information and this is the structure that we want it in. Now knowing what we know about Python, if we were to set this up without piantic, we would know that we could specify a model, but the AI model could just hallucinate and introduce some kind of like weird data structures in there and Python wouldn't care. It would simply say totally fine, let's run it, put it into the database, make calculations, whatever. Not a problem. Now we understand that with Pentic, we can put a hard stop on that. Super powerful. So here's what that looks like and I'm going to give you a quick example using the open AI library. So there is a little bit of code in here that we're going to run but I'm simply going to use the open AAI SDK. So this is another pip installed should be available within the PI project already over here. This also uh you should also make sure that you now update your environment variable with your OpenAI API key otherwise you cannot run this. We're using GPT40 and we're going to say simple extract the example that we have. We have the new MacBook Pro. This is the price is now available and the data model is name, price, category in stock. That's what we want to get out of it. So if we now run this, let me actually clean this up a little bit. We create our model. We now understand how that works. We run our response. Okay, so now we can actually perform the operation. And now we have a response. And how we managed to do that is we use client responses parse. So this is the open AI SDK. Again this is syntax beyond the scope of this video how that works. But we can specify text format and we can put in product info which is our paidic base model. So that's the cool thing. If we hover over the parse and we can see the text format. This can now be a pyantic model and it will work. So now we can validate that the product that we're getting is actually within the correct format that we want. So we can get a name MacBook Pro. We have a price, we have a category, and we know whether it is in stock, yes or no. So currently this is literally the way to make AI applications somewhat reliable. When you're working with large language models, you really force them. You ask questions. You give them the right information. And then you really constrain them through structured output which is what this called. And Pentic is just the standard way to do that within the Python ecosystem. If you're in the Java JavaScript ecosystem, this is done via Zot. In Python, this is the way to do it. And that's why it's so powerful part of the Agentic ecosystem. So scrolling down a little bit, knowing this, you can also get really creative with this. So I've shown you a basic example, but a common theme that resurfaces throughout this course again and again is that everything works. Everything stacks. We can use nested models. We can use all of the other constraints. We do fields, minimum, maximum lengths. We can create these gigantic constraint models. And the L these LLMs are generally really good at adhering to these models. And one of the cool things is under the hood there is even a retry mechanism that's built into this where it pretty much forces the data into the pyantic model. If that gives an error it will take that human readable error and feed it back to the language model and then it can selfcorrect on top of it. Now depending on which model provider you use or which implementation this can be a little bit different but in most approaches this is possible and this is why it's so reliable under the hood. So we can get very granular here and define the exact schema that we want to extract from the model. And remember this is also where the descriptions are super useful because under the hood what's happening is you have all of the context system prompts user messages combination and then it through text format it essentially injects the JSON schema in there and says look this is what we need and when you add these descriptions remember right so this is under the hood what's going on if we go back to let's see the nested models I think it was at fields and validation so scrolling down over Remember the schema generation, right? If we have the description in here, this is what the language model will see. So this is where the descriptions can really come in handy and they act as a they are part of your prompts. So whenever you have unreliable results, you can try to uh play with the descriptions in the form of prompting it in order to make it more clear as to what it needs to do. Okay. And then scrolling down, there are some more complex extraction examples in here, but this is the most important thing that I still want to show using the literals. Right? So, this is we've already covered this, but I want to show you how powerful this is because up until this point, the literal, we haven't seen that one that much. And we also know that Python doesn't enforce it. But with LLMs, this is super useful because with this we can actually create granular workflows, categories, routers. We can really orchestrate the flow of our application. If it's positive, we go that way. We perform that function. If it's negative, we go that way or escalate to a human. If it's neutral, we do that. Literal is really at the core of doing that. Now, there is you could also do this via Python enums. I'm not going to go into uh that into this video right now. Enums, literals, they both work the same way in when it comes to structured output. But using this and say creating a clear model saying sentiment analysis, we have the text, we have the sentiment, we can now use that within our flow to send that towards open AI in order to specifically said look it can either be positive, negative or neutral. So this is something we do all the time in our application. So here is another production example where we whenever a user ticket comes in. So this is a customer care application. Whenever a ticket comes in, we first want to get clear on the category. We want to give it a sentiment and whether it's order related, whether it needs tracking. And then here you can see how in this case when we go to the categories, you can see in this case we're using enums, but like I've said literal would be exactly the same. This is just a little bit of a different way to uh to kind of like put them into your code, but it's the exact same ID. So, this is something very common. We have categories, we have sentiment in here, the example that we've shown, right? So, very common, something very powerful that you can use to create routers within your application. So, let's go over a quick real world example over here. when with AI whenever you want to uh for example an invoice comes in we have a line item and we have the invoice itself and we want to extract all of the information so this is an OCR task that we use a language model for example we can see we have the uh we have the invoice text in here and you know what let's actually run this entire example because I think this is a cool one wait I don't need to be in this one let's go back to the demo so here you can see let me zoom out a little bit because it's this is quite the file. So, this is cool to play with because we first of all have a we have a nested data model. There's even a property in here. We have the incoming text and then we use structured output in order to force it into an invoice response. And then later down the line, we want to extract all of these totals in here. So, if this is your first time working with AI, this is already really a sneak preview of what AI can do and how cool it is. So, this will take couple of seconds to run. And now we can see zoom in a little bit that we can actually from this invoice information which is just a simple string of text we can get the name company we can get the total amount and whether it's paid all validated through pentantic models in here using the literal. All right and that was the final example of chapter 7 the structured output. So let's quickly go over the summary. We learned quite a lot and by now you are really a paidic pro in my opinion. This is everything you need to know about the library itself. You know how to use it, when to use it and beyond that you can simply just use AI. Now it's just practicing. So we covered all the foundations, right? Really what is it? Why do we need it? Then we explained Python type hints because that's the foundation that you need to understand in order to know what to do with Pentic. We created your first model. We validate we we taught you how to use validation in fields then nested models how you can use that remember right like list order item pentic settings and then even working with structured output using language models. So remember the key patterns, right? Use the imports. Inherit from the base model. Use type hints. Add field notations when you want

Course Summary and Next Steps

to get even more granular. Make fields optional if they can also be empty. Use default values. Use model dump if you want to convert it to a dictionary. And use model validate if you want to do the other way around from a dictionary to a pyantic model. Now next steps. Now you need to practice on your own. So make sure that whenever you are working on a Python project, I can guarantee you for any serious project, there is always room for paid. In my opinion, there's always a way to make your application a little bit more robust by implementing some of these pyentic data models. I even go as far and start to think about my application usually from the point of pyantic data models. That's really how important I find this to build really reliable applications. All right, and that brings us towards the end of this full Pentic crash course. Now, if you want to continue learning and understand how Pyantic fits into the larger ecosystem in Python and how you build AI applications, like I said, you want to check out the Python for AI resource hub and community access. This crash course is part of the larger free series and Python courses that I am creating. Everything is here in here is for free. You can put in zero or put in any tip you want. I want this and you'll be invited. You'll get all of the resources and in here there's a full free course, Python ADC for AI. It has all of the videos that really get you started building effective AI agents in per pure Python. All of the things and all of the methods that we really use in the production systems that I give you really a little bit of a sneak peek on during this crash course. Right? So we run an AI development company and everything that I learn in there I translate to the academy in there. So if that excites you, go check it out and then I want to thank you for watching. I hope you found it valuable. If so, please leave a like and also consider subscribing. And then you can continue with the resources or I will also show two videos over here that I think you will like. So, make sure to check out either one of those or go to the resources.

Другие видео автора — Dave Ebbelaar

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник