*   [](/v0.2/)
*   [How-to guides](/v0.2/docs/how_to/)
*   How to use reference examples when doing extraction

On this page

How to use reference examples when doing extraction
===================================================

The quality of extractions can often be improved by providing reference examples to the LLM.

Data extraction attempts to generate structured representations of information found in text and other unstructured or semi-structured formats. [Tool-calling](/v0.2/docs/concepts/#functiontool-calling) LLM features are often used in this context. This guide demonstrates how to build few-shot examples of tool calls to help steer the behavior of extraction and similar applications.

tip

While this guide focuses how to use examples with a tool calling model, this technique is generally applicable, and will work also with JSON more or prompt based techniques.

LangChain implements a [tool-call attribute](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.ai.AIMessage.html#langchain_core.messages.ai.AIMessage.tool_calls) on messages from LLMs that include tool calls. See our [how-to guide on tool calling](/v0.2/docs/how_to/tool_calling/) for more detail. To build reference examples for data extraction, we build a chat history containing a sequence of:

*   [HumanMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.human.HumanMessage.html) containing example inputs;
*   [AIMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.ai.AIMessage.html) containing example tool calls;
*   [ToolMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.tool.ToolMessage.html) containing example tool outputs.

LangChain adopts this convention for structuring tool calls into conversation across LLM model providers.

First we build a prompt template that includes a placeholder for these messages:

    from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder# 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.)prompt = ChatPromptTemplate.from_messages(    [        (            "system",            "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, return null for the attribute's value.",        ),        # ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓        MessagesPlaceholder("examples"),  # <-- EXAMPLES!        # ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑        ("human", "{text}"),    ])

**API Reference:**[ChatPromptTemplate](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.chat.ChatPromptTemplate.html) | [MessagesPlaceholder](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.chat.MessagesPlaceholder.html)

Test out the template:

    from langchain_core.messages import (    HumanMessage,)prompt.invoke(    {"text": "this is some text", "examples": [HumanMessage(content="testing 1 2 3")]})

**API Reference:**[HumanMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.human.HumanMessage.html)

    ChatPromptValue(messages=[SystemMessage(content="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, return null for the attribute's value."), HumanMessage(content='testing 1 2 3'), HumanMessage(content='this is some text')])

Define the schema[​](#define-the-schema "Direct link to Define the schema")
---------------------------------------------------------------------------

Let's re-use the person schema from the [extraction tutorial](/v0.2/docs/tutorials/extraction/).

    from typing import List, Optionalfrom langchain_core.pydantic_v1 import BaseModel, Fieldfrom langchain_openai import ChatOpenAIclass Person(BaseModel):    """Information about a person."""    # ^ Doc-string for the entity Person.    # This doc-string is sent to the LLM as the description of the schema Person,    # and it can help to improve extraction results.    # Note that:    # 1. Each field is an `optional` -- this allows the model to decline to extract it!    # 2. Each field has a `description` -- this description is used by the LLM.    # Having a good description can help improve extraction results.    name: Optional[str] = Field(..., description="The name of the person")    hair_color: Optional[str] = Field(        ..., description="The color of the person's hair if known"    )    height_in_meters: Optional[str] = Field(..., description="Height in METERs")class Data(BaseModel):    """Extracted data about people."""    # Creates a model so that we can extract multiple entities.    people: List[Person]

**API Reference:**[ChatOpenAI](https://api.python.langchain.com/en/latest/chat_models/langchain_openai.chat_models.base.ChatOpenAI.html)

Define reference examples[​](#define-reference-examples "Direct link to Define reference examples")
---------------------------------------------------------------------------------------------------

Examples can be defined as a list of input-output pairs.

Each example contains an example `input` text and an example `output` showing what should be extracted from the text.

info

This is a bit in the weeds, so feel free to skip.

The format of the example needs to match the API used (e.g., tool calling or JSON mode etc.).

Here, the formatted examples will match the format expected for the tool calling API since that's what we're using.

    import uuidfrom typing import Dict, List, TypedDictfrom langchain_core.messages import (    AIMessage,    BaseMessage,    HumanMessage,    SystemMessage,    ToolMessage,)from langchain_core.pydantic_v1 import BaseModel, Fieldclass Example(TypedDict):    """A representation of an example consisting of text input and expected tool calls.    For extraction, the tool calls are represented as instances of pydantic model.    """    input: str  # This is the example text    tool_calls: List[BaseModel]  # Instances of pydantic model that should be extracteddef tool_example_to_messages(example: Example) -> List[BaseMessage]:    """Convert an example into a list of messages that can be fed into an LLM.    This code is an adapter that converts our example to a list of messages    that can be fed into a chat model.    The list of messages per example corresponds to:    1) HumanMessage: contains the content from which content should be extracted.    2) AIMessage: contains the extracted information from the model    3) ToolMessage: contains confirmation to the model that the model requested a tool correctly.    The ToolMessage is required because some of the chat models are hyper-optimized for agents    rather than for an extraction use case.    """    messages: List[BaseMessage] = [HumanMessage(content=example["input"])]    tool_calls = []    for tool_call in example["tool_calls"]:        tool_calls.append(            {                "id": str(uuid.uuid4()),                "args": tool_call.dict(),                # The name of the function right now corresponds                # to the name of the pydantic model                # This is implicit in the API right now,                # and will be improved over time.                "name": tool_call.__class__.__name__,            },        )    messages.append(AIMessage(content="", tool_calls=tool_calls))    tool_outputs = example.get("tool_outputs") or [        "You have correctly called this tool."    ] * len(tool_calls)    for output, tool_call in zip(tool_outputs, tool_calls):        messages.append(ToolMessage(content=output, tool_call_id=tool_call["id"]))    return messages

**API Reference:**[AIMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.ai.AIMessage.html) | [BaseMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.base.BaseMessage.html) | [HumanMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.human.HumanMessage.html) | [SystemMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.system.SystemMessage.html) | [ToolMessage](https://api.python.langchain.com/en/latest/messages/langchain_core.messages.tool.ToolMessage.html)

Next let's define our examples and then convert them into message format.

    examples = [    (        "The ocean is vast and blue. It's more than 20,000 feet deep. There are many fish in it.",        Person(name=None, height_in_meters=None, hair_color=None),    ),    (        "Fiona traveled far from France to Spain.",        Person(name="Fiona", height_in_meters=None, hair_color=None),    ),]messages = []for text, tool_call in examples:    messages.extend(        tool_example_to_messages({"input": text, "tool_calls": [tool_call]})    )

Let's test out the prompt

    example_prompt = prompt.invoke({"text": "this is some text", "examples": messages})for message in example_prompt.messages:    print(f"{message.type}: {message}")

    system: content="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, return null for the attribute's value."human: content="The ocean is vast and blue. It's more than 20,000 feet deep. There are many fish in it."ai: content='' tool_calls=[{'name': 'Person', 'args': {'name': None, 'hair_color': None, 'height_in_meters': None}, 'id': 'b843ba77-4c9c-48ef-92a4-54e534f24521'}]tool: content='You have correctly called this tool.' tool_call_id='b843ba77-4c9c-48ef-92a4-54e534f24521'human: content='Fiona traveled far from France to Spain.'ai: content='' tool_calls=[{'name': 'Person', 'args': {'name': 'Fiona', 'hair_color': None, 'height_in_meters': None}, 'id': '46f00d6b-50e5-4482-9406-b07bb10340f6'}]tool: content='You have correctly called this tool.' tool_call_id='46f00d6b-50e5-4482-9406-b07bb10340f6'human: content='this is some text'

Create an extractor[​](#create-an-extractor "Direct link to Create an extractor")
---------------------------------------------------------------------------------

Let's select an LLM. Because we are using tool-calling, we will need a model that supports a tool-calling feature. See [this table](/v0.2/docs/integrations/chat/) for available LLMs.

*   OpenAI
*   Anthropic
*   Azure
*   Google
*   Cohere
*   FireworksAI
*   Groq
*   MistralAI
*   TogetherAI

    pip install -qU langchain-openai

    import getpassimport osos.environ["OPENAI_API_KEY"] = getpass.getpass()from langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-4-0125-preview", temperature=0)

    pip install -qU langchain-anthropic

    import getpassimport osos.environ["ANTHROPIC_API_KEY"] = getpass.getpass()from langchain_anthropic import ChatAnthropicllm = ChatAnthropic(model="claude-3-sonnet-20240229")

    pip install -qU langchain-openai

    import getpassimport osos.environ["AZURE_OPENAI_API_KEY"] = getpass.getpass()from langchain_openai import AzureChatOpenAIllm = AzureChatOpenAI(    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],    azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],    openai_api_version=os.environ["AZURE_OPENAI_API_VERSION"],)

    pip install -qU langchain-google-vertexai

    import getpassimport osos.environ["GOOGLE_API_KEY"] = getpass.getpass()from langchain_google_vertexai import ChatVertexAIllm = ChatVertexAI(model="gemini-pro")

    pip install -qU langchain-cohere

    import getpassimport osos.environ["COHERE_API_KEY"] = getpass.getpass()from langchain_cohere import ChatCoherellm = ChatCohere(model="command-r")

    pip install -qU langchain-fireworks

    import getpassimport osos.environ["FIREWORKS_API_KEY"] = getpass.getpass()from langchain_fireworks import ChatFireworksllm = ChatFireworks(model="accounts/fireworks/models/mixtral-8x7b-instruct")

    pip install -qU langchain-groq

    import getpassimport osos.environ["GROQ_API_KEY"] = getpass.getpass()from langchain_groq import ChatGroqllm = ChatGroq(model="llama3-8b-8192")

    pip install -qU langchain-mistralai

    import getpassimport osos.environ["MISTRAL_API_KEY"] = getpass.getpass()from langchain_mistralai import ChatMistralAIllm = ChatMistralAI(model="mistral-large-latest")

    pip install -qU langchain-openai

    import getpassimport osos.environ["TOGETHER_API_KEY"] = getpass.getpass()from langchain_openai import ChatOpenAIllm = ChatOpenAI(    base_url="https://api.together.xyz/v1",    api_key=os.environ["TOGETHER_API_KEY"],    model="mistralai/Mixtral-8x7B-Instruct-v0.1",)

Following the [extraction tutorial](/v0.2/docs/tutorials/extraction/), we use the `.with_structured_output` method to structure model outputs according to the desired schema:

    runnable = prompt | llm.with_structured_output(    schema=Data,    method="function_calling",    include_raw=False,)

Without examples 😿[​](#without-examples- "Direct link to Without examples 😿")
-------------------------------------------------------------------------------

Notice that even capable models can fail with a **very simple** test case!

    for _ in range(5):    text = "The solar system is large, but earth has only 1 moon."    print(runnable.invoke({"text": text, "examples": []}))

    people=[Person(name='earth', hair_color='null', height_in_meters='null')]people=[Person(name='earth', hair_color='null', height_in_meters='null')]people=[]people=[Person(name='earth', hair_color='null', height_in_meters='null')]people=[]

With examples 😻[​](#with-examples- "Direct link to With examples 😻")
----------------------------------------------------------------------

Reference examples helps to fix the failure!

    for _ in range(5):    text = "The solar system is large, but earth has only 1 moon."    print(runnable.invoke({"text": text, "examples": messages}))

    people=[]people=[]people=[]people=[]people=[]

Note that we can see the few-shot examples as tool-calls in the [Langsmith trace](https://smith.langchain.com/public/4c436bc2-a1ce-440b-82f5-093947542e40/r).

And we retain performance on a positive sample:

    runnable.invoke(    {        "text": "My name is Harrison. My hair is black.",        "examples": messages,    })

    Data(people=[Person(name='Harrison', hair_color='black', height_in_meters=None)])

[Edit this page](https://github.com/langchain-ai/langchain/edit/master/docs/docs/how_to/extraction_examples.ipynb)

* * *

#### Was this page helpful?

  

#### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchain/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E).

[

Previous

How to select examples by similarity

](/v0.2/docs/how_to/example_selectors_similarity/)[

Next

How to handle long text when doing extraction

](/v0.2/docs/how_to/extraction_long_text/)

*   [Define the schema](#define-the-schema)
*   [Define reference examples](#define-reference-examples)
*   [Create an extractor](#create-an-extractor)
*   [Without examples 😿](#without-examples-)
*   [With examples 😻](#with-examples-)