<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicolas Munoz on Medium]]></title>
        <description><![CDATA[Stories by Nicolas Munoz on Medium]]></description>
        <link>https://medium.com/@nicolasmunozfidalgo?source=rss-d3c79b03a2f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yoGMHbNmC3sNAa_B.jpg</url>
            <title>Stories by Nicolas Munoz on Medium</title>
            <link>https://medium.com/@nicolasmunozfidalgo?source=rss-d3c79b03a2f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:26:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicolasmunozfidalgo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Transforming Natural Language into Structured Data with OpenAI and LangChain]]></title>
            <link>https://medium.com/@nicolasmunozfidalgo/transforming-natural-language-into-structured-data-with-openai-and-langchain-e9c295be67a7?source=rss-d3c79b03a2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c295be67a7</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nicolas Munoz]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 23:41:57 GMT</pubDate>
            <atom:updated>2024-01-11T23:49:06.986Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transforming Natural Language into Structured Data with LangChain and OpenAI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N45Qb6wR5XvTo4n2sdQvPg.png" /></figure><p>In a world driven by data, the ability to effortlessly translate natural language queries into structured data is a game-changer. By now everyone has experienced the power of Natural Language Processing (NLP) through LLMs to turn text prompts into generated content limited only by one’s creativity. The results are outstanding, and while it’s sufficient to have text responses as output within an interactive interface, the reality is that in order to embed these outputs into our applications we need a structured data object.</p><p>I’m not just talking about wrapping the text response as the value of a single JSON parameter. The power of LLMs allow us to extract meaning from the prompt into separate parameter values, as long as we accurately define each parameter for the LLM to understand what data to extract. For example, given the prompt <strong><em>“The 3,000 sqft. house has 3 bedrooms, 4 bathrooms and features an outdoor swimming pool and a finished basement”</em></strong>, we could extract all the desired features and return the following JSON object:</p><pre>{<br>  &quot;type&quot;: &quot;house&quot;,<br>  &quot;area&quot;: 3000,<br>  &quot;beds&quot;: 3,<br>  &quot;baths&quot;: 4,<br>  &quot;features&quot; : [&quot;outdoor swimming pool&quot;,&quot;finished basement&quot;]<br>}</pre><p>Not only does this return a structured output that can be ingested by our applications, but we could even use the output as the next input in our flow, such as calling an external API or performing additional processing on it.</p><p>This tutorial will go in depth into building an extraction chain as described above using OpenAI and LangChain. Whether you’re a seasoned developer eager to dive into the technical details or a non-technical leader curious about the potential applications of this technology, this tutorial is your gateway to unlocking a new dimension of data interaction.</p><h4>Overview</h4><p>In this tutorial I won’t be covering the installation of Python (which you can find a very thorough explanation at <a href="https://www.datacamp.com/blog/how-to-install-python">datacamp</a> for any OS and setup), or basics about LangChain and constructing LLM chains. If you would like a quick intro to how LangChain works I suggest heading over to their <a href="https://python.langchain.com/docs/get_started/quickstart">Quickstart</a> section to learn the basics.</p><p>This tutorial will focus on the specifics needed to turn a request into structured output that can be used downstream in your applications. Here’s an overview of what we <strong>will</strong> be covering in this tutorial:</p><ol><li>Environment setup — installing the necessary python packages</li><li>Model instantiation — creating the GPT-4 chat model that will be used to interpret our request</li><li>Data schema definition — defining the fields that we want to be output as a Pydantic model with an output parser</li><li>Creating the prompt — the instructions that will be sent to the GPT-4 model</li><li>Creating the chain — the chain that will be invoked on our request and output the structure data schema defined</li><li>Adding memory — in order to have a conversation with our model</li></ol><p>We’ll implement the above for a hypothetical recipe searching app, where the user will be searching for recipes that fit their desired preferences. So one can imagine the user might specify their diet, allergies, ingredients to include and exclude, etc.</p><h4>Let’s dive in!</h4><p>First we’ll need to set up our environment with the necessary packages, our OpenAI API key (if you don’t have one, head over to their website to create an account and generate a key), and creating the model to be used.</p><p>We’ll be using LangChain alongside OpenAI’s GPT-4 model. I tested this approach using GPT-3.5-turbo but the results were not nearly as good. You’re not limited to OpenAI’s models either; feel free to experiment with different ones such as open source models hosted on HuggingFace if you would like (follow LangChain’s <a href="https://python.langchain.com/docs/integrations/platforms/huggingface">Hugging Face Hub tutorial</a>).</p><pre>!pip install langchain openai tiktoken</pre><pre>import os<br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;YOUR_OPENAI_API_KEY&quot;</pre><pre>from langchain.chat_models import ChatOpenAI<br># The temperature impacts the randomness of the output,<br># which in this case we don&#39;t want any randomness so we define it as 0.0<br>temperature = 0.0<br>model = &quot;gpt-4&quot;<br><br>llm = ChatOpenAI(model=model, temperature=temperature)</pre><p>In order for our model to extract structured data from a prompt, we first have to define the structured data schema that we would like to receive as the output. We do this by defining a Pydantic model with the fields we want to extract, along with their definitions. LangChain has a very useful Pydantic output parser that automatically generates the prompt instructions for us based on the model parameters.</p><p><em>Note: It helps if the field names are already fairly self descriptive as the model will get meaning from the name as well as the description.</em></p><p>So let’s define the schema based on the elements a user might search for. We will also create the output parser that will contain the instructions to include in our prompt.</p><pre>from langchain_core.pydantic_v1 import BaseModel, Field<br>from langchain.output_parsers import PydanticOutputParser<br><br>class SearchSchema(BaseModel):<br>    includedIngredients: list[str] = Field(description=&quot;the list of ingredients that should be included in the recipe&quot;)<br>    excludedIngredients: list[str] = Field(description=&quot;the list of ingredients that should be excluded from the recipe&quot;)<br>    allergies: list[str] = Field(description=&quot;the list of allergies specified in the request&quot;)<br>    diets: list[str] = Field(description=&quot;the list of diets specified in the request&quot;)<br>    cuisines: list[str] = Field(description=&quot;the list of cuisines specified in the request&quot;)<br><br>pydantic_parser = PydanticOutputParser(pydantic_object=SearchSchema)<br>format_instructions = pydantic_parser.get_format_instructions()<br><br># The Pydantic model creates the formatting instructions to be included in the prompt<br># Here is the what those instructions look like<br>print(format_instructions)<br>&#39;&#39;&#39;<br>The output should be formatted as a JSON instance that conforms to the JSON schema below.<br><br>As an example, for the schema {&quot;properties&quot;: {&quot;foo&quot;: {&quot;title&quot;: &quot;Foo&quot;, &quot;description&quot;: &quot;a list of strings&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}}, &quot;required&quot;: [&quot;foo&quot;]}<br>the object {&quot;foo&quot;: [&quot;bar&quot;, &quot;baz&quot;]} is a well-formatted instance of the schema. The object {&quot;properties&quot;: {&quot;foo&quot;: [&quot;bar&quot;, &quot;baz&quot;]}} is not well-formatted.<br><br>Here is the output schema:<br>```<br>{&quot;properties&quot;: {&quot;includedIngredients&quot;: {&quot;title&quot;: &quot;Includedingredients&quot;, &quot;description&quot;: &quot;the list of ingredients that should be included in the recipe&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}, &quot;excludedIngredients&quot;: {&quot;title&quot;: &quot;Excludedingredients&quot;, &quot;description&quot;: &quot;the list of ingredients that should be excluded from the recipe&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}, &quot;allergies&quot;: {&quot;title&quot;: &quot;Allergies&quot;, &quot;description&quot;: &quot;the list of allergies specified in the request&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;enum&quot;: [&quot;peanut-free&quot;, &quot;soy-free&quot;, &quot;dairy-free&quot;, &quot;nut-free&quot;], &quot;type&quot;: &quot;string&quot;}}, &quot;diets&quot;: {&quot;title&quot;: &quot;Diets&quot;, &quot;description&quot;: &quot;the list of diets specified in the request&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;enum&quot;: [&quot;vegetarian&quot;, &quot;vegan&quot;, &quot;keto-friendly&quot;, &quot;pescatarian&quot;, &quot;mediterranean&quot;], &quot;type&quot;: &quot;string&quot;}}, &quot;cuisines&quot;: {&quot;title&quot;: &quot;Cuisines&quot;, &quot;description&quot;: &quot;the list of cuisines specified in the request&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}}, &quot;required&quot;: [&quot;includedIngredients&quot;, &quot;excludedIngredients&quot;, &quot;allergies&quot;, &quot;diets&quot;, &quot;cuisines&quot;]}<br>```<br>&#39;&#39;&#39;<br></pre><p>Now that we have our Pydantic schema defined with our formatting instructions, we need to construct the prompt which will be sent to the model. In the prompt we will include three elements:</p><ol><li>A general goal for the model, in this case to parse out a “recipe search request”</li><li>The formatting instructions produced by the PydanticOuptutParser above; this will be included as a placeholder variable</li><li>The user’s request to parse out; also included as a placeholder variable</li></ol><pre>RECIPE_SEARCH_PROMPT = &quot;&quot;&quot;<br>Your goal is to understand and parse out the user&#39;s recipe search request based on their preferences.<br><br>{format_instructions}<br><br>Recipe Search Request:<br>{request}<br>&quot;&quot;&quot;<br><br>prompt = ChatPromptTemplate.from_template(<br>    template=RECIPE_SEARCH_PROMPT,<br>    partial_variables = {<br>        &quot;format_instructions&quot;: format_instructions # passing in the formatting instructions created earlier in place of &quot;format_instructions&quot; placeholder<br>    }<br>)</pre><p>Now that we have our prompt created, we can define the chain to be invoked with our user recipe search request. This is a fairly basic chain that simply passes in the user request to the prompt, which is passed on to the llm that we defined. The LLM will then output the expected result once invoked.</p><pre>full_chain = {&quot;request&quot;: lambda x: x[&quot;request&quot;]} | prompt | llm</pre><p>It’s ready to test! Let’s invoke it with a simple search request and see what it outputs…</p><pre>request = &quot;I am vegetarian and have a peanut allergy. Find me Mexican recipes that have tomatoes but no corn.&quot;<br>result = full_chain.invoke({&quot;request&quot;: request})<br><br>print(result.content)<br>&#39;&#39;&#39;<br>{<br>  &quot;includedIngredients&quot;: [&quot;tomatoes&quot;],<br>  &quot;excludedIngredients&quot;: [&quot;corn&quot;],<br>  &quot;allergies&quot;: [&quot;peanut&quot;],<br>  &quot;diets&quot;: [&quot;vegetarian&quot;],<br>  &quot;cuisines&quot;: [&quot;Mexican&quot;]<br>}<br>&#39;&#39;&#39;<br></pre><p>As you can see from the printed result above, it worked remarkably well. It parsed out all the relevant parts of the request into the correct output fields that we defined, just as expected.</p><p>If our goal of this process is to simply use this as a starting point to call an API, what happens if the API endpoint doesn’t understand what a “peanut” allergy is; perhaps it uses some other terminology and only accepts a specific set of options? We can modify our schema to specify the options that the model is allowed to use by using Literal type instead of a simple List[str]. With a Literal, we’re able to specify the the options that the model can use, similar to having a dropdown with a list of allowed choices.</p><pre>from langchain_core.pydantic_v1 import BaseModel, Field<br>from typing import Literal<br><br>class SearchSchema(BaseModel):<br>    includedIngredients: list[str] = Field(description=&quot;the list of ingredients that should be included in the recipe&quot;)<br>    excludedIngredients: list[str] = Field(description=&quot;the list of ingredients that should be excluded from the recipe&quot;)<br>    allergies: list[Literal[&quot;peanut-free&quot;,&quot;soy-free&quot;,&quot;dairy-free&quot;,&quot;nut-free&quot;]] = Field(description=&quot;the list of allergies specified in the request&quot;)<br>    diets: list[Literal[&quot;vegetarian&quot;,&quot;vegan&quot;,&quot;keto-friendly&quot;,&quot;pescatarian&quot;,&quot;mediterranean&quot;]] = Field(description=&quot;the list of diets specified in the request&quot;)<br>    cuisines: list[str] = Field(description=&quot;the list of cuisines specified in the request&quot;)</pre><p>Let’s test it with a new request…</p><pre>request = &quot;I follow a keto diet and have a peanut allergy. Find me Mexican recipes that have tomatoes but no corn.&quot;<br>result = full_chain.invoke({&quot;request&quot;: request})<br><br>print(result.content)<br>&#39;&#39;&#39;<br>{<br>  &quot;includedIngredients&quot;: [&quot;tomatoes&quot;],<br>  &quot;excludedIngredients&quot;: [&quot;corn&quot;],<br>  &quot;allergies&quot;: [&quot;peanut-free&quot;],<br>  &quot;diets&quot;: [&quot;keto-friendly&quot;],<br>  &quot;cuisines&quot;: [&quot;Mexican&quot;]<br>}<br>&#39;&#39;&#39;</pre><p>As you can see, the model knew to interpret “keto diet” and “peanut allergy” as the allowed options “keto-friendly” and “peanut-free” for the respective categories.</p><p>Now what if we wanted it to behave more like a chat in order to have a fluid conversation that remembers what we’ve said previously? Currently, the user would need to reenter their entire prompt each time with the desired modifications because the current architecture has no concept of chat memory. Let’s modify the above chain to introduce this:</p><ol><li>Update the prompt to include a chat_history placeholder variable</li><li>Insert the chat_history in the chain invocation</li></ol><pre>RECIPE_SEARCH_PROMPT =<br>&quot;&quot;&quot;<br>Your goal is to understand and parse out the user&#39;s recipe search request based on their preferences.<br>            <br>Use the Chat History to build new requests on top of previous ones.<br><br>{format_instructions}<br><br>Chat History:<br>{chat_history}<br><br>Recipe Search Request:<br>{request}<br>&quot;&quot;&quot;</pre><pre>full_chain = {<br>  &quot;request&quot;: lambda x: x[&quot;request&quot;],<br>  &quot;chat_history&quot;: lambda x: x[&quot;chat_history&quot;]<br>} | prompt | llm</pre><pre>chat_history = []<br>request = &quot;I follow a keto diet and have a peanut allergy. Find me Mexican recipes that have tomatoes but no corn.&quot;<br><br># Invoke the chain with an initial request<br>result = full_chain.invoke({<br>  &quot;request&quot;: request,<br>  &quot;chat_history&quot;: chat_history<br>})<br># Save the user&#39;s request to the chat_history to keep track for future use<br>chat_history.append(request)<br><br># Invoke the chain with a secondary request while introducing the newly added chat_history<br>request = &quot;I also dislike mushrooms and cheese&quot;<br>result = full_chain.invoke({<br>  &quot;request&quot;: request,<br>  &quot;chat_history&quot;: chat_history<br>})<br>chat_history.append(request)<br><br>print(result.content)<br>&#39;&#39;&#39;<br>{<br>  &quot;includedIngredients&quot;: [&quot;tomatoes&quot;],<br>  &quot;excludedIngredients&quot;: [&quot;corn&quot;, &quot;mushrooms&quot;, &quot;cheese&quot;],<br>  &quot;allergies&quot;: [&quot;peanut-free&quot;],<br>  &quot;diets&quot;: [&quot;keto-friendly&quot;], <br>  &quot;cuisines&quot;: [&quot;Mexican&quot;]<br>}<br>&#39;&#39;&#39;</pre><p>Including the chat history now allows us to have a conversation with our model, building upon previous requests rather than having to start from scratch every time.</p><h4>Conclusion</h4><p>Now that you’ve learned how to extract important information from natural language queries into a structured response, you can integrate it into your existing applications, or envision entirely new tools, and transform how a user interacts with them.</p><p>You can imagine how this technique could be used to transform how we interact with our favorite applications. Instead of using carefully defined filters with intuitive interfaces, we could simply ask for what we want. You could even develop this further by integrating speech-to-text and allowing the user to speak to their device, removing even more friction from the process. You don’t have to stop at data retrieval either; you could potentially use similar approaches to perform actions on their behalf, such as making ingredient substitutions in a recipe. Generative AI has the potential to revolutionize, not just the content being generated for us, but also the way in which we interact with our applications and devices.</p><p>I hope you enjoyed this tutorial. Let me know your thoughts in the comments below. If you have any questions I’ll be happy to answer them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c295be67a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>