PDF Extractor with Native Multi Step Tool Use

PDF Extractor with Native Multi Step Tool Use

Jason Jung

Jason Jung

Objective

Generally, users are limited to text inputs when using large language models (LLMs), but agents enable the model to do more than ingest or output text information. Using tools, LLMs can call other APIs, save data, and much more. In this notebook, we will explore how we can leverage agents to extract information from PDFs. We will mimic an application where the user uploads PDF files and the agent extracts useful information. This can be useful when the text information has varying formats and you need to extract various types of information.

In the directory, we have a simple_invoice.pdf file. Everytime a user uploads the document, the agent will extract key information total_amount and invoice_number and then save it as CSV which then can be used in another application. We only extract two pieces of information in this demo, but users can extend the example and extract a lot more information.

Steps

  1. extract_pdf() function extracts text data from the PDF using unstructured package. You can use other packages like PyPDF2 as well.
  2. This extracted text is added to the prompt so the model can "see" the document.
  3. The agent summarizes the document and passes that information to convert_to_json() function. This function makes another call to command model to convert the summary to json output. This separation of tasks is useful when the text document is complicated and long. Therefore, we first distill the information and ask another model to convert the text into json object. This is useful so each model or agent focuses on its own task without suffering from long context.
  4. Then the json object goes through a check to make sure all keys are present and gets saved as a csv file. When the document is too long or the task is too complex, the model may fail to extract all information. These checks are then very useful because they give feedback to the model so it can adjust it's parameters to retry.
import os

import cohere
import pandas as pd
import json
from unstructured.partition.pdf import partition_pdf
# uncomment to install dependencies
# !pip install cohere unstructured
# versions
print('cohere version:', cohere.__version__)
cohere version: 5.5.1

Setup

COHERE_API_KEY = os.environ.get("CO_API_KEY")
COHERE_MODEL = 'command-r-plus'
co = cohere.Client(api_key=COHERE_API_KEY)

Data

The sample invoice data is from https://unidoc.io/media/simple-invoices/simple_invoice.pdf.

Tool

Here we define the tool which converts summary of the pdf into json object. Then, it checks to make sure all necessary keys are present and saves it as csv.

def convert_to_json(text: str) -> dict:
    """
    Given text files, convert to json object and saves to csv.

    Args:
        text (str): The text to extract information from.

    Returns:
        dict: A dictionary containing the result of the conversion process.
    """

    MANDATORY_FIELDS = [
        "total_amount",
        "invoice_number",
    ]

    message = """# Instruction
    Given the text, convert to json object with the following keys:
    total_amount, invoice_number

    # Output format json:
    {{
        "total_amount": "<extracted invoice total amount>",
        "invoice_number": "<extracted invoice number>",
    }}

    Do not output code blocks.

    # Extracted PDF
    {text}
    """

    result = co.chat(
        message=message.format(text=text), model=COHERE_MODEL, preamble=None
    ).text

    try:
        result = json.loads(result)
        # check if all keys are present
        if not all(i in result.keys() for i in MANDATORY_FIELDS):
            return {"result": f"ERROR: Keys are missing. Please check your result {result}"}

        df = pd.DataFrame(result, index=[0])
        df.to_csv("output.csv", index=False)
        return {"result": "SUCCESS. All steps have been completed."}

    except Exception as e:
        return {"result": f"ERROR: Could not load the result as json. Please check the result: {result} and ERROR: {e}"}

Cohere Agent

Below is a cohere agent that leverages multi-step API. It is equipped with convert_to_json tool.

def cohere_agent(
    message: str,
    preamble: str,
    verbose: bool = False,
) -> str:
    """
    Function to handle multi-step tool use api.

    Args:
        message (str): The message to send to the Cohere AI model.
        preamble (str): The preamble or context for the conversation.
        verbose (bool, optional): Whether to print verbose output. Defaults to False.

    Returns:
        str: The final response from the call.
    """

    functions_map = {
        "convert_to_json": convert_to_json,
    }

    tools = [
        {
            "name": "convert_to_json",
            "description": "Given a text, convert it to json object.",
            "parameter_definitions": {
                "text": {
                    "description": "text to be converted into json",
                    "type": "str",
                    "required": True,
                },
            },
        }
    ]

    counter = 1

    response = co.chat(
        model=COHERE_MODEL,
        message=message,
        preamble=preamble,
        tools=tools,
    )

    if verbose:
        print(f"\nrunning step 0")
        print(response.text)

    while response.tool_calls:
        tool_results = []

        if verbose:
            print(f"\nrunning step {counter}")
        for tool_call in response.tool_calls:
            print("tool_call.parameters:", tool_call.parameters)
            if tool_call.parameters:
                output = functions_map[tool_call.name](**tool_call.parameters)
            else:
                output = functions_map[tool_call.name]()

            outputs = [output]
            tool_results.append({"call": tool_call, "outputs": outputs})

            if verbose:
                print(
                    f"= running tool {tool_call.name}, with parameters: {tool_call.parameters}"
                )
                print(f"== tool results: {outputs}")

        response = co.chat(
            model=COHERE_MODEL,
            message="",
            chat_history=response.chat_history,
            preamble=preamble,
            tools=tools,
            tool_results=tool_results,
        )

        if verbose:
            print(response.text)
            counter += 1

    return response.text

main

def extract_pdf(path):
    """
    Function to extract text from a PDF file.
    """
    elements = partition_pdf(path)
    return "\n".join([str(el) for el in elements])


def pdf_extractor(pdf_path):
    """
    Main function that extracts pdf and calls the cohere agent.
    """
    pdf_text = extract_pdf(pdf_path)

    prompt = f"""
    # Instruction
    You are expert at extracting invoices from PDF. The text of the PDF file is given below.

    You must follow the steps below:
    1. Summarize the text and extract only the most information: total amount billed and invoice number.
    2. Using the summary above, call convert_to_json tool, which uses the summary from step 1.
    If you run into issues. Identifiy the issue and retry.
    You are not done unless you see SUCCESS in the tool output.

    # File Name:
    {pdf_path}

    # Extracted Text:
    {pdf_text}
    """
    output = cohere_agent(prompt, None, verbose=True)
    print(f"Finished extracting: {pdf_path}")

    print('Please check the output below')
    print(pd.read_csv('output.csv'))


pdf_extractor('simple_invoice.pdf')

running step 0
I will summarise the text and then use the convert_to_json tool to format the summary.

running step 1
tool_call.parameters: {'text': 'Total amount billed: $115.00\nInvoice number: 0852'}
= running tool convert_to_json, with parameters: {'text': 'Total amount billed: $115.00\nInvoice number: 0852'}
== tool results: [{'result': 'SUCCESS. All steps have been completed.'}]
SUCCESS.
Finished extracting: simple_invoice.pdf
Please check the output below
  total_amount  invoice_number
0      $115.00             852

As shown above, the model first summarized the extracted pdf as Total amount: $115.00\nInvoice number: 0852 and sent this to conver_to_json() function.
conver_to_json() then converts it to json format and saves it into a csv file.