avatarLaxfed Paulacy

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2483

Abstract

ser</span>, <span class="hljs-title class_">OutputFixingParser</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">"langchain/output_parsers"</span>;

<span class="hljs-keyword">const</span> outputParser = <span class="hljs-title class_">StructuredOutputParser</span>.<span class="hljs-title function_">fromZodSchema</span>( z.<span class="hljs-title function_">array</span>( z.<span class="hljs-title function_">object</span>({ <span class="hljs-attr">fields</span>: z.<span class="hljs-title function_">object</span>({ <span class="hljs-title class_">Name</span>: z.<span class="hljs-title function_">string</span>().<span class="hljs-title function_">describe</span>(<span class="hljs-string">"The name of the country"</span>), <span class="hljs-title class_">Capital</span>: z.<span class="hljs-title function_">string</span>().<span class="hljs-title function_">describe</span>(<span class="hljs-string">"The country's capital"</span>) }) }) ).<span class="hljs-title function_">describe</span>(<span class="hljs-string">"An array of Airtable records, each representing a country"</span>) );

<span class="hljs-keyword">const</span> chatModel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ChatOpenAI</span>({ <span class="hljs-attr">modelName</span>: <span class="hljs-string">"gpt-4"</span>, <span class="hljs-comment">// Or gpt-3.5-turbo</span> <span class="hljs-attr">temperature</span>: <span class="hljs-number">0</span> <span class="hljs-comment">// For best results with the output fixing parser</span> });

<span class="hljs-keyword">const</span> outputFixingParser = <span class="hljs-title class_">OutputFixingParser</span>.<span class="hljs-title function_">fromLLM</span>( chatModel, outputParser );

<span class="hljs-keyword">const</span> prompt = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PromptTemplate</span>({ <span class="hljs-attr">template</span>: <span class="hljs-string">Answer the user's question as best you can:\n{format_instructions}\n{query}</span>, <span class="hljs-attr">inputVariables</span>: [<span class="hljs-string">'query'</span>], <span class="hljs-attr">partialVariables</span>: { <span class="hljs-attr">format_instructions</span>: outputFixingParser.<span class="hljs-title function_">getFormatInstructions</span>() } });

<span class="hljs-comment">// For those unfamiliar with LangChain, a clas

Options

s used to call LLMs</span> <span class="hljs-keyword">const</span> answerFormattingChain = <span class="hljs-keyword">new</span> <span class="hljs-title class_">LLMChain</span>({ <span class="hljs-attr">llm</span>: chatModel, <span class="hljs-attr">prompt</span>: prompt, <span class="hljs-attr">outputKey</span>: <span class="hljs-string">"records"</span>, <span class="hljs-comment">// For readability - otherwise the chain output will default to a property named "text"</span> <span class="hljs-attr">outputParser</span>: outputFixingParser });

<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> answerFormattingChain.<span class="hljs-title function_">call</span>({ <span class="hljs-attr">query</span>: <span class="hljs-string">"List 5 countries."</span> });

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(result.<span class="hljs-property">records</span>, <span class="hljs-literal">null</span>, <span class="hljs-number">2</span>));</pre></div><p id="e343">In the code above, we first define a Zod schema to specify the structure of the expected output. Then, we create an output fixing parser using LangChain’s capabilities, and finally, we call the LLM chain to obtain the structured data output.</p><p id="e0f4">With this solution, you can easily handle badly formatted outputs from LLMs, ensuring that the data is structured and ready for use in the next steps of your pipeline.</p><div id="3ad9" class="link-block"> <a href="https://readmedium.com/langchain-plan-and-execute-agents-5f5ff46b9499"> <div> <div> <h2>LANGCHAIN — Plan and Execute Agents</h2> <div><h3># Technology makes it possible for people to gain control over everything, except over technology. — John Tudor.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*nu7ZXSdSXeo6aCLEJYoZpg.jpeg)"></div> </div> </div> </a> </div><p id="9893">By using LangChain’s output fixing parsers, you can make the most out of GPT-4’s capabilities while ensuring that the output is in a structured format, ready for further processing or storage.</p></article></body>

LANGCHAIN — How to Make GPT-4 Output Structured Data Using LangChain

The best way to predict the future is to invent it. — Alan Kay.

If you’re looking to make GPT-4 output structured data, LangChain provides a solution through its output fixing parsers, which allow for handling badly formatted outputs using a focused prompt. Below is a step-by-step guide on how to achieve this using LangChain.

First, install the required dependencies by running the following commands:

yarn add langchain
yarn add zod

Next, you can use the following code snippet to implement the solution:

import { z } from "zod";
import { ChatOpenAI } from "langchain/chat_models/openai";
import { PromptTemplate } from "langchain/prompts";
import { LLMChain } from "langchain/chains";
import {
  StructuredOutputParser,
  OutputFixingParser
} from "langchain/output_parsers";

const outputParser = StructuredOutputParser.fromZodSchema(
  z.array(
    z.object({
      fields: z.object({
        Name: z.string().describe("The name of the country"),
        Capital: z.string().describe("The country's capital")
      })
    })
  ).describe("An array of Airtable records, each representing a country")
);

const chatModel = new ChatOpenAI({
  modelName: "gpt-4", // Or gpt-3.5-turbo
  temperature: 0 // For best results with the output fixing parser
});

const outputFixingParser = OutputFixingParser.fromLLM(
  chatModel,
  outputParser
);

const prompt = new PromptTemplate({
  template: `Answer the user's question as best you can:\n{format_instructions}\n{query}`,
  inputVariables: ['query'],
  partialVariables: {
    format_instructions: outputFixingParser.getFormatInstructions()
  }
});

// For those unfamiliar with LangChain, a class used to call LLMs
const answerFormattingChain = new LLMChain({
  llm: chatModel,
  prompt: prompt,
  outputKey: "records", // For readability - otherwise the chain output will default to a property named "text"
  outputParser: outputFixingParser
});

const result = await answerFormattingChain.call({
  query: "List 5 countries."
});

console.log(JSON.stringify(result.records, null, 2));

In the code above, we first define a Zod schema to specify the structure of the expected output. Then, we create an output fixing parser using LangChain’s capabilities, and finally, we call the LLM chain to obtain the structured data output.

With this solution, you can easily handle badly formatted outputs from LLMs, ensuring that the data is structured and ready for use in the next steps of your pipeline.

By using LangChain’s output fixing parsers, you can make the most out of GPT-4’s capabilities while ensuring that the output is in a structured format, ready for further processing or storage.

Make
Langchain
Output
Data
Using
Recommended from ReadMedium