LLM JSON Schema for Financial Report Extraction: Stable Structured Output

Use LLM JSON Schema for financial report extraction to return revenue, cash flow, risk factors, source evidence, nulls, confidence, and review fields as validated output.

Published · 2026-06-2215 min readXBSTACK
Evidence 4 cited sources
On this page

If you need an LLM to extract revenue, cash flow, risk factors, and source evidence from financial reports, use JSON Schema as an output contract instead of relying on prompt wording alone. A production-oriented schema should define field names and types, allow undisclosed values to remain null, retain traceable fields such as source_page and source_text, and separate financial_metrics, risk_factors, management_tone, and review_questions. A schema constrains structure; it does not prove that a number, unit, reporting period, or citation is correct. Structured outputs can still involve refusals, incomplete responses, API errors, or business-rule errors, so verify extracted values against the original filing.

This guide focuses on that structured-output layer. It includes a concrete schema design, null-handling rules, evidence fields, validation strategy, and review boundaries.

What Structured Outputs Do—and Do Not—Guarantee

JSON Schema describes a data structure, types, and constraints. A model API’s Structured Outputs feature can constrain responses to a supported subset of that schema, but it is not a factual verification system. OpenAI’s documentation requires applications to handle refusals, incomplete responses, and API errors, and to validate business rules that the schema cannot express. For financial reports, validate the company, reporting period, currency, units, GAAP / non-GAAP basis, and source page separately. A model-generated confidence value is an auxiliary signal, not a statistical confidence interval or a substitute for human review.

Official Specifications and Implementation References

If this schema is going into a production Agent, do not validate only whether the JSON parses. Feed field-level evidence, null handling, confidence, and human-review outcomes into AI Agent Evaluation and AI Agent Observability so you can distinguish schema-valid output from financially correct, traceable output.

Problems Addressed in This Article

  • LLMs often confuse Non-GAAP and GAAP financial metrics during extraction and may even miss units, years, or the scope of consolidation.
  • When the model encounters undisclosed data in financial reports, it tends to guess and fill in numbers using common sense or vague formulas.
  • Risk factors and management discussion sections are overly compressed by the model into meaningless boilerplate, losing sensitivity to subtle tonal variations.
  • The JSON format output by the model is prone to parsing errors in production due to truncated quotes, extra commas, or explanatory prefaces.

Who Should Read This

  • Full-stack engineers developing AI Agents or RAG applications who face challenges extracting high-precision data from unstructured text.
  • Investment researchers looking to use LLM tools to analyze financial reports more efficiently while maintaining strict control over hallucinations and data accuracy.
  • Technical architects focused on stable structured output, validation gates, and fault-tolerant LLM design.

Position in the Toolchain

This article only addresses structured output and JSON Schema constraints. For PDF table extraction, see Financial Report PDF Table Extraction; for asynchronous task services, see AI Financial Report Task Queue; for product entry, see AI Finance Tool.

Structured Verification Fields

Before launch, it is recommended to retain source_page, evidence, confidence, review_status, and null_reason, so that each conclusion can trace back to the original text location, evidence segments, and manual verification status.

Why Financial Report Analysis Cannot Allow Free LLM Output

Free natural language output causes the financial analysis system to lose basic verifiability and programmability.

A financial-report extraction workflow often has to reconcile hundreds of pages across annual reports, quarterly filings, and appendices. The hard part is not merely reading the text: it is preserving company identity, reporting period, currency, units, accounting basis, and page-level evidence while preventing the model from mixing values from different sections or periods.

If you let the model freely answer “Summarize this company’s revenue, cash flow, and risk factors,” you usually get a paragraph that looks fluent but has no standard format. For example, it might confuse net cash flow from operating activities with free cash flow, or apply prior year data to this year. Worse, it might even consider FY2024 Q4 figures as full-year numbers.

Another fatal problem with free output is “format drift.” In automated analysis workflows, the backend database requires fixed field values for plotting or quantitative scoring. If the model outputs a markdown table one time, a key-value pair the next, and then wraps JSON externally with json ... next time, the downstream parser will throw JSONDecodeError.

Therefore, in serious investment research scenarios, we must forcibly narrow the model’s expression range, constraining it from “speaking freely” to “following format definitions.” This is the underlying value of JSON Schema. It’s not just a front-end display convention; it is the data contract for the entire AI financial report extraction pipeline.

Modules Needed for Structured Financial Report Output

Breaking down financial report output into four core modules—financial metrics, risk factors, management tone, and verification checklist—is crucial for achieving system stability.

A financial-report extraction schema is usually easier to validate when it separates company metadata, financial metrics, risk factors, management commentary, and review questions. The following is a reference structure for an implementation; it is not presented as a deployed XBSTACK backend schema:

{
  "company_metadata": {
    "company_name": "NVIDIA Corporation",
    "report_period": "FY2024",
    "reporting_currency": "USD"
  },
  "financial_metrics": {},
  "risk_factors": [],
  "management_tone": [],
  "review_questions": []
}

Every submodule here carries specific data constraint logic.

First, the company_metadata module verifies which company and period the report covers. An LLM’s attention can drift when it processes long documents. If it is analyzing an NVIDIA PDF but encounters competitor data in the context, it may mix the figures together. Constraining metadata at the outermost layer forces the model to identify the company and reporting period first.

Second, the financial_metrics module precisely extracts core financial metrics such as revenue, gross profit, operating expenses, net income, operating cash flow, and free cash flow.

Third, the risk_factors module captures risk warnings, which in financial reports often span dozens of pages, and extracts them into comparable feature dictionaries.

Fourth, the management_tone module tracks subtle wording changes by management regarding business outlook.

Fifth, the review_questions module consists of audit questions generated by AI, serving as a starting point for human review.

financial_metrics: Precise Definitions for Financial Metrics

Financial metric extraction should use structured objects that bind each value to its unit, period, source page, and source text.

Many developers, when designing financial metric schemas, prefer to use flat key-value pairs. For example, defining revenue as “revenue”: 60922. This is a major risk in practice.

The number 60922 alone carries too little context. Is the unit millions or thousands? Does the figure cover the year ended January 28 or a particular quarter? Which PDF page contains it? What is the original context?

To solve this problem, define each financial_metrics member as an independent object. Financial amounts and ratios should not be stored first as binary floating-point values; preserve the original decimal string in the schema and parse it with Decimal in the application layer for exact arithmetic. The following is an example model using Pydantic:

from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Literal

class MetricDetail(BaseModel):
    value: Optional[str] = Field(
        default=None,
        description="The original metric as a decimal string; parse with Decimal in the application layer. Use null when undisclosed and do not convert to binary float first."
    )
    unit: Optional[str] = Field(
        default=None,
        description="Unit, such as USD million or CNY thousand; it must match the source text."
    )
    period: Optional[str] = Field(
        default=None,
        description="Corresponding financial period, such as FY2024 or Q4 FY2024."
    )
    source_page: Optional[int] = Field(
        default=None,
        description="Absolute page number for this data in the original PDF file."
    )
    source_text: Optional[str] = Field(
        default=None,
        description="Original sentence or table-row text from the financial report used to extract this data."
    )
    confidence: Literal["high", "medium", "low"] = Field(
        default="low",
        description="Confidence. Use high when the data comes from a table with clear context; use medium/low when inference is required or the context is ambiguous."
    )

class FinancialMetrics(BaseModel):
    revenue: MetricDetail = Field(description="Operating revenue")
    gross_margin: MetricDetail = Field(description="Gross margin")
    net_income: MetricDetail = Field(description="Net income")
    operating_cash_flow: MetricDetail = Field(description="Cash flow from operating activities")
    free_cash_flow: MetricDetail = Field(description="Free cash flow, defined as operating cash flow minus capital expenditures; look for an official disclosure or explicit statement")

With this structure, what we get is no longer just simple numbers, but a dataset with its own chain of evidence.

For example, when debugging Nvidia’s FY2024 financial report, if the model’s extracted gross margin is confused between Non-GAAP and GAAP, when we verify the source_text, we can clearly see whether it reads 76.0% of Non-GAAP or 72.7% of GAAP. By tracing source_page, analysts can jump to the corresponding PDF location with one click, making the AI’s output fully traceable.

Why Must Missing Fields Be Returned as null?

Preserving uncertainty in financial report analysis is far more important than forcing every field to contain a value. A null state is the first line of defense against invented formulas and hallucinated data.

In traditional software engineering, we always try to make each field have a definite value. But the logic behind AI financial report analysis is exactly the opposite.

What should we do if a company does not separately disclose the Free Cash Flow metric in its financial report, or does not provide details of capital expenditures that quarter?

If the Schema does not allow null, or the prompt lacks strict constraints, LLMs often try too hard to satisfy the request by calculating from the available data. A model may piece together free cash flow by subtracting spending on fixed assets and construction, or simply fabricate a proportional figure from the previous quarter’s data.

This is extremely dangerous because companies calculate free cash flow in different ways. Some deduct interest attributable to non-controlling shareholders, while others include proceeds from asset disposals. The AI’s seemingly clever assumptions directly undermine the rigor of the financial data.

Therefore, in the Schema definition, every field other than required metadata should default to None, and the description should repeatedly state:

[If the metric is not directly stated in the text or cannot be derived directly, it must be set to null. Do not estimate it with a formula or infer it from background knowledge.]

This way, when the frontend receives null, we know the information was not disclosed; it is not a false signal calculated by the LLM.

Xiaobai Lab In-House / TOOL CONVERSION

Want to test the AI Financial Report Assistant? Open the tool with one click.

The public tool takes a ticker and displays public financial metrics and risk summaries. Batch PDF extraction is an engineering design, not a released feature.

risk_factors: Do More Than Summarize Risk Factors

Risk factors need multidimensional, structured extraction—with enumerated types, severity levels, and source-evidence chains—to support comparisons across periods and companies.

Typically, the Item 1A (Risk Factors) section in a financial report contains tens of thousands of words. Most AI tools use a “concise summary” and finally output a paragraph summary.

This kind of summary is easy to read, but in reality, it erases the most valuable micro-changes.

If a semiconductor company changes its wording on geopolitical supply-chain disruption from “may have an impact” to “substantial delays have already occurred,” that signals a significant escalation. A natural-language summary may reduce both statements to “facing supply-chain risks,” erasing a subtle but critical warning.

We can extend the design of risk factors to multidimensional list elements:

class RiskFactor(BaseModel):
    risk_type: Literal[
        "customer_concentration",   # Customer concentration
        "supply_chain",             # Supply-chain risk
        "regulation",               # Regulatory risk
        "currency_fluctuation",     # Currency risk
        "litigation",               # Litigation risk
        "inventory_impairment",     # Inventory impairment risk
        "debt_solvency",            # Debt-servicing risk
        "competition",              # Industry competition
        "macro_economy",            # Macroeconomy
        "other"
    ] = Field(description="Risk category")
    risk_summary: str = Field(description="A concise, single-sentence summary of the substance of the risk")
    severity: Literal["critical", "high", "medium", "low"] = Field(description="Potential degree of negative impact on the company's performance")
    is_new_or_intensified: bool = Field(description="Whether the risk is new since the previous period or its wording has become materially stronger")
    evidence: str = Field(description="Specific factual statement in the financial report about how the risk has developed")
    source_page: int = Field(description="Page number for the risk in the financial report PDF")

With such a structured list, we can compare fields of the same company across different years.

If is_new_or_intensified returns True, the risk is new or has intensified in the current period. If risk_type is customer_concentration and the evidence says “a single customer accounts for 15%,” that specific figure can immediately alert the analyst.

management_tone: How Should Management Tone Be Structured?

Management-tone extraction must be based on objective changes in wording and context, not an LLM’s subjective classification of emotion.

In the MD&A (Management’s Discussion and Analysis) section, changes in the management’s wording represent their actual attitude toward the future.

Because LLMs have strong semantic capabilities, simply asking, “Is management’s attitude good or bad?” usually produces an answer such as “the attitude is optimistic.” Financial reports typically use positive words such as strong, progress, and commitment throughout their corporate messaging.

To extract the real attitude change, we need to adopt a “dual wording verification” structure in the schema:

class ToneAnalysis(BaseModel):
    topic: str = Field(description="Topic under discussion, such as demand, pricing_power, or capital_expenditure")
    current_statement: str = Field(description="Summary of management's statement for the current period")
    tone: Literal["positive", "neutral", "cautious", "negative"] = Field(description="Management's tone on the topic")
    change_from_previous: str = Field(description="Whether the stance has become more cautious, remained stable, or become more optimistic relative to previous known statements")
    evidence: str = Field(description="The most representative sentence in the source text supporting the tone assessment")
    source_page: int = Field(description="Corresponding page number")

For example, if management says, ‘Customers are becoming more cautious with their budgets,’ the model classifies the current tone as cautious. By comparing change_from_previous with the prior period, the system records the shift toward caution.

This approach limits subjective speculation by forcing the LLM to support its classification with source evidence and a specific change in wording.

review_questions: The Final Output Should Be a Review Checklist

AI should not serve as the final decision-maker in serious investment research, but should output a review checklist that analysts can manually verify.

One design to avoid is having an AI financial-report system append a trading direction to its analysis. Structured extraction and risk flags should not be presented as automated buy or sell instructions; any investment action should remain a separate decision made after reviewing the original disclosures and the user’s own constraints.

First, LLMs lack real-time macroeconomic awareness and can be misled by official wording in financial reports when industry dynamics are complex.

Second, directly giving trading decisions would push the system into extremely complex compliance and liability disputes.

The best endpoint for AI financial report analysis is not to provide conclusions but to provide a review checklist.

We can design a review_questions module, allowing AI, after extracting all the data, to automatically generate 3 to 5 critical review questions about the company:

class ReviewQuestion(BaseModel):
    question: str = Field(description="Key financial or operating question requiring human review")
    why_it_matters: str = Field(description="Why this question is critical to the current valuation or risk assessment")
    related_metrics: List[str] = Field(description="List of financial-metric keys associated with this question")
    source_pages: List[int] = Field(description="List of original financial report PDF pages the analyst should review")

For example, when AI detects that a company’s revenue has increased by 20%, but net cash flow from operating activities has dropped by 15%, it will generate a question like this on the review checklist:

[The company’s net income and operating cash flow are moving in different directions. Are accounts receivable or inventory accumulating abnormally? This could affect cash conversion in coming quarters. Review changes in Accounts Receivable on page 68 of the PDF and Inventory impairment provisions on page 72.]

In this way, AI does not overstep by making trading decisions for humans. Instead, it plays the role of an extremely sharp assistant, helping analysts compress thick financial reports into a few key clues worth investigating.

Illustrative Failure Shapes

Possible failure cases include refusals, incomplete responses, API errors, and values that fail application-level field or enum validation.

Even with Structured Outputs, the application must still handle refusals, incomplete responses, and API errors. The following snippets illustrate possible failure shapes only; they are not XBSTACK production logs and do not establish that a real production incident occurred.

ValidationError: 1 validation error for FinancialReportSchema
  risk_factors -> 0 -> severity
    Input 'high_severity' is not a valid enum member (should be one of: 'critical', 'high', 'medium', 'low')

Or this kind of JSON parsing error caused by the model output being truncated prematurely:

JSONDecodeError: Expecting ',' delimiter: line 42 column 18 (char 1289)

Prefer the OpenAI Python SDK’s chat.completions.parse() helper and pass a Pydantic model as response_format. The SDK derives a supported JSON Schema and parses the response into a typed model. The application must still handle refusals, incomplete responses, and API errors; do not repeatedly feed refusal or truncated output back into the prompt.

The following compact example illustrates the flow. Its field model is illustrative and must be expanded for the target reporting basis; monetary values, periods, currencies, and source pages still require independent validation:

from openai import OpenAI
from pydantic import BaseModel, ValidationError

class FinancialMetric(BaseModel):
    name: str
    value: str | None = None
    unit: str | None = None
    period: str | None = None
    source_page: int | None = None
    source_text: str | None = None

class RiskFactor(BaseModel):
    category: str
    summary: str
    evidence: str
    source_page: int | None = None

class ReviewQuestion(BaseModel):
    question: str
    why_it_matters: str
    source_pages: list[int]

class FinancialReportSchema(BaseModel):
    company_name: str
    report_period: str
    currency: str
    financial_metrics: list[FinancialMetric]
    risk_factors: list[RiskFactor]
    review_questions: list[ReviewQuestion]

client = OpenAI()

def extract_financial_data(prompt: str):
    try:
        completion = client.chat.completions.parse(
            model="gpt-4o-2024-08-06",
            messages=[
                {
                    "role": "system",
                    "content": (
                        "Extract only information supported by the supplied report. "
                        "Use null for undisclosed optional values. Never invent figures."
                    ),
                },
                {"role": "user", "content": prompt},
            ],
            response_format=FinancialReportSchema,
        )

        choice = completion.choices[0]
        message = choice.message

        if message.refusal:
            return {"status": "refused", "reason": message.refusal}
        if choice.finish_reason == "length" or message.parsed is None:
            return {"status": "needs_human_review", "reason": "incomplete_or_unparsed"}
        return message.parsed

    except ValidationError as exc:
        return {"status": "needs_human_review", "validation_errors": exc.errors()}
    except Exception as exc:
        # Production code should log a redacted error and classify retryable API failures.
        return {"status": "api_error", "error_type": type(exc).__name__}

The SDK helper performs Pydantic parsing. This example handles refusals, length truncation or missing parsed output, validation exceptions, and API exceptions separately. A production system should add bounded retries based on error classification, idempotency controls, redacted logs, and human review rather than treating every failure as a formatting error.

Comparison Blocks

Schema-constrained output can enforce supported structural requirements more reliably than prompt instructions alone, but it does not establish a universal ranking against tool/function calling or guarantee lower factual error. Latency and correctness depend on the provider, model, schema, and application.

The following is a qualitative engineering comparison, not a measured benchmark. System-prompt instructions, tool/function calling, and schema-constrained structured output serve different purposes and have different failure modes. Do not infer a universal hallucination rate or latency ranking without testing the same model, prompt, schema, workload, and runtime configuration.

For financial extraction, compare the approaches on schema-validation pass rate, field-level accuracy, evidence-page accuracy, refusal/incomplete-response handling, end-to-end latency, and integration complexity. The observations below are design trade-offs to validate in your own environment, not results from a published XBSTACK experiment:

  • Solution 1: Pure System Prompt constraints

    • Format stability: prompt instructions alone do not enforce a machine-checkable schema; the application must detect missing fields and extra text.
    • Semantic risk: if unknown/null states are not explicitly defined, a model may guess missing values; evaluate this with a labeled test set.
    • Latency: there is no separate schema-processing stage, but end-to-end latency still depends on the model, prompt, and output length.
    • Code integration difficulty: low. You only need to write the prompt well, without relying on specific SDKs.
  • Solution 2: LLM Function Calling (Tool Call) constraints

    • Format stability: tool arguments can be checked against the declared parameter schema, subject to provider support and application-side validation.
    • Semantic risk: valid arguments can still contain incorrect values; required fields do not prove factual correctness.
    • Latency: measure the complete tool workflow, including tool selection, argument generation, and subsequent execution.
    • Code integration difficulty: Moderate. You need to parse message.tool_calls and handle the subsequent processing.
  • Solution 3: Native JSON Schema constraints (Structured Output)

    • Format stability: constrained/structured output can greatly reduce JSON syntax and schema-shape errors, but it does not justify a fixed 99.9% accuracy claim and it does not prove that amounts, units, page numbers, or financial meaning are correct. Track schema-validation pass rate separately from field accuracy and evidence-mapping accuracy.
    • Semantic error risk: a schema constrains field types, enums, and required relationships, but it cannot prevent a model from producing a value that is structurally valid and factually wrong. Allow null/missing values, retain source_page / evidence, and validate with rules and human sampling.
    • Latency: some providers incur extra processing on the first request with a new schema; repeated requests may benefit from caching. Measure first-request and steady-state latency separately.
    • Code integration difficulty: High. You must define the Pydantic class precisely and serialize it into a schema dictionary that meets OpenAI or Gemini requirements.

For financial extraction, schema-constrained output is useful when the provider supports the required schema subset, but the same output constraint is not suitable for every task. Combine it with refusal and incomplete-response handling, source-page verification, accounting/business rules, regression evaluations, and human review. Report schema conformance separately from factual accuracy; neither should be described as 100% without measured evidence.

NEXT READING

Ready to analyze your first financial report?

The public tool currently accepts a stock ticker and shows public financial metrics and risk summaries; it does not support PDF uploads. PDF parsing, evidence links, and review checklists described here are engineering and research directions.

FAQ

Why does AI financial report analysis require JSON Schema?

JSON Schema constrains LLM output fields and formats, reducing hallucinations, missing fields, and format drift while returning revenue, profit, cash flow, risk factors, and review questions in a stable structure. Without a Schema, backend databases cannot use unstructured LLM output directly, and the system cannot make quantitative comparisons across companies.

Why must missing financial data output a null state?

If the financial report does not clearly disclose the data, the model must not guess. Returning null preserves uncertainty and prevents the model from fabricating numbers or drawing incorrect conclusions from crude calculations. This blocks the AI’s imagination at the data source and preserves the rigor of the data.

Why are the source_page and source_text fields mandatory?

They bind the AI’s extracted conclusions to the exact location and source passage in the original financial report PDF. If analysts suspect an error, source_page and source_text let them return quickly to the relevant passage for manual comparison, addressing the black-box, unverifiable nature of LLM output.

Can AI Financial Report Assistants Be Used Directly as Trading Signals?

No. AI financial report assistants are suitable only for information compression, structured extraction, and checklist generation. They lack expert-level macroeconomic awareness and real-time sentiment judgment. They cannot predict stock prices or directly provide buy or sell recommendations; they can only help human analysts reduce noise.

Public tool versus PDF engineering design

XBSTACK AI Finance currently takes a ticker and organizes public financial metrics and risk summaries. PDF upload, batch extraction and page-level evidence are engineering designs discussed here, not released capabilities. Validate the provider-supported schema subset and refusal or incomplete responses, then reconcile fiscal period, currency, units and source location. Valid JSON is not proof of a financial fact.

Keep reading

If you’re interested in other aspects of financial report analysis, you can continue reading my series of practical summaries:

Tool / AI Finance

Run the financial-report workflow instead of only reading about it

The AI Finance tool turns report extraction, source-page evidence and review steps into an interactive workflow. It compresses information and does not provide investment advice.

Next step: make the workflow operable

Full decision path →

Continue with retries, queues, idempotency, observability, or cost controls that keep the workflow reliable.

Verify behavior and observabilityAI Financial Report Assistant Evaluation Framework: How to Use a Golden Dataset to Detect LLM Misreads?Create a financial-report AI golden dataset with labeled statements, citations, numerical checks, failure cases and reviewer corrections.Continue with state and memoryAI Financial Report Assistant: Converting PDFs into Structured Risk ChecklistsImplement an AI financial report assistant with PDF parsing, structured JSON extraction, evidence citations, numeric checks and human review.Next problem in the same topicAI Financial Report Task Queues: PDF Parsing and RecoveryDecide when financial PDF parsing needs a durable task queue, workers, status updates and idempotent retries; synchronous FastAPI requests do not inherently cause 504.
Comments & evidence

DISCUSSION

Questions, verification and corrections

Sign in to comment. Every new comment is reviewed before publication; while pending, it is visible only to you and the administrator.

Sign-in required Reviewed before public
Loading the discussion…