Information Extraction with LangChain & Kor

Sam Witteveen · Beginner ·🧠 Large Language Models ·3y ago

Key Takeaways

The video demonstrates information extraction using LangChain and Kor with large language models, covering topics such as defining schemas, using pedantic classes, and validating output. It provides a comprehensive overview of how to extract structured information from text using these tools.

Full Transcript

so in the last video we looked at how to make some market research type content through getting two agents to converse with each other if you haven't watched that already go and have a look at that one of the big challenges then is we've now got a bunch of text files with information that we probably want to get into some kind of structured format if we were doing some kind of market research where people are talking about a product and qualities of that product that kind of thing then we want to be able to extract those out and be able to put them in some kind of report or some kind of structured data to make use of that so today what I want to do is go through a package called core which is kind of like an add-on to a lang chain which is basically built for information extraction so what I'm going to do is go through some of the examples in here and then I'm going to show you at the end of using it for a real world Goose case of where I take the conversation that I had about two people talking about restaurants and we're going to extract out the restaurants their locations the dishes that they had in there so this is the package core you can see here it's still in a reasonably uh nascent stage I would say there's a whole bunch of things that have been added and my guess is that it may evolve over time already though it's very useful to use one of the big challenges that we have in natural language processing is if we want to make a nerd detector or something like that where we're doing a named entity a recognition or even any sort of extraction information extraction thing we usually need to train up a model and to do that we're going to need a decent amount of data so if we were doing this kind of task and we had the data already that was all nicely labeled oh we would probably go and train up a bird Model A distilled model something along those lines maybe a small T5 model to extract that information and label it nicely as we go along the challenge is what if you're doing something where you do don't have any data to make a model in the first place and this is where a tool like core comes in this allows us to use a large language model in this case we're going to be using the chat open AI model to basically go through and extract out information that we can then use for either creating our reports or even eventually for making a data set for us to make a proper nerve model later on so let's just jump in so this is using Lang chain under the hood it's basically got a simple sort of workflow of where you go through you get your text you clean it up you split it up you define a schema that you're going to use to go through it and then you give it to the large language model to go through and extract out what it is that you want to have so you can see here we're basically bringing in some sort of standard stuff we're going to bring in the link chain callbacks so we can see how much money we're spending on this from core we're going to have this change which is the fundamental chain the create extraction chain there they then have core nodes so these are type of things that you can extract from here so you can define an object which we'll look at we can have text we can have numbers in there we can also have some other structured things which I'm not going through today and then one of the things that we'll finish up with is showing you that we can actually Define pedantic classes and use them to do or to assist with the extraction of data from this so let's jump in and look at some simple examples so first off we just Define a large language model and then we need to define the schema of how we're going to basically deal with this so we're going to have this is just some examples taken from their documentation in this case we're going to basically have an object which is going to be extracting out personal information we give it a description so the description is going to help the large language model to work out what to what to basically extract and also we're going to give examples of things which will then also help the large language model to work out what to extract so things like the description and the examples are things that are going to go into your income text learning in the prompts to be able to make it easier to extract this stuff out so here we've basically got we're going to extract out personal information the attributes we're going to get we Define this one as a text and this is going to be first name the description is the first name of the person an example John Smith went to the store here's John is what we would extract out for that last name we would extract out this age we can extract out that as well and then we can give it some sort of full examples of where if we had a sentence that had these in it this is what we would expect it to extract out so John Smith was 23 sure enough John Smith age 23 Jane Doe age five and that it you know extracts that out now to make the chain for this the basic chain we're just passing in the llm and the schema that we've got here and then once we've got that if we want to look at the prompt that it's actually using we can see the prompt here is basically your goal is to extract structured information from the user's input that matches the form described below goes on there we can then see also that it's giving us an example of what these are with the description for each of these and then we've got some you know some examples of the actual extraction for these that are also being put in there so this is giving us the ink context learning then our text will go in here the output will then generate so sure enough we can see if we pass in David Jones was 33 year old a long time ago it's able to pick out David Jones age 34 right from that so this is like the most basic example that you can do we can then start to Nest things as well so we can actually go into the schema and Nest a bunch of things into the scheme now to do this we we're going to end up using Json so above was using the CSV extraction by default here we can look at this doing the Json so here we're basically getting a from address you can see here we're getting the text we're getting Street city state ZIP code country and then we give it an example we give it a two address and then we can see that for the schema we can basically just pass in that okay we want to basically get the the full name of a person and then we want to get the the from address and the two address so those are being nested in to the full schema object here okay so to use nested objects we need to basically move away from the CSV encoder class to Json encoder class here same deal we're basically just setting this up passing in the LM the schema here we're just defining the encoder class and an input formatter if we're going to have something for doing that and sure enough we've got our prompt again and we can see that okay The Prompt is showing what we would expect this to be out we can see now it's saying please output the extracted information in Json format do not output anything except the extracted information do not add any clarifying information do not add any fields that are not in the same schema if the text contains attributes that do not appear in the schema please ignore them all output must be in Json format so you can see it's a pretty long prompt that we've got going in there we've then got our ICL going on here and then finally we've got our output so sure enough now if we use that and we say alisto moved from New York to Boston MA while Bob Smith did the opposite so we can see that okay it's got the person's name Alice doe to address Boston State Massachusetts person Bob Smith to address City New York so it was able to extract those out in this case and you can see that it didn't add the state for New York because that wasn't mentioned uh in here whereas uh the state for Alice moving to was mentioned in here so these are the basic examples of it the way that I found myself using it in the real world is to use it with pedantic classes so if you haven't come across pedantic before this is basically just a class system it's used a lot for fast API for sort of defining inputs and outputs to a certain class of what you would expect it what you expect to get out of this so here I'm just basically quickly loading up the text file from the camel extraction that we did yesterday and you can see just printing out a little bit of that here you can see this is basically just a conversation where they're talking about things we can see that they've mentioned a restaurant there if we and we can see that that restaurant is in Spain they go on to mention dishes and other restaurants and other places so what I want here is to be able to extract out that information about the restaurants their location perhaps their style of food and the dishes that people liked from there so I've basically just brought this in I've just done some splitting with it so that we've got it split up it turns out this one is quite small so it's not a big problem but showing you if you wanted to do a full-size dock you could do that we set up the llm again and here's the new bit where we've got so we're setting up this pedantic class here and so we're basically saying this is a class of restaurant the restaurant is going to have a name with a string field attached to this our description is the name of the restaurant a location so this is going to be optional so the name must be there is what we're after right this is uh the thing the whole reason for using the the pedantic class is it's going to force the model to stick to this sort of group of information more and it's also going to allow us to validate that information now not validate in the sense of checking is this uh real information or fake information just validating is this in the right format so that we're getting out for each restaurant we're getting out it's like we're getting out an instantiation of this class with these fields and some of them are optional you can see that location style top dish are optional but some of them like the name not optional right that has to be in there so we've basically got that we've got this validator that says okay this must not be empty in here and then we can see here we're basically saying from the pedantic we're extracting this out with the extraction validator we're passing in the class of restaurant we're passing in some descriptions and examples and just setting this up and we're saying that many equals true means that we can have it's not just one restaurant we're looking for we're looking for multiple restaurants in here okay so now we basically set this up I'm going to go back to the CSV encoder in this case they mention in the actual documentation and I found this to be true as well that the Json decoder doesn't seem to do as well as the CSV encoder so if you don't have something that's nested if you don't have something that needs the Json decoder you're probably better to go for the CSV decoder in here so I pass in the large language model I pass in the schema I passion our extraction validator that we've just defined up here and then we're going to run this through and so you can see here we're going to basically pass in let's just look at the prompt uh The Prompt is very similar to what we see before we can see this time you know it's outputting it in CSV format so it's using the pipe character as a delimiter here and we can see that the rest is kind of similar in that you know do not add any clarifying information you must follow the schema above Etc and then we've got our example in there now I could probably add quite a few more examples in there to get the in context learning to be better for this so that's something you want to experiment with all right I now basically run this I run this as we go through it and just running the the docs through you can see that it cost just half a cent to run this and then now sure enough I'm getting this formatted stuff out so okay I want to actually make that human readable so here I've basically just written a little function to basically take this in and put it as human readable and sure enough you can see now when we run that through that function we now see that we're getting restaurant name we're getting the restaurant the location Girona Spain I'm guessing Cuisine not specified in this case the top dish and we can see that okay Noma Copenhagen top dish fermented berries and ants dessert we can see one of the restaurants that's mentioned from Mexico from Bangkok we can see quite a famous restaurant Osteria francescana from moderna in Italy and if you look at it this is one of their famous desserts there and it's not the kind of language that we would expect to be associated with a dessert yet this is actually what it is called and so it's been able to extract that out quite nicely in there and we can see that it's got Attica now I'm pretty sure that it got all of the uh restaurants that were mentioned in there so it's done a pretty good job of going through that if we wanted to put that in a panda's data frame just give it a structured data we could then you know basically just put it into uh Panda's data frame we've got it like this run this from this point you could just use a nice prompt to take this as information in and write up a report that would mention these things and use them in some way like that so you've basically automated everything from the at this stage of creating the conversation extracting the information out of the conversation through to writing up a report based on this and obviously you would have the report once you've done many of these pass through that kind of thing so just to show you that how the the pedantic validation helps out I've done one where we haven't used the the same validation here and we can see that the output so this is basically just going through we're just using uh a sort of just we're just passing in the restaurant pop thing we're not passing in the validator so it's just going to come out with a sort of blank validator where it's not using any of the examples that we had if we basically run this through you'll see that the output now is yes it does get the the first ones quite nicely but then it starts making up ones or getting sort of partial ones here you can see it's got the restaurant for Melbourne Australia but it hasn't got Attica as the name for that in there and we can see in other ones it's got a deconstructed lemon tart but it doesn't have you know the name of the restaurant the same here it's sort of repeating some of the ones up here so that's where the validation is not being enforced in the same way so this sort of shows you that using the pedantic classes and and putting good examples in there it really helps you to get some good results out and just the results out that you want not other things as well now this is far from perfect and it will make mistakes I really appreciate that the author of the package mentions that one of the things that's really good at is making mistakes I do find though you know it is used full and if you play around with it with descriptions giving it enough in context learning you can get some very good results out of this for real world sorts of things and then you could use this to build a proper nerve model with a Burt model that kind of thing going forward anyway as always if you've got questions please put them in the comments below if you found this useful please click like And subscribe I will talk to you in the next video bye for now

Original Description

Colab : https://colab.research.google.com/drive/1Hj55qsYgHX9mMC_81BwpjORIEjajxOPp?usp=sharing In this video I go through examples of how you can extract information out of text using a LLM with LangChain and Kor For more tutorials on using LLMs and building Agents, check out my Patreon: Patreon: https://www.patreon.com/SamWitteveen Twitter: https://twitter.com/Sam_Witteveen My Links: Linkedin: https://www.linkedin.com/in/samwitteveen/ Github: https://github.com/samwit/langchain-tutorials https://github.com/samwit/llm-tutorials 00:00 Previous Video 00:38 Intro to Kor 02:38 Basic examples for text extraction 08:45 Pydantic Classes for extraction
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Sam Witteveen · Sam Witteveen · 0 of 60

← Previous Next →
1 LangChain Basics Tutorial #1 - LLMs & PromptTemplates with Colab
LangChain Basics Tutorial #1 - LLMs & PromptTemplates with Colab
Sam Witteveen
2 LangChain Basics Tutorial #2 Tools and Chains
LangChain Basics Tutorial #2 Tools and Chains
Sam Witteveen
3 ChatGPT API Announcement & Code Walkthrough with LangChain
ChatGPT API Announcement & Code Walkthrough with LangChain
Sam Witteveen
4 Trying Out Flan 20B with UL2 - Working in Colab with 8Bit Inference
Trying Out Flan 20B with UL2 - Working in Colab with 8Bit Inference
Sam Witteveen
5 LangChain - Conversations with Memory (explanation & code walkthrough)
LangChain - Conversations with Memory (explanation & code walkthrough)
Sam Witteveen
6 LangChain Chat with Flan20B
LangChain Chat with Flan20B
Sam Witteveen
7 LangChain - Using Hugging Face Models locally (code walkthrough)
LangChain - Using Hugging Face Models locally (code walkthrough)
Sam Witteveen
8 PAL : Program-aided Language Models with LangChain code
PAL : Program-aided Language Models with LangChain code
Sam Witteveen
9 Building a Summarization System with LangChain and GPT-3 - Part 1
Building a Summarization System with LangChain and GPT-3 - Part 1
Sam Witteveen
10 Building a Summarization System with LangChain and GPT-3 - Part 2
Building a Summarization System with LangChain and GPT-3 - Part 2
Sam Witteveen
11 Microsoft's Visual ChatGPT using LangChain
Microsoft's Visual ChatGPT using LangChain
Sam Witteveen
12 Building a Summarization System with LangChain - Part 3 Using ChatGPT Turbo
Building a Summarization System with LangChain - Part 3 Using ChatGPT Turbo
Sam Witteveen
13 LangChain Agents - Joining Tools and Chains with Decisions
LangChain Agents - Joining Tools and Chains with Decisions
Sam Witteveen
14 Investigating Alpaca 7B - Finetuned LLaMa LLM
Investigating Alpaca 7B - Finetuned LLaMa LLM
Sam Witteveen
15 Comparing LLMs with LangChain
Comparing LLMs with LangChain
Sam Witteveen
16 Running Alpaca7B in Colab
Running Alpaca7B in Colab
Sam Witteveen
17 How to finetune your own Alpaca 7B
How to finetune your own Alpaca 7B
Sam Witteveen
18 How to make a custom dataset like Alpaca7B
How to make a custom dataset like Alpaca7B
Sam Witteveen
19 Understanding Constitutional AI - the paper and key concepts
Understanding Constitutional AI - the paper and key concepts
Sam Witteveen
20 Using Constitutional AI in LangChain
Using Constitutional AI in LangChain
Sam Witteveen
21 Talking to Alpaca with LangChain - Creating an Alpaca Chatbot
Talking to Alpaca with LangChain - Creating an Alpaca Chatbot
Sam Witteveen
22 Text-to-video-synthesis with Diffusers and Colab
Text-to-video-synthesis with Diffusers and Colab
Sam Witteveen
23 Meet Dolly the new Alpaca model
Meet Dolly the new Alpaca model
Sam Witteveen
24 Checking out the Cerebras-GPT family of models
Checking out the Cerebras-GPT family of models
Sam Witteveen
25 A Step-by-Step Guide to Fine-Tuning Your Dolly Model (tutorial)
A Step-by-Step Guide to Fine-Tuning Your Dolly Model (tutorial)
Sam Witteveen
26 Is GPT4All your new personal ChatGPT?
Is GPT4All your new personal ChatGPT?
Sam Witteveen
27 Raven - RWKV-7B RNN's LLM Strikes Back
Raven - RWKV-7B RNN's LLM Strikes Back
Sam Witteveen
28 Talk to your CSV & Excel with LangChain
Talk to your CSV & Excel with LangChain
Sam Witteveen
29 Vicuna - 90% of ChatGPT quality by using a new dataset?
Vicuna - 90% of ChatGPT quality by using a new dataset?
Sam Witteveen
30 Koala Revealed: The ChatGPT Alternative You Need to Know! 🔍
Koala Revealed: The ChatGPT Alternative You Need to Know! 🔍
Sam Witteveen
31 Running Koala for free in Colab. Your own personal ChatGPT? (tutorial)
Running Koala for free in Colab. Your own personal ChatGPT? (tutorial)
Sam Witteveen
32 BabyAGI: Discover the Power of Task-Driven Autonomous Agents!
BabyAGI: Discover the Power of Task-Driven Autonomous Agents!
Sam Witteveen
33 Auto-GPT - How to Automate a Task Based AI with GPT-4
Auto-GPT - How to Automate a Task Based AI with GPT-4
Sam Witteveen
34 Improve your BabyAGI with LangChain
Improve your BabyAGI with LangChain
Sam Witteveen
35 Generative Agents - Deep Dive and GPT-4 Recreation
Generative Agents - Deep Dive and GPT-4 Recreation
Sam Witteveen
36 GPT4ALLv2: The Improvements and Drawbacks You Need to Know!
GPT4ALLv2: The Improvements and Drawbacks You Need to Know!
Sam Witteveen
37 Dolly 2.0 by Databricks: Open for Business but is it  Ready to Impress!
Dolly 2.0 by Databricks: Open for Business but is it Ready to Impress!
Sam Witteveen
38 Red Pajama - Operation: Freeing LLaMA
Red Pajama - Operation: Freeing LLaMA
Sam Witteveen
39 Investigating Open Assistant - Models, Datasets and Addons
Investigating Open Assistant - Models, Datasets and Addons
Sam Witteveen
40 Investigating MiniGPT-4 - The Secret behind GPT-V?
Investigating MiniGPT-4 - The Secret behind GPT-V?
Sam Witteveen
41 Stable LM 3B - The new tiny kid on the block.
Stable LM 3B - The new tiny kid on the block.
Sam Witteveen
42 Bard can now code and put that code in Colab for you.
Bard can now code and put that code in Colab for you.
Sam Witteveen
43 Checking out Bark: a Text to Speech system by Suno AI
Checking out Bark: a Text to Speech system by Suno AI
Sam Witteveen
44 Fine-tuning LLMs with PEFT and LoRA
Fine-tuning LLMs with PEFT and LoRA
Sam Witteveen
45 Master PDF Chat with LangChain - Your essential guide to queries on documents
Master PDF Chat with LangChain - Your essential guide to queries on documents
Sam Witteveen
46 Using LangChain with DuckDuckGO Wikipedia & PythonREPL Tools
Using LangChain with DuckDuckGO Wikipedia & PythonREPL Tools
Sam Witteveen
47 Building Custom Tools and Agents with LangChain (gpt-3.5-turbo)
Building Custom Tools and Agents with LangChain (gpt-3.5-turbo)
Sam Witteveen
48 StableVicuna: The New King of Open ChatGPTs?
StableVicuna: The New King of Open ChatGPTs?
Sam Witteveen
49 WizardLM: Evolving Instruction Datasets to Create a Better Model
WizardLM: Evolving Instruction Datasets to Create a Better Model
Sam Witteveen
50 LaMini-LM - Mini Models Maxi Data!
LaMini-LM - Mini Models Maxi Data!
Sam Witteveen
51 Finding the Best Free ChatGPT
Finding the Best Free ChatGPT
Sam Witteveen
52 MPT-7B - The First Commercially Usable Fully Trained LLaMA Style Model
MPT-7B - The First Commercially Usable Fully Trained LLaMA Style Model
Sam Witteveen
53 LangChain Retrieval QA Over Multiple Files with ChromaDB
LangChain Retrieval QA Over Multiple Files with ChromaDB
Sam Witteveen
54 LangChain Retrieval QA with Instructor Embeddings & ChromaDB for PDFs
LangChain Retrieval QA with Instructor Embeddings & ChromaDB for PDFs
Sam Witteveen
55 LangChain + Retrieval Local LLMs for Retrieval QA - No OpenAI!!!
LangChain + Retrieval Local LLMs for Retrieval QA - No OpenAI!!!
Sam Witteveen
56 Transformers Agent - Is this Hugging Face's LangChain Competitor?
Transformers Agent - Is this Hugging Face's LangChain Competitor?
Sam Witteveen
57 StarCoder - The LLM to make you a coding star?
StarCoder - The LLM to make you a coding star?
Sam Witteveen
58 Testing Starcoder for Reasoning with PAL
Testing Starcoder for Reasoning with PAL
Sam Witteveen
59 The New Wizards - Unfiltered & Unaligned
The New Wizards - Unfiltered & Unaligned
Sam Witteveen
60 Camel + LangChain for Synthetic Data & Market Research
Camel + LangChain for Synthetic Data & Market Research
Sam Witteveen

This video teaches how to extract information from text using LangChain and Kor with large language models. It covers defining schemas, using pedantic classes, and validating output, providing a comprehensive overview of information extraction techniques.

Key Takeaways
  1. Define a large language model
  2. Define the schema of how to deal with the text
  3. Use Core nodes to extract information
  4. Use pedantic classes to assist with data extraction
  5. Pass in LM and schema to LangChain
  6. Expect output in JSON format
  7. Create a pedantic class to define the schema and format of the expected data
  8. Use the extraction validator to extract the desired information from the text
💡 Using pedantic classes and validation can significantly improve the accuracy and reliability of information extraction tasks

Related Reads

📰
The Most Dangerous Question in the Age of AI
In the age of AI, we must remember to ask the right questions, as machines can generate any answer, but not necessarily the correct one
Medium · AI
📰
Automating LLM Memory Validation with Pytest & Redis: 45x Faster Regression Testing
Learn to automate LLM memory validation using Pytest and Redis for 45x faster regression testing
Dev.to · BAOFUFAN
📰
SQLite + Vector Search: The Dependency-Free AI Memory Stack
Learn how to build a dependency-free AI memory stack using SQLite and vector search, enabling efficient and lightweight AI applications
Dev.to · Robert Pelloni
📰
Drop one tool from your request: one GPT-5 version keeps 76% of it cached, another keeps nothing
Optimize LLM performance with prompt caching, which can reduce token costs by recognizing previously seen prompts
Dev.to AI

Chapters (4)

Previous Video
0:38 Intro to Kor
2:38 Basic examples for text extraction
8:45 Pydantic Classes for extraction
Up next
5 Levels of AI Agents - From Simple LLM Calls to Multi-Agent Systems
Dave Ebbelaar (LLM Eng)
Watch →