!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Get started](/v0.1/docs/get_started/)
    
    *   [Introduction](/v0.1/docs/get_started/introduction/)
    *   [Installation](/v0.1/docs/get_started/installation/)
    *   [Quickstart](/v0.1/docs/get_started/quickstart/)
*   [LangChain Expression Language](/v0.1/docs/expression_language/)
    
    *   [Get started](/v0.1/docs/expression_language/get_started/)
    *   [Why use LCEL?](/v0.1/docs/expression_language/why/)
    *   [Interface](/v0.1/docs/expression_language/interface/)
    *   [Streaming](/v0.1/docs/expression_language/streaming/)
    *   [How to](/v0.1/docs/expression_language/how_to/routing/)
        
    *   [Cookbook](/v0.1/docs/expression_language/cookbook/)
        
    *   [LangChain Expression Language (LCEL)](/v0.1/docs/expression_language/)
*   [Modules](/v0.1/docs/modules/)
    
    *   [Model I/O](/v0.1/docs/modules/model_io/)
        
        *   [Quickstart](/v0.1/docs/modules/model_io/quick_start/)
        *   [Concepts](/v0.1/docs/modules/model_io/concepts/)
        *   [Prompts](/v0.1/docs/modules/model_io/prompts/)
            
        *   [LLMs](/v0.1/docs/modules/model_io/llms/)
            
        *   [Chat Models](/v0.1/docs/modules/model_io/chat/)
            
        *   [Model I/O](/v0.1/docs/modules/model_io/)
        *   [Output Parsers](/v0.1/docs/modules/model_io/output_parsers/)
            
            *   [Quick Start](/v0.1/docs/modules/model_io/output_parsers/quick_start/)
            *   [Custom output parsers](/v0.1/docs/modules/model_io/output_parsers/custom/)
            *   [Output Parser Types](/v0.1/docs/modules/model_io/output_parsers/types/)
                
    *   [Retrieval](/v0.1/docs/modules/data_connection/)
        
    *   [Chains](/v0.1/docs/modules/chains/)
    *   [Agents](/v0.1/docs/modules/agents/)
        
    *   [More](/v0.1/docs/modules/memory/)
        
*   [Security](/v0.1/docs/security/)
*   [Guides](/v0.1/docs/guides/)
    
*   [Ecosystem](/v0.1/docs/ecosystem/)
    
*   [LangGraph](/v0.1/docs/langgraph/)
*   * * *
    

*   [](/v0.1/)
*   [Modules](/v0.1/docs/modules/)
*   [Model I/O](/v0.1/docs/modules/model_io/)
*   [Output Parsers](/v0.1/docs/modules/model_io/output_parsers/)
*   Quick Start

On this page

Quick Start
===========

Language models output text. But you may often want to get more structured information than just text back. This is where output parsers come in.

Output parsers are classes that help structure language model responses. There are two main methods an output parser must implement:

*   `getFormatInstructions()`: A method which returns a string containing instructions for how the output of a language model should be formatted. You can inject this into your prompt if necessary.
*   `parse()`: A method which takes in a string (assumed to be the response from a language model) and parses it into some structure.

And then one optional one:

`parseWithPrompt()`: A method which takes in a string (assumed to be the response from a language model) and a prompt (assumed to be the prompt that generated such a response) and parses it into some structure. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so.

Get started[​](#get-started "Direct link to Get started")
---------------------------------------------------------

Below we go over one useful type of output parser, the `StructuredOutputParser`.

This output parser can be used when you want to return multiple fields.

**Note:** If you want complex schema returned (i.e. a JSON object with arrays of strings), you can use [Zod Schema](https://zod.dev/) as [detailed here](/v0.1/docs/modules/model_io/output_parsers/types/structured/#structured-output-parser-with-zod-schema).

tip

See [this section for general instructions on installing integration packages](/v0.1/docs/get_started/installation/#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/openai

    yarn add @langchain/openai

    pnpm add @langchain/openai

    import { OpenAI } from "@langchain/openai";import { RunnableSequence } from "@langchain/core/runnables";import { StructuredOutputParser } from "langchain/output_parsers";import { PromptTemplate } from "@langchain/core/prompts";const parser = StructuredOutputParser.fromNamesAndDescriptions({  answer: "answer to the user's question",  source: "source used to answer the user's question, should be a website.",});const chain = RunnableSequence.from([  PromptTemplate.fromTemplate(    "Answer the users question as best as possible.\n{format_instructions}\n{question}"  ),  new OpenAI({ temperature: 0 }),  parser,]);console.log(parser.getFormatInstructions());/*Answer the users question as best as possible.You must format your output as a JSON value that adheres to a given "JSON Schema" instance."JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:```{"type":"object","properties":{"answer":{"type":"string","description":"answer to the user's question"},"sources":{"type":"array","items":{"type":"string"},"description":"sources used to answer the question, should be websites."}},"required":["answer","sources"],"additionalProperties":false,"$schema":"http://json-schema.org/draft-07/schema#"}```What is the capital of France?*/const response = await chain.invoke({  question: "What is the capital of France?",  format_instructions: parser.getFormatInstructions(),});console.log(response);// { answer: 'Paris', source: 'https://en.wikipedia.org/wiki/Paris' }

#### API Reference:

*   [OpenAI](https://api.js.langchain.com/classes/langchain_openai.OpenAI.html) from `@langchain/openai`
*   [RunnableSequence](https://api.js.langchain.com/classes/langchain_core_runnables.RunnableSequence.html) from `@langchain/core/runnables`
*   [StructuredOutputParser](https://api.js.langchain.com/classes/langchain_output_parsers.StructuredOutputParser.html) from `langchain/output_parsers`
*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`

LCEL[​](#lcel "Direct link to LCEL")
------------------------------------

Output parsers implement the [Runnable interface](/v0.1/docs/expression_language/interface/), the basic building block of the LangChain Expression Language (LCEL). This means they support `invoke`, `stream`, `batch`, and `streamLog` calls.

Output parsers accept model outputs (a string or `BaseMessage`) as input and can return an arbitrary type. This is convenient for chaining as shown above.

    await parser.invoke(`\`\`\`json{ answer: 'Paris', sources: [ 'https://en.wikipedia.org/wiki/Paris' ] }\`\`\``);// { answer: 'Paris', sources: [ 'https://en.wikipedia.org/wiki/Paris' ] }

While all parsers support the streaming interface, only certain parsers can stream through partially parsed objects as the model generates them, since this is highly dependent on the output type. Parsers which cannot construct partial objects will simply yield the fully parsed output.

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

Output Parsers

](/v0.1/docs/modules/model_io/output_parsers/)[

Next

Custom output parsers

](/v0.1/docs/modules/model_io/output_parsers/custom/)

*   [Get started](#get-started)
*   [LCEL](#lcel)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.