惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Proofpoint News Feed
宝玉的分享
宝玉的分享
人人都是产品经理
人人都是产品经理
博客园_首页
爱范儿
爱范儿
博客园 - 叶小钗
aimingoo的专栏
aimingoo的专栏
S
SegmentFault 最新的问题
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
Microsoft Security Blog
Microsoft Security Blog
Blog — PlanetScale
Blog — PlanetScale
博客园 - 【当耐特】
Y
Y Combinator Blog
量子位
博客园 - 三生石上(FineUI控件)
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
The Blog of Author Tim Ferriss
月光博客
月光博客
有赞技术团队
有赞技术团队
Apple Machine Learning Research
Apple Machine Learning Research
A
About on SuperTechFans

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
LLM-powered extraction kept silently corrupting my databa...
Joyal Seejo · 2026-06-12 · via DEV Community

I've been building an extraction API for the past month. The use case is specific — reading informal WhatsApp orders in mixed Hindi/English/Malayalam and turning them into structured records for Indian distributors. Something like:

"bhai 50 bags opc 53 cement calicut tuesday urgent"

needs to become:

{
  "product": "OPC Grade 53 Cement",
  "quantity": 50,
  "unit": "bags",
  "location": "Calicut",
  "delivery_date": "Tuesday",
  "urgency": "urgent"
}

Regex dies on the first message. Template matching dies on the second. The only approach that actually works is LLMs. But the moment I put it in production I hit a problem nobody warned me about.

LLMs lie about returning JSON

Not in a hallucination sense. In a more annoying sense — they return almost JSON. Things like:

Here's the extracted data:


json
{ "product": "cement", "quantity": 50 }


plaintext

Or:

Based on the message, I can identify:
{ "product": "cement", "quantity": "50" }
Note: quantity returned as string since units weren't explicit.


javascript

Both of these throw a JSON.parse error. Neither throws any other error. If you're not checking carefully, you silently skip the record or crash the job.

The failure modes I documented:

  • JSON wrapped in markdown code fences
  • Explanatory text before or after the JSON
  • Fields present in schema but missing from response (not null, just absent)
  • Type mismatches (quantity: "50" instead of quantity: 50)
  • Field name variations (delivery_date vs date_of_delivery)

None of these are obvious bugs. They all look like successful API calls.

The fix that actually worked

First instinct: strip markdown fences with regex. That works until the model puts fences inside the JSON for a nested code field. Then it doesn't.

What actually worked was corrective prompting. When parsing fails, instead of retrying with the same prompt, you feed the bad response back and tell the model specifically what it did wrong:

async function extract(input, schema, maxRetries = 2) {
  const messages = [
    { role: 'user', content: buildPrompt(input, schema) }
  ]

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const response = await anthropic.messages.create({
      model: selectModel(input, schema),
      messages
    })

    const text = response.content[0].text

    try {
      const parsed = JSON.parse(text)
      return { data: parsed, attempts: attempt + 1 }
    } catch {
      // don't just retry — tell it what it did wrong
      messages.push(
        { role: 'assistant', content: text },
        { role: 'user', content: 
          'That response was not valid JSON. Return ONLY a raw JSON object. ' +
          'First character must be {. Last character must be }. Nothing else.' 
        }
      )
    }
  }

  throw new ExtractorError('Failed after retries')
}

In practice about 90% of parse failures resolve on the second attempt with this approach. The model usually knows it produced bad output — it just needs to be explicitly called out on it.

The thing I didn't expect to need: per-field confidence

Once JSON was reliable, I hit the next problem. The model would confidently return:

{ "delivery_date": "Tuesday" }

But was that Tuesday this week or next week? Was "calicut" a city name, a warehouse code, or a customer shorthand? The extraction worked but I had no idea how much to trust individual fields.

I added a _meta object to the schema contract:

{
  "product": "OPC Grade 53 Cement",
  "quantity": 50,
  "delivery_date": "Tuesday",
  "_meta": {
    "confidence": 0.87,
    "field_confidences": {
      "product": 0.99,
      "quantity": 0.97,
      "delivery_date": 0.61
    },
    "warnings": ["delivery_date is ambiguous — no week specified"]
  }
}

This changes the extraction from a black box into something auditable. A downstream system can auto-approve high-confidence extractions and flag low-confidence ones for human review. For the distributor use case this matters a lot — a wrong delivery date costs real money.

Testing LLM-dependent code without burning API credits

This took me an embarrassingly long time to figure out. The answer is obvious in retrospect: mock the SDK entirely.

// __tests__/mocks/anthropic.js
jest.unstable_mockModule('@anthropic-ai/sdk', () => ({
  default: class MockAnthropic {
    messages = {
      create: jest.fn().mockResolvedValue({
        content: [{
          text: JSON.stringify({
            product: 'OPC Grade 53 Cement',
            quantity: 50,
            _meta: { confidence: 0.97, field_confidences: {}, warnings: [] }
          })
        }],
        usage: { input_tokens: 150, output_tokens: 40 }
      })
    }
  }
}))

Now the test suite runs in under 10 seconds and calls zero real API endpoints. 56 tests, no Anthropic bill.

What I ended up with

The full thing is open source — schema-defined extraction with the reliability layer, per-field confidence, retry logic, dead letter queue for persistent failures, webhook delivery logs, and a sandbox mode (mx_test_ keys) that returns instant mock data without hitting the API.

7 pre-built schemas included: invoice, receipt, purchase order, shipment, support ticket, lead contact, job application.

https://github.com/joyalseejo/morphex-api.git

The original problem (Indian B2B text in mixed languages) is still the primary use case I'm building toward. But the reliability layer turned out to be useful for any LLM extraction pipeline regardless of language or domain.

If you've hit the silent JSON corruption problem before, curious what approach you used.