How to Summarise Legal Contracts with Haystack

Summarise legal contracts inside a Haystack pipeline with EnConvert Distill, which returns schema-defined fields for up to 50 hosted contract URLs in one call

Get API key

A developer building a Haystack pipeline that reviews legal contracts needs structured clause-level content before the pipeline can flag obligations, risks, or missing terms. Legal contracts hosted at shared document URLs mix clause numbering, exhibit appendices, defined terms sections, and legal boilerplate in a dense layout that returns no clean structured text when fetched directly, and document management platforms require OAuth or a service account before contract content can be read programmatically. EnConvert Distill accepts the hosted contract URL and a schema the pipeline defines, and returns structured fields in one synchronous call. The pipeline gets schema-defined contract content ready for downstream clause analysis with no DMS credentials.

Example

python
import os

import requests
from haystack.components.agents import Agent
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.tools import Tool

# OpenAIChatGenerator reads OPENAI_API_KEY from the environment
CONTRACT_URL = os.environ["CONTRACT_URL"]  # a hosted contract document that opens without signing in

BASE_URL = "https://api.enconvert.com/v2"
headers = {
    "X-API-Key": os.environ["ENCONVERT_API_KEY"],
    "Content-Type": "application/json",
}

# The fields the pipeline receives. The response keys match these names exactly.
CONTRACT_SCHEMA = {
    "title": "The contract title, as written at the top of the document",
    "parties": (
        "The named parties to the contract, as a list, exactly as written. "
        "Return an empty list if none are named."
    ),
    "effective_date": "The effective date stated in the contract. Return an empty string if none is stated.",
    "key_obligations": (
        "Obligations that the contract text states, as a list, one short sentence each, naming "
        "the obligated party. Return an empty list if the contract text is not on the page."
    ),
    "termination_clauses": (
        "The termination provisions that the contract text states, as a list, with the clause "
        "number where one is shown. Return an empty list if none are stated."
    ),
    "governing_law": "The governing law or jurisdiction stated in the contract. Return an empty string if none is stated.",
}

def as_text(value) -> str:
    if isinstance(value, list):
        return "; ".join(str(item) for item in value) or "not stated"
    return str(value) if value else "not stated"

def summarise_legal_contracts(urls: list[str]) -> str:
    """Reads legal contracts at hosted document URLs that open without signing in and returns
    structured fields for each: title, parties, effective date, key obligations, termination
    clauses, and governing law. Accepts up to 50 URLs."""
    if len(urls) > 50:
        return "Too many URLs. Distill accepts at most 50 per call."

    # One synchronous call: no job_id, no polling, no download step
    response = requests.post(
        f"{BASE_URL}/distill",
        headers=headers,
        json={"urls": urls, "schema": CONTRACT_SCHEMA},
        timeout=300,
    )

    # Distill runs on paid plans only, and the free tier returns 402
    if response.status_code == 402:
        return "Distill requires a paid plan."
    response.raise_for_status()

    contracts = []
    for result in response.json()["results"]:
        if result["status"] != "completed":
            contracts.append(f"Source: {result['url']}\nCould not be read ({result['status']}).")
            continue

        render_quality = result.get("render_quality", 1.0)
        if render_quality < 0.5:
            contracts.append(
                f"Source: {result['url']}\nLow render quality ({render_quality}), "
                "likely a login page or inaccessible document. Skipped."
            )
            continue

        data = result["data"]  # keys match CONTRACT_SCHEMA exactly
        contracts.append(
            f"Source: {result['url']}\n"
            f"Title: {as_text(data['title'])}\n"
            f"Parties: {as_text(data['parties'])}\n"
            f"Effective date: {as_text(data['effective_date'])}\n"
            f"Governing law: {as_text(data['governing_law'])}\n"
            f"Key obligations: {as_text(data['key_obligations'])}\n"
            f"Termination clauses: {as_text(data['termination_clauses'])}"
        )
    return "\n\n---\n\n".join(contracts)

contract_tool = Tool(
    name="summarise_legal_contracts",
    description=(
        "Reads legal contracts at hosted document URLs that open without signing in and returns "
        "structured fields for each: title, parties, effective date, key obligations, termination "
        "clauses, and governing law."
    ),
    parameters={
        "type": "object",
        "properties": {
            "urls": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Contract URLs to read, at most 50",
            }
        },
        "required": ["urls"],
    },
    function=summarise_legal_contracts,
)

agent = Agent(
    chat_generator=OpenAIChatGenerator(model="gpt-4.1"),
    tools=[contract_tool],
    system_prompt=(
        "You review contracts for a legal team. Use summarise_legal_contracts to read the "
        "contracts you need, report only what the tool returns, and cite the contract URL for "
        "every statement. If a field is not stated, say so."
    ),
)

result = agent.run(
    messages=[
        ChatMessage.from_user(
            f"Review {CONTRACT_URL} and list the "
            "parties, the termination provisions, and the governing law."
        )
    ]
)
print(result["last_message"].text)

What you get back

Distill returns schema-defined fields inline as structured JSON in the data object, with no polling and no job_id. The render_quality score lets the pipeline detect a login wall or inaccessible document before reasoning over incomplete content. Reading a legal contract from a DMS API requires OAuth credentials, role configuration, and a format-specific parser for each document type, while Distill returns schema-defined fields from the document URL in one call.

Get free API key — 500 ops per month, no card required. Note: Distill runs on paid plans. Free tier returns 402.