!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/)
            
            *   [Use reference examples](/v0.1/docs/use_cases/extraction/how_to/examples/)
            *   [Handle long text](/v0.1/docs/use_cases/extraction/how_to/handle_long_text/)
            *   [Handle Files](/v0.1/docs/use_cases/extraction/how_to/handle_files/)
            *   [Without function calling](/v0.1/docs/use_cases/extraction/how_to/parse/)
        *   [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/)
*   How-To Guides
*   Without function calling

On this page

Without function calling
========================

LLMs that are able to follow prompt instructions well can be tasked with outputting information in a given format without using function calling.

This approach relies on designing good prompts and then parsing the output of the LLMs to make them extract information well, though it lacks some of the guarantees provided by function calling or JSON mode.

Here, we’ll use Claude which is great at following instructions! See [here for more about Anthropic models](/v0.1/docs/integrations/chat/anthropic/).

First, we’ll install the integration package:

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/anthropic zod zod-to-json-schema

    yarn add @langchain/anthropic zod zod-to-json-schema

    pnpm add @langchain/anthropic zod zod-to-json-schema

    import { ChatAnthropic } from "@langchain/anthropic";const model = new ChatAnthropic({  model: "claude-3-sonnet-20240229",  temperature: 0,});

tip

All the same considerations for extraction quality apply for parsing approach. Review the [guidelines](/v0.1/docs/use_cases/extraction/guidelines/) for extraction quality.

This tutorial is meant to be simple, but generally should really include reference examples to squeeze out performance!

Using StructuredOutputParser[​](#using-structuredoutputparser "Direct link to Using StructuredOutputParser")
------------------------------------------------------------------------------------------------------------

The following example uses the built-in [`StructuredOutputParser`](/v0.1/docs/modules/model_io/output_parsers/types/structured/) to parse the output of a chat model. We use the built-in prompt formatting instructions contained in the parser.

    import { z } from "zod";import { StructuredOutputParser } from "langchain/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";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.");const parser = StructuredOutputParser.fromZodSchema(personSchema);const prompt = ChatPromptTemplate.fromMessages([  [    "system",    "Answer the user query. Wrap the output in `json` tags\n{format_instructions}",  ],  ["human", "{query}"],]);const partialedPrompt = await prompt.partial({  format_instructions: parser.getFormatInstructions(),});

Let’s take a look at what information is sent to the model

    const query = "Anna is 23 years old and she is 6 feet tall";

    const promptValue = await partialedPrompt.invoke({ query });console.log(promptValue.toChatMessages());

    [  SystemMessage {    lc_serializable: true,    lc_kwargs: {      content: "Answer the user query. Wrap the output in `json` tags\n" +        "You must format your output as a JSON value th"... 1444 more characters,      additional_kwargs: {}    },    lc_namespace: [ "langchain_core", "messages" ],    content: "Answer the user query. Wrap the output in `json` tags\n" +      "You must format your output as a JSON value th"... 1444 more characters,    name: undefined,    additional_kwargs: {}  },  HumanMessage {    lc_serializable: true,    lc_kwargs: {      content: "Anna is 23 years old and she is 6 feet tall",      additional_kwargs: {}    },    lc_namespace: [ "langchain_core", "messages" ],    content: "Anna is 23 years old and she is 6 feet tall",    name: undefined,    additional_kwargs: {}  }]

    const chain = partialedPrompt.pipe(model).pipe(parser);await chain.invoke({ query });

    { name: "Anna", hair_color: "", height_in_meters: "1.83" }

Custom Parsing[​](#custom-parsing "Direct link to Custom Parsing")
------------------------------------------------------------------

You can also create a custom prompt and parser with `LangChain` and `LCEL`.

You can use a raw function to parse the output from the model.

In the below example, we’ll pass the schema into the prompt as JSON schema. For convenience, we’ll declare our schema with Zod, then use the [`zod-to-json-schema`](https://github.com/StefanTerdell/zod-to-json-schema) utility to convert it to JSON schema.

    import { z } from "zod";import { zodToJsonSchema } from "zod-to-json-schema";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.");const peopleSchema = z.object({  people: z.array(personSchema),});const SYSTEM_PROMPT_TEMPLATE = [  "Answer the user's query. You must return your answer as JSON that matches the given schema:",  "```json\n{schema}\n```.",  "Make sure to wrap the answer in ```json and ``` tags. Conform to the given schema exactly.",].join("\n");const prompt = ChatPromptTemplate.fromMessages([  ["system", SYSTEM_PROMPT_TEMPLATE],  ["human", "{query}"],]);const extractJsonFromOutput = (message) => {  const text = message.content;  // Define the regular expression pattern to match JSON blocks  const pattern = /```json\s*((.|\n)*?)\s*```/gs;  // Find all non-overlapping matches of the pattern in the string  const matches = pattern.exec(text);  if (matches && matches[1]) {    try {      return JSON.parse(matches[1].trim());    } catch (error) {      throw new Error(`Failed to parse: ${matches[1]}`);    }  } else {    throw new Error(`No JSON found in: ${message}`);  }};

    const query = "Anna is 23 years old and she is 6 feet tall";const promptValue = await prompt.invoke({  schema: zodToJsonSchema(peopleSchema),  query,});promptValue.toString();

    "System: Answer the user's query. You must return your answer as JSON that matches the given schema:\n"... 170 more characters

    const chain = prompt.pipe(model).pipe(extractJsonFromOutput);await chain.invoke({  schema: zodToJsonSchema(peopleSchema),  query,});

    { name: "Anna", age: 23, height: { feet: 6, inches: 0 } }

* * *

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

[

Previous

Handle Files

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

Next

Guidelines

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

*   [Using StructuredOutputParser](#using-structuredoutputparser)
*   [Custom Parsing](#custom-parsing)

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.