|

How to Perform AI Text Extraction and Structured Processing? Here Is a Practical Guide for You

How to Perform AI Text Extraction and Structured Processing? Here Is a Practical Guide for You

Extracting email bodies, quote tables, and contract clauses into JSON or CSV is the first real task many teams hand to a Large Language Model. It sounds like something you can solve with a single sentence, but after launch it often gets stuck on two details: the fields don’t match up, and the types aren’t clear.

This isn’t another collection of prompt templates. What determines whether this process can actually run isn’t how smart the model is—it’s whether you’ve separated “reading text” from “trusting data”: the model is responsible for reading natural language into fields, and the program is responsible for deciding whether those fields can be used.

Core value: By the end of this article, you’ll have a three-step path you can put into practice right away, a field checklist you can adapt directly, and a failure-handling rule set that retries only when necessary.

article-6cbce8bf-en-image-0

Key Points for AI Text Extraction and Structured Processing

The really hard part of structured extraction isn’t getting the API to respond—it’s whether what gets extracted is safe enough to write straight to the database. Break this into four stages—choose a model, define fields, run validation, handle failures—and make the owner of each stage explicit, and the whole process becomes stable.

The third stage is the one most easily skipped. Many implementations treat “the model says it’s done” as a success signal. Then downstream gets half-empty fields, the error surfaces in the business layer, and troubleshooting costs multiply. What the model returns is always text; whether it can be used as data is up to the program to decide.

Step What to do Owner Common mistake
1. Choose a model Extraction is a short-text, fixed-field task, so start with a cheap high-throughput model Engineering Running the entire dataset on the most expensive model from day one
2. Define fields Write field names, types, enum values, and how to represent missing values into the prompt Prompt Writing only “extract key information”
3. Run validation The program checks for missing values, types, enums, formats, and ranges Program Trusting the model’s claim that it’s “done”
4. Handle failures Retry only once; if it still fails, move it to the manual review queue and keep a sample Process Retrying endlessly, so the bill and the error count climb together

Pay attention to the last row. Retry policy isn’t a technical detail—it directly determines the cost curve: no retries push the error rate onto manual reviewers, unlimited retries push the bill onto finance, and retrying once is a defensible middle ground between the two.

Why validation belongs outside the model

Even when the prompt says “required,” if the source text genuinely lacks that information, the model will usually still hand you a plausible-looking value instead of leaving it blank. That’s just how generative models are wired: producing a coherent stretch of text is far easier than admitting “I couldn’t find it.” Trusting the model to report which fields are missing is far less reliable than checking each field yourself in code.

Keeping validation outside the model has an engineering upside too: the rules can change independently. Fields grow from 8 to 20, amounts need a currency, dates need a uniform format — all of that happens inside the validation function, with no need to rewrite the prompt or re-test the model. The stability of an extraction pipeline comes mostly from this layer, not from how fancy the prompt is.

Three types of text need three different field designs

Emails, tables, and contracts differ wildly in information density, so a single field design can’t cover them all. Take “amount” — in an email it usually comes with a currency and casual units, in a table it’s a bare number sitting under a header, and in a contract it may split into principal, interest, and penalty, each with its own conditions attached.

Input type Typical fields Design considerations
Email Sender, recipient, sent time, subject, amount, request type Normalize times to ISO 8601; split amount into separate numeric and currency columns
Table Row number, column name mapping, numeric value, unit, empty-cell marker Keep the original row number so errors can be traced to a specific row
Contract Party A, party B, effective date, expiration date, total amount, clause text Store clause snippets as raw text, not model summaries

One general principle: store values and units separately, store dates in a comparable format, and keep long text as raw snippets rather than summaries. Once a summary goes wrong, you can’t trace it back later; if a raw snippet is wrong, a quick human scan will catch it.

article-6cbce8bf-en-image-1

Not Every Model Supports Structured Outputs

There are two ways to constrain fields: use the model’s built-in JSON mode, or rely entirely on prompt constraints plus local parsing. The former usually has a lower error rate, but not every model offers it. When choosing a model, it’s worth confirming this before talking about price.

One concrete example: Gemini 4 Live’s official model page explicitly states that Structured outputs are not supported, and this model doesn’t appear in APIYI’s pricing API either. It’s designed for real-time multimodal interaction, so it’s not a good fit as the primary model for field extraction—especially not for scenarios where “all fields must be present” is part of the acceptance criteria.

If you choose within the supported range, the cost structure is actually pretty clear.

Model Input (USD / million tokens) Output (USD / million tokens) Cached read (USD / million tokens) Use case
glm-5.3-flash 0.15 0.50 0.03 Routine extraction with fixed fields and short text
deepseek-v4.1-flash 0.30 1.20 0.006 Batch processing historical emails with a high cache hit rate
glm-5.4 1.4 4.4 0.26 Long contract clauses with deeply nested fields

The data above is from the APIYI apiyi.com pricing page as of 2026-12-04, in USD per million tokens. The price differences aren’t huge, but for extraction tasks, token consumption comes mainly from input: a 2,000-character email, 2,000 emails a day—the input side is where the bulk of the bill comes from. The cached read price is also worth a look—when the same formatting template is sent over and over, the portion that hits the cache costs noticeably less. Prices change, so before you order, it’s a good idea to verify the current numbers on the pricing page.

article-6cbce8bf-en-image-2

AI Text Extraction and Structured Processing: Quick Start

Here’s the shortest path that actually works — five steps. Don’t build a framework first. Validate your field definitions against a few dozen real documents, and only then start thinking about engineering for scale.

  1. Get a key: Sign up at APIYI apiyi.com and create an API key. Use https://api.apiyi.com/v1 as your base_url — the interface is OpenAI-compatible, so an existing SDK only needs two lines changed.
  2. Define the fields: For the first version, write just 6 to 10 fields. Fewer is better; don’t get greedy. The more fields you have, the more likely the model is to miss one, and the harder it is to work out where validation went wrong.
  3. Write the prompt: Spell out five things, one item at a time — format, types, missing-value convention, enums, and units. Details below.
  4. Run it once: Set temperature to 0 and look at what the output actually looks like. Don’t rush into batch processing.
  5. Hook up validation: Parse the returned text into an object, run a field check, and log the reasons it fails.
import json
import openai

client = openai.OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.apiyi.com/v1",
)

response = client.chat.completions.create(
    model="glm-5.3-flash",
    temperature=0,
    messages=[
        {"role": "system", "content": "你是字段抽取器,只输出一个 JSON 对象,不输出解释。"},
        {"role": "user", "content": prompt},
    ],
)

try:
    data = json.loads(response.choices[0].message.content)
except json.JSONDecodeError:
    data = None  # hand it off to the validation step

This code does two things only: it sends the source text and field requirements in, and it parses the returned text as JSON. Always wrap that parse in exception handling — if the model occasionally tacks on an extra sentence like “Above is the extraction result,” the whole job throws.

Your prompt needs to state all five items clearly. Miss one, and you’ll end up patching it with retries later.

  1. Output format: a single JSON object — no array wrapper, no explanatory text before or after.
  2. Field names and types: declare strings, numbers, booleans, and dates separately, and hard-code the date format to ISO 8601.
  3. Missing-value convention: if it isn’t there, write null. Don’t guess, don’t invent, and don’t use placeholders like “unknown” or “not available.”
  4. Enum values: category fields may only take the given values — list every allowed value.
  5. Unit conventions: output amounts as numbers only, put currency in its own field, and express percentages as decimals.

Items 3 and 5 are the ones people skip most often. Once you skip them, the model “helpfully” fills in the gaps — and the values it makes up are structurally perfectly valid, so validation can’t stop them. Validation catches missing fields and wrong types; it can’t catch semantic fabrication. That’s exactly why a source-snippet field is worth keeping around: when someone spot-checks by hand, there’s something to check against.

Tip: Use the free test credits at APIYI apiyi.com to run through these five steps before you settle on a field list and a model. The same code switches models by changing only the model parameter, so comparing them is cheap.

AI Text Extraction and Structured Processing: Validation and Retry

The validation function has a narrow job: decide whether this output can go downstream. It doesn’t judge whether the content is correct—only whether the structure is complete, the types are right, and the values fall within the allowed range. Draw the boundary clearly, and the code gets a lot shorter.

Validation check What it checks What to do if it fails
Missing Whether required fields are null Record the missing field names and move to retry
Type Whether numeric fields can be converted to numbers, and whether booleans are real booleans Call out that field in the prompt on retry
Enum Whether the value falls within the allowed set Retry once; if it’s still invalid, route to human review
Format Whether dates parse as ISO 8601 Try common formats as a fallback first, then retry if that fails
Range Whether amounts are positive and dates fall in a reasonable interval Flag it as an exception immediately; don’t retry

Retry only once, for a very practical reason: with the same source text, the same set of fields, and the same model, a second call will most likely produce the same kind of error. The real problem is usually that the field definitions are too vague, or the source text itself is missing information—neither of which more calls will fix.

Make that one retry count. Feed the original error message from the first attempt (for example, “amount is not a number”) back into the prompt along with the field’s description, and have the model extract again with that specific error in hand. The success rate is much higher than resending the identical prompt. If it still fails, put the source text, model output, and validation error into the manual review queue together, and keep this sample as the basis for revising the field definitions next round.

Common failure Symptom Fix
Field name drift Sometimes it’s amount, sometimes it’s total_amount Provide the full JSON skeleton in the prompt
Mixed units “12,000 yuan” shoved into a numeric field Split the value and unit into two fields
Table misalignment Rows and columns shift when column counts don’t match Convert the table to line-numbered plain text first
Long-text truncation Every field in the second half of the contract is empty Split by clause, extract segment by segment, then merge by number
Over-summarization A clause field turns into a one-sentence summary Explicitly require source excerpts

The first two come up in almost every project. Field name drift usually happens because the prompt has only a prose description and no JSON skeleton; mixed units happen when someone mistakes “a human can understand it” for “a program can parse it.” Both are solved by changing the field definitions, not by switching models.

article-6cbce8bf-en-image-3

FAQ

Q1: What is AI text extraction and structured processing?

It’s the process of reading unstructured or semi-structured text — emails, spreadsheets, contracts — and converting it into a database-ready format like JSON or CSV according to predefined fields. The two things that matter are “predefined” and “verifiable”: a human pins down the fields, and the output has to be something a program can check.

Q2: Which model should I choose for extraction tasks?

Split it into two tiers based on field difficulty. For routine tasks with fixed fields and short text, a low-cost model like glm-5.3-flash is enough; for long contract clauses with deeply nested structures, switch to glm-5.4. If you’re batch-processing historical documents with highly repetitive formats, factor the cache read price into your calculation. With APIYI apiyi.com you can switch models under the same key and compare them without opening separate accounts.

Q3: Why retry only once when validation fails?

Because a repeated call usually doesn’t change the error type. The two root causes — vague field definitions and missing information in the source text — are still there on the second call. Trying a few more times just multiplies the cost and delays the point where a human steps in.

Q4: How should I split long contracts?

Split by clause or by page, extract each segment along with an ID, and merge them by ID at the end. Splitting loses context, so cross-segment fields (say, the total amount on the first page and the installments on the last page) need a separate extraction pass.

Q5: How do I quickly get a usable API key and test quota?

Sign up at APIYI apiyi.com and you’ll get one — new users receive free test quota. Set base_url to https://api.apiyi.com/v1 and you can call it with your existing OpenAI SDK. Validate the fields on a few dozen real documents first, then scale up.

Q6: What are the known limitations of this pipeline?

Validation can only guarantee structure, not semantics. If the source text itself has typos, an ambiguous amount, or an unclear reference for “Party A”, the program won’t catch it. Also, models that don’t support structured output (like Gemini 4 Live) have to rely on prompt constraints plus local parsing as a fallback, which costs you both stability and field coverage.

Summary

Let’s recap the key points of this workflow:

  • Separation of responsibilities: the model reads the text, the program judges the data — don’t mix the two.
  • Start with few fields: 6 to 10 fields in the first version; expand once it works. Adding fields is cheaper than reworking the architecture.
  • Five elements of a prompt: format, type, convention for missing values, enums, units. Skip any one of them and you’ll be papering over it with retries.
  • Tiered models: use a low-cost model for routine extraction and step up to a pricier one only for the tough fields — don’t throw the top-tier model at everything.
  • Four validation checks: missing, type, enum, format. Anything range-related gets flagged as an anomaly outright.
  • Retry once only: resend with the specific error attached; if it still fails, hand it off to a human and keep the sample.

When you put this into practice, go in three steps: first pin down the field list and write it into the prompt, then pick a low-cost model that supports structured output and get the minimal pipeline working end to end, and finally lock the validation and retry rules into code. None of the three steps is complicated — the hard part is not skipping the third one.

To validate results quickly, we recommend APIYI at apiyi.com. The platform offers free credits and a unified interface across models, so the same code with a different model parameter is all it takes to run a comparison.


Author: APIYI Technical Team
Technical discussion: Feel free to reach us through the APIYI homepage; more resources are available at the docs.apiyi.com documentation center.

Related Articles

Similar Posts