!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

*   [Use cases](/v0.1/docs/use_cases/)
    
    *   [SQL](/v0.1/docs/use_cases/sql/)
        
    *   [Chatbots](/v0.1/docs/use_cases/chatbots/)
        
    *   [Extraction](/v0.1/docs/use_cases/extraction/)
        
        *   [Quickstart](/v0.1/docs/use_cases/extraction/quickstart/)
        *   [How-To Guides](/v0.1/docs/use_cases/extraction/how_to/examples/)
            
        *   [Guidelines](/v0.1/docs/use_cases/extraction/guidelines/)
    *   [Query Analysis](/v0.1/docs/use_cases/query_analysis/)
        
    *   [Q&A with RAG](/v0.1/docs/use_cases/question_answering/)
        
    *   [Tool use](/v0.1/docs/use_cases/tool_use/)
        
    *   [Interacting with APIs](/v0.1/docs/use_cases/api/)
    *   [Tabular Question Answering](/v0.1/docs/use_cases/tabular/)
    *   [Graphs](/v0.1/docs/use_cases/graph/)
        
    *   [Summarization](/v0.1/docs/use_cases/summarization/)
    *   [Agent Simulations](/v0.1/docs/use_cases/agent_simulations/)
        
    *   [Autonomous Agents](/v0.1/docs/use_cases/autonomous_agents/)
        
    *   [Code Understanding](/v0.1/docs/use_cases/code_understanding/)
    *   [Audio/Video Structured Extraction](/v0.1/docs/use_cases/media/)

*   [](/v0.1/)
*   [Use cases](/v0.1/docs/use_cases/)
*   [Extraction](/v0.1/docs/use_cases/extraction/)
*   Quickstart

On this page

Quickstart
==========

In this quick start, we will use LLMs that are capable of **function/tool calling** to extract information from text.

info

Extraction using **function/tool calling** only works with [models that support **function/tool calling**](/v0.1/docs/modules/model_io/chat/function_calling/).

Set up[​](#set-up "Direct link to Set up")
------------------------------------------

We will use the new [withStructuredOutput()](/v0.1/docs/integrations/chat/) method available on LLMs that are capable of **function/tool calling**, along with the popular and intuitive [Zod](https://zod.dev/) typing library.

Select a model, install the dependencies for it and set your API keys as environment variables. We’ll use Mistral as an example below:

tip

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

*   npm
*   yarn
*   pnpm

    npm i @langchain/mistralai zod

    yarn add @langchain/mistralai zod

    pnpm add @langchain/mistralai zod

You can also see [this page](/v0.1/docs/integrations/chat/) for an overview of which models support different kinds of structured output.

The Schema[​](#the-schema "Direct link to The Schema")
------------------------------------------------------

First, we need to describe what information we want to extract from the text.

For convenience, we’ll use Zod to define an example schema to extract personal information. You may also use JSON schema directly if you wish.

    import { z } from "zod";// Note that:// 1. Each field is `optional` -- this allows the model to decline to extract it!// 2. Each field uses the `.describe()` method -- this description is used by the LLM.// Having a good description can help improve extraction results.const personSchema = z  .object({    name: z.optional(z.string()).describe("The name of the person"),    hair_color: z      .optional(z.string())      .describe("The color of the person's hair, if known"),    height_in_meters: z      .optional(z.string())      .describe("Height measured in meters"),  })  .describe("Information about a person.");

There are two best practices when defining schema:

1.  Document the **attributes** and the **schema** itself: This information is sent to the LLM and is used to improve the quality of information extraction.
2.  Do not force the LLM to make up information! Above we used `Optional` for the attributes allowing the LLM to output `None` if it doesn’t know the answer.

info

For best performance, document the schema well and make sure the model isn’t force to return results if there’s no information to be extracted in the text.

The Extractor[​](#the-extractor "Direct link to The Extractor")
---------------------------------------------------------------

Let’s create an information extractor using the schema we defined above.

    import {  ChatPromptTemplate,  MessagesPlaceholder,} from "@langchain/core/prompts";// Define a custom prompt to provide instructions and any additional context.// 1) You can add examples into the prompt template to improve extraction quality// 2) Introduce additional parameters to take context into account (e.g., include metadata//    about the document from which the text was extracted.)const SYSTEM_PROMPT_TEMPLATE = `You are an expert extraction algorithm.Only extract relevant information from the text.If you do not know the value of an attribute asked to extract, you may omit the attribute's value.`;const prompt = ChatPromptTemplate.fromMessages([  ["system", SYSTEM_PROMPT_TEMPLATE],  // Please see the how-to about improving performance with  // reference examples.  // new MessagesPlaceholder("examples"),  ["human", "{text}"],]);

We need to use a model that supports function/tool calling.

Please review [the chat model integration page](/v0.1/docs/integrations/chat/) for list of some models that can be used with this API.

    import { ChatMistralAI } from "@langchain/mistralai";const llm = new ChatMistralAI({  model: "mistral-large-latest",  temperature: 0,});const extractionRunnable = prompt.pipe(llm.withStructuredOutput(personSchema));

Let’s test it out!

    const text = "Alan Smith is 6 feet tall and has blond hair.";await extractionRunnable.invoke({ text });

    { name: "Alan Smith", height_in_meters: "1.8288", hair_color: "blond" }

info

Extraction is Generative 🤯

LLMs are generative models, so they can do some pretty cool things like correctly extract the height of the person in meters even though it was provided in feet!

Multiple Entities[​](#multiple-entities "Direct link to Multiple Entities")
---------------------------------------------------------------------------

In **most cases**, you should be extracting a list of entities rather than a single entity.

This can be easily achieved with Zod by nesting models inside one another. Here’s an example using the `personSchema` we defined above:

    const dataSchema = z.object({  people: z.array(personSchema),});

info

Extraction might not be perfect here. Please continue to see how to use **Reference Examples** to improve the quality of extraction, and see the **guidelines** section!

    const extractionRunnable = prompt.pipe(llm.withStructuredOutput(dataSchema));const text =  "My name is Jeff, my hair is black and i am 6 feet tall. Anna has the same color hair as me.";await extractionRunnable.invoke({ text });

    {  people: [    { name: "Jeff", hair_color: "black", height_in_meters: "1.8288" },    { name: "Anna", hair_color: "black" }  ]}

tip

When the schema accommodates the extraction of **multiple entities**, it also allows the model to extract **no entities** if no relevant information is in the text by providing an empty list.

This is usually a **good** thing! It allows specifying **required** attributes on an entity without necessarily forcing the model to detect this entity.

Next steps[​](#next-steps "Direct link to Next steps")
------------------------------------------------------

Now that you understand the basics of extraction with LangChain, you’re ready to proceed to the rest of the how-to guide:

*   [Add Examples](/v0.1/docs/use_cases/extraction/how_to/examples/): Learn how to use **reference examples** to improve performance.
*   [Handle Long Text](/v0.1/docs/use_cases/extraction/how_to/handle_long_text/): What should you do if the text does not fit into the context window of the LLM?
*   [Handle Files](/v0.1/docs/use_cases/extraction/how_to/handle_files/): Examples of using LangChain document loaders and parsers to extract from files like PDFs.
*   [Without function calling](/v0.1/docs/use_cases/extraction/how_to/parse/): Use a prompt based approach to extract with models that do not support **tool/function calling**.
*   [Guidelines](/v0.1/docs/use_cases/extraction/guidelines/): Guidelines for getting good performance on extraction tasks.

* * *

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

[

Previous

Extraction

](/v0.1/docs/use_cases/extraction/)[

Next

Use reference examples

](/v0.1/docs/use_cases/extraction/how_to/examples/)

*   [Set up](#set-up)
*   [The Schema](#the-schema)
*   [The Extractor](#the-extractor)
*   [Multiple Entities](#multiple-entities)
*   [Next steps](#next-steps)

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.