Spring › Spring-AI

Verifying LLM search outputs against public API ground truth

Stop LLM hallucinations in legal discovery by pairing deterministic server normalization with real-time 3-tuple cross-checks against a public precedent API.

Verifying LLM search outputs against public API ground truth

Pairing an LLM with live web search doesn’t eliminate hallucinations. Even with Google Search Grounding enabled, models still invent case numbers, mangle abbreviated court names, confuse publication dates with ruling dates, and fabricate links. In this post, I’ll walk through a two-stage verification pipeline that treats LLM output strictly as an untrusted lead and confirms facts via deterministic server rules and real-time public Open API cross-checks.

Tested with Spring Boot, Kotlin, Google GenAI SDK, and Korea’s National Law Information Center Open API.


Why web-grounded LLM outputs still hallucinate

In my legal precedent platform (demo-backend-server), a daily batch job (judgment-discovery) uses Gemini with Google Search Grounding to find major criminal rulings reported in the news and propose them as candidates for review (see preserving Gemini Search Grounding metadata with the GenAI SDK for the retrieval layer).

As soon as I ran the first prototype against real news articles, four hallucination patterns showed up:

  1. Fabricated case numbers: Even when an article stated “the case number was not disclosed,” the model invented a valid-looking docket number like 2026-CR-9999.
  2. Inconsistent court abbreviations: News outlets mix shorthand court names and panel numbers (for example, Seoul High Ct. Criminal Div. 1 or Suwon Dist. Ct. Ansan Branch), and the model either copied the shorthand verbatim or distorted it into a nonexistent court.
  3. Report date vs. ruling date confusion: The model often extracted the article’s publication date as the court ruling date, or surfaced an old retrospective case as a fresh ruling.
  4. Fabricated source URLs: When asked for citations, the model occasionally generated blog or news URLs that never appeared in the search grounding metadata.
1
2
[Unverified LLM output reaches production]
Fake case number persisted -> Nonexistent ruling published -> Legal data trust collapses

In a legal data service, publishing even one fabricated ruling destroys trust. I set a hard boundary: LLM output is only an untrusted observation, never ground truth.


Two-stage ground truth architecture

The pipeline separates Stage 1 (deterministic server normalization) from Stage 2 (exact 3-tuple cross-check against the official public Open API):

flowchart TD
    A["Gemini search + JSON structuring"] --> B["Stage 1: Server rules (DiscoveryRules)"]

    subgraph S1["Stage 1: Deterministic normalization"]
        B --> B1{"Source in groundingChunks?"}
        B1 -->|"Unverified URL"| R1["Drop source / reject candidate"]
        B1 -->|"Verified"| B2{"Case number bounded in text?"}
        B2 -->|"Missing in text"| R2["Set caseNumber = null"]
        B2 -->|"Present"| B3["Normalize court alias & branch"]
        B3 --> B4["Verify ruling date & build dedup key"]
    end

    B4 --> C[("DB: JudgmentDiscovery (NEW / AWAITING_SOURCE)")]
    C --> D["Stage 2: Public API verifier (DiscoveryVerifier)"]

    subgraph S2["Stage 2: Official API cross-check"]
        D --> D1["LawPrecedentClient.list(caseNumber)"]
        D1 --> D2{"Exact 3-tuple match?"}
        D2 -->|"1 exact match"| D3{"Supported JSON source?"}
        D3 -->|"Supported"| V["Transition to VERIFIED (lock precSerial)"]
        D3 -->|"HTML-only source"| RV["Transition to NEEDS_REVIEW"]
        D2 -->|"0 matches"| AW["AWAITING_SOURCE (retry 14 days)"]
        D2 -->|"Mismatch or >1 match"| RV
    end

    V --> H["Admin review & approval (HITL)"]
    H --> IMP["Import official full text into raw_judgments"]

Core design rules and trade-offs

Matching strategyPrecisionRecallRight for legal ground truth?
Embedding / cosine similarityLowHighNo — confuses 1st-instance, appeal, and Supreme Court rulings
Case number onlyMediumHighNo — docket prefixes can collide across courts or partial queries
Exact 3-tuple (case number + court + ruling date)100%Controlled via 14-day retryYes — isolates the exact official record

When not to enforce strict 3-tuple blocking: If you’re building an exploratory research assistant or internal news digest where approximate matches are acceptable, strict 3-tuple rejection will feel overly rigid. Use it only when your system writes into a canonical, authoritative datastore where a false positive costs far more than a delayed import.


Stage 1: Deterministic normalization and boundary checks

Stage 1 runs in pure Kotlin before any candidate touches the database. It checks every extracted field against the raw search text and the verified groundingChunks list.

Note that in production my app parses Korean statutory court names and docket codes from Korea’s National Law Information Center (law.go.kr). In the snippets below, I’ve localized the comments, error messages, and court-normalization rules to English so the algorithm is easy to follow regardless of locale.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// src/main/kotlin/com/example/server/discovery/application/DiscoveryRules.kt
package com.example.server.discovery.application

import com.example.server.discovery.domain.DiscoveryInstance
import com.example.server.discovery.domain.DiscoveryRecency
import java.time.LocalDate
import tools.jackson.databind.JsonNode

object DiscoveryRules {
    private val CASE_NUMBER = Regex("^\\d{2,4}[A-Z]{1,4}\\d{1,7}$")
    private val SOURCE_ID = Regex("^S(\\d{1,3})$")

    fun check(node: JsonNode, search: DiscoverySearchResult, from: LocalDate, to: LocalDate): CandidateCheck {
        val title = text(node, "title")?.take(200)
            ?: return CandidateCheck.Rejected("(untitled)", "Missing candidate title.")
        if (text(node, "stage") == "PRE_JUDGMENT") return CandidateCheck.PreJudgment(title)
        if (text(node, "stage") != "JUDGMENT") return CandidateCheck.Rejected(title, "Invalid judgment stage.")
        val summary = text(node, "issueSummary")?.take(2000)
            ?: return CandidateCheck.Rejected(title, "Missing issue summary.")

        val notes = mutableListOf<String>()

        // 1. Source whitelist: accept only indices present in Google Search groundingChunks
        val sources = node.path("sources").takeIf { it.isArray }?.toList().orEmpty().mapNotNull { item ->
            val index = SOURCE_ID.matchEntire(text(item, "id").orEmpty())?.groupValues?.get(1)?.toInt()
            val source = index?.let { search.sources.getOrNull(it - 1) }
            if (source == null) {
                notes += "Dropped source not found in search grounding metadata."
                return@mapNotNull null
            }
            SourceInput(source, domain(source), date(text(item, "reportedDate"))?.takeIf { it <= to })
        }.distinctBy { it.source.url }

        if (sources.isEmpty()) return CandidateCheck.Rejected(title, "No verified search sources attached.")

        val body = compact(search.text)

        // 2. Case number format and numeric-boundary check against the article body
        val caseNumber = text(node, "caseNumber")?.let(::compact)?.let { value ->
            if (CASE_NUMBER.matches(value) && bounded(value, search.text)) value
            else {
                notes += "Dropped unverified case number ($value) not present in search text."
                null
            }
        }

        // 3. Official court name normalization and text presence check
        val courtName = text(node, "courtName")?.take(100)?.let { value ->
            court(value, body) ?: run {
                notes += "Dropped unverified court name ($value) not present in search text."
                null
            }
        }

        // 4. Ruling date presence check across common date formats
        val sentenceDate = text(node, "sentenceDate")?.let { value ->
            date(value)?.takeIf { it <= to && mentioned(it, search.text) } ?: run {
                notes += "Dropped unverified ruling date ($value) not present in search text."
                null
            }
        }

        val modelInstance = runCatching {
            DiscoveryInstance.valueOf(text(node, "instance").orEmpty())
        }.getOrDefault(DiscoveryInstance.UNKNOWN)

        val recency = when {
            sentenceDate == null -> DiscoveryRecency.UNKNOWN
            sentenceDate < from -> DiscoveryRecency.RESURFACED
            else -> DiscoveryRecency.RECENT_SENTENCE
        }

        return CandidateCheck.Accepted(
            CandidateInput(
                title = title,
                issueSummary = summary,
                issueEvidence = text(node, "issueEvidence")?.take(2000),
                caseNumber = caseNumber,
                courtName = courtName,
                sentenceDate = sentenceDate,
                instance = instanceOf(caseNumber) ?: modelInstance,
                recency = recency,
                sources = sources,
                notes = notes.distinct()
            )
        )
    }

    /**
     * Strip panel suffixes (e.g., "Criminal Div. 1") and expand media shorthand
     * into the canonical statutory court name, confirming it appears in the article.
     */
    fun court(value: String, compactBody: String): String? {
        val expanded = value.trim()
            .replace(Regex("\\s+(Criminal|Civil)\\s+Div\\.\\s*\\d+$", RegexOption.IGNORE_CASE), "")
            .replace("High Ct.", "High Court")
            .replace("Dist. Ct.", "District Court")
        val canonical = Regex("^(.*?(?:Court|Branch))").find(expanded)?.groupValues?.get(1)?.trim() ?: return null
        val shortForm = canonical.replace("High Court", "High Ct.").replace("District Court", "Dist. Ct.")
        if (compact(canonical) !in compactBody && compact(shortForm) !in compactBody) return null
        return canonical.take(100)
    }

    /** Derive court level from the docket code whenever it is unambiguous. */
    fun instanceOf(caseNumber: String?): DiscoveryInstance? {
        val code = caseNumber?.let { Regex("^\\d+([A-Z]+)\\d+$").matchEntire(it)?.groupValues?.get(1) } ?: return null
        return when (code) {
            "SC" -> DiscoveryInstance.SUPREME
            "AP" -> DiscoveryInstance.APPEAL
            "CR", "CV" -> DiscoveryInstance.FIRST
            else -> null
        }
    }

    /**
     * Allow optional whitespace between characters, but require non-digit boundaries.
     * Prevents false matches like "2026CR1" matching "2026CR123" or "2026.3.1" matching "2026.3.15".
     */
    private fun bounded(value: String, text: String) =
        Regex("(?<!\\d)" + value.map { Regex.escape(it.toString()) }.joinToString("\\s*") + "(?!\\d)")
            .containsMatchIn(text)

    fun mentioned(date: LocalDate, text: String): Boolean {
        val y = date.year; val m = date.monthValue; val d = date.dayOfMonth
        val forms = listOf(
            "$y.$m.$d",
            "%d.%02d.%02d".format(y, m, d),
            "%d-%02d-%02d".format(y, m, d),
            "%d%02d%02d".format(y, m, d),
            "$m/$d/$y"
        )
        return forms.any { bounded(it, text) }
    }
}

Why lookaround boundaries (?<!\d)...(?!\d) matter: A naive String.contains("2026CR1") falsely matches 2026CR123 in the article text. Stripping all whitespace upfront is just as risky: "Oct 8 2026CR1" glues the day number onto the case year and breaks digit boundaries. Matching directly against the original text with \s* between characters and negative digit lookarounds avoids both bugs.

Terminal output showing court alias normalization and boundary verification tests Figure 1. Stage 1 normalization unit test log: fabricated case numbers drop to null while media court aliases normalize to canonical names.


Stage 2: Exact 3-tuple verification against the public API

Candidates that pass Stage 1 enter the database as NEW or AWAITING_SOURCE. Every 30 minutes, a verification worker (judgment-discovery-verify) queries the official public precedent API and checks for an exact 1-to-1 match on (case number, court name, ruling date).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// src/main/kotlin/com/example/server/discovery/application/DiscoveryVerifier.kt
package com.example.server.discovery.application

import com.example.server.judgment.application.LawPrecedentClient
import com.example.server.judgment.dto.LawPrecedentSummary
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import org.springframework.stereotype.Component

@Component
class DiscoveryVerifier(private val client: LawPrecedentClient) {

    fun verify(target: VerificationTarget, check: () -> Unit = {}): VerificationOutcome {
        val caseNumber = target.caseNumber
            ?: return VerificationOutcome.Review("Missing case number: verify and fill in case details from the article.")

        // The public API performs substring search on caseNumber, so paginate up to MAX_PAGES
        val items = mutableListOf<LawPrecedentSummary>()
        var page = 1
        while (true) {
            val result = client.list(page, 100, caseNumber = caseNumber, check = check)
            items += result.items
            if (result.items.isEmpty() || page.toLong() * 100 >= result.totalCount) break
            if (page == MAX_PAGES) {
                if (items.none { compact(it.caseNumber) == caseNumber }) {
                    return VerificationOutcome.Review(
                        "Public API returned ${result.totalCount} records for $caseNumber; " +
                        "no exact match found within the first ${MAX_PAGES * 100} rows."
                    )
                }
                break
            }
            page++
        }
        return evaluate(target, items)
    }

    fun evaluate(target: VerificationTarget, items: List<LawPrecedentSummary>): VerificationOutcome {
        // 1. Exact case-number filter after stripping whitespace
        val exact = items.filter { compact(it.caseNumber) == target.caseNumber }
        if (exact.isEmpty()) {
            return VerificationOutcome.Awaiting("Case number ${target.caseNumber} is not yet published in the official API.")
        }

        if (target.courtName == null || target.sentenceDate == null) {
            return VerificationOutcome.Review("Court or ruling date missing. Official candidates: ${describe(exact)}")
        }

        // 2. Exact 3-tuple match (caseNumber + courtName + sentenceDate)
        val matches = exact.filter {
            compact(it.courtName) == compact(target.courtName) && date(it.sentenceDate) == target.sentenceDate
        }

        return when (matches.size) {
            0 -> VerificationOutcome.Review("Case number matched, but court or ruling date differed: ${describe(exact)}")
            1 -> matches.single().let {
                // 3. Confirm the official source provides full JSON text (skip HTML-only feeds)
                if (it.dataSourceName != null && it.dataSourceName !in SUPPORTED_SOURCES) {
                    VerificationOutcome.Review("Unsupported HTML-only source (${it.dataSourceName}); skipping auto-import.")
                } else {
                    VerificationOutcome.Verified(it.precSerial, it.dataSourceName)
                }
            }
            else -> VerificationOutcome.Review("Multiple official records matched the same 3-tuple: ${describe(matches)}")
        }
    }

    private fun describe(items: List<LawPrecedentSummary>) = items.take(5).joinToString(", ") {
        "serial ${it.precSerial} (${it.courtName ?: "unknown court"}, ${it.sentenceDate ?: "unknown date"})"
    } + if (items.size > 5) " and ${items.size - 5} more" else ""

    private fun compact(value: String?) = value?.replace(Regex("\\s+"), "")

    private fun date(value: String?): LocalDate? = value?.replace(Regex("\\D"), "")?.takeIf { it.length == 8 }
        ?.let { runCatching { LocalDate.parse(it, DateTimeFormatter.BASIC_ISO_DATE) }.getOrNull() }

    companion object {
        /** Allow only official data sources that reliably serve full JSON bodies. */
        val SUPPORTED_SOURCES = setOf("SupremeCourt", "WorkersCompPrecedent")
        const val MAX_PAGES = 5
    }
}

Side-by-side comparison of news-extracted fields and official precedent API response Figure 2. Cross-checking news-extracted fields against the official precedent API. Only a 100% 3-tuple match locks in the official precSerial.


State machine lifecycle and human-in-the-loop safety net

News articles go live on the day of a ruling, while official court portals often take days or up to two weeks to publish the full text. Treating an initial 0 matches API response as a hallucination would throw away valid leads.

Instead, I modeled an explicit state machine with a 14-day retry window and a human-in-the-loop (HITL) review queue (for broader HITL patterns, see Human-in-the-Loop and agent safety patterns):

stateDiagram-v2
    [*] --> NEW: Stage 1 accepted

    NEW --> AWAITING_SOURCE: 0 matches in official API
    NEW --> VERIFIED: Single exact 3-tuple match
    NEW --> NEEDS_REVIEW: Missing fields, mismatch, or >1 match

    AWAITING_SOURCE --> VERIFIED: Found during scheduled retry
    AWAITING_SOURCE --> NEEDS_REVIEW: Still missing after 14 days

    VERIFIED --> IMPORTED: Admin approves official import
    VERIFIED --> REJECTED: Admin rejects

    NEEDS_REVIEW --> NEW: Admin corrects metadata
    NEEDS_REVIEW --> REJECTED: Admin rejects
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// src/main/kotlin/com/example/server/discovery/domain/JudgmentDiscovery.kt
package com.example.server.discovery.domain

enum class DiscoveryStatus(val label: String) {
    NEW("Pending check"),
    NEEDS_REVIEW("Needs review"),
    AWAITING_SOURCE("Awaiting official record"),
    VERIFIED("Verified"),
    IMPORTED("Imported"),
    REJECTED("Rejected")
}

fun applyVerification(id: Long, outcome: VerificationOutcome, now: Instant = Instant.now()) {
    val discovery = find(id)
    if (discovery.status == DiscoveryStatus.IMPORTED || !discovery.open) return

    when (outcome) {
        is VerificationOutcome.Verified -> {
            val duplicate = discoveries.existsByPrecSerialAndStatusAndIdNot(outcome.precSerial, DiscoveryStatus.IMPORTED, id) ||
                            discoveries.existsByPrecSerialAndStatusAndIdNot(outcome.precSerial, DiscoveryStatus.VERIFIED, id)
            if (duplicate) {
                discovery.needsReview("Duplicate of another verified/imported candidate (serial ${outcome.precSerial}).", now)
            } else {
                discovery.verified(outcome.precSerial, judgments.findByPrecSerial(outcome.precSerial)?.id, now)
                discovery.officialDataSourceName = outcome.dataSourceName
            }
        }
        is VerificationOutcome.Review -> discovery.needsReview(outcome.reason, now)
        is VerificationOutcome.Awaiting -> {
            val deadline = discovery.firstDiscoveredAt.plus(Duration.ofDays(properties.sourceWaitDays.toLong()))
            if (now.isAfter(deadline)) {
                discovery.needsReview(
                    "Official record not found within ${properties.sourceWaitDays} days. " +
                    "Review public court records manually. (${outcome.reason})", now
                )
            } else {
                discovery.awaitSource(outcome.reason, now.plus(properties.verifyRetryInterval), now)
            }
        }
    }
}
  1. Scheduled retries for AWAITING_SOURCE: Unregistered rulings stay in the queue and re-check on the configured retry interval.
  2. Graceful 14-day escalation: Records still missing after 14 days move to NEEDS_REVIEW instead of being deleted, prompting an operator to check public court portals manually.
  3. Manual correction loop: If a news article had a typo in the case number, an admin edits the candidate in the console, resetting its status to NEW so Stage 2 runs cleanly from scratch.

Admin console showing a verified judgment candidate ready for official import Figure 3. Candidate detail screen in VERIFIED state after passing the 3-tuple API check, ready for one-click import of the official JSON full text.


Unit tests and production checklist

Because Stage 1 is pure Kotlin with no external dependencies, every boundary edge case runs in milliseconds under JUnit 5:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// src/test/kotlin/com/example/server/discovery/DiscoveryRulesTest.kt
package com.example.server.discovery

import com.example.server.discovery.application.DiscoveryRules
import com.example.server.discovery.domain.DiscoveryInstance
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDate

class DiscoveryRulesTest {

    @Test
    fun `accepts only dates matching exact numeric boundaries in article text`() {
        val date = LocalDate.of(2026, 10, 2)
        listOf("2026. 10. 2. ruling", "2026.10.02 ruling", "2026-10-02", "10/2/2026").forEach {
            assertThat(DiscoveryRules.mentioned(date, it)).describedAs(it).isTrue()
        }

        // Reject partial numeric overlaps
        assertThat(DiscoveryRules.mentioned(date, "2026-10-20 ruling")).isFalse()
        assertThat(DiscoveryRules.mentioned(LocalDate.of(2026, 3, 1), "2026.3.15 ruling")).isFalse()
        assertThat(DiscoveryRules.mentioned(LocalDate.of(2026, 1, 2), "11/2/2026 ruling")).isFalse()
    }

    @Test
    fun `normalizes media court aliases and rejects courts absent from text`() {
        val body = "SeoulHighCt.CriminalDiv.1ruled...SuwonDist.Ct.AnsanBranch...".replace(" ", "")

        assertThat(DiscoveryRules.court("Seoul High Ct. Criminal Div. 1", body)).isEqualTo("Seoul High Court")
        assertThat(DiscoveryRules.court("Seoul High Court", body)).isEqualTo("Seoul High Court")
        assertThat(DiscoveryRules.court("Suwon Dist. Ct. Ansan Branch", body)).isEqualTo("Suwon District Court Ansan Branch")

        // Reject hallucinated court names not present in the source text
        assertThat(DiscoveryRules.court("Busan District Court", body)).isNull()
        assertThat(DiscoveryRules.court("Criminal Div. 1", body)).isNull()
    }

    @Test
    fun `derives court instance from docket code`() {
        assertThat(DiscoveryRules.instanceOf("2026CR123")).isEqualTo(DiscoveryInstance.FIRST)
        assertThat(DiscoveryRules.instanceOf("2026AP45")).isEqualTo(DiscoveryInstance.APPEAL)
        assertThat(DiscoveryRules.instanceOf("2026SC678")).isEqualTo(DiscoveryInstance.SUPREME)
    }
}

Production checklist

  • Split discovery from verification: Let the LLM read unstructured news and propose candidates, but validate every identifier with deterministic regexes and official APIs.
  • Quarantine candidates in a staging table: Never write LLM-extracted rows directly into your public table (judgments). Stage them in judgment_discoveries until ground truth confirms them.
  • Account for publication lag: Build an AWAITING_SOURCE retry state with a clear expiry window instead of discarding leads that haven’t hit the upstream API yet.
  • Route the ambiguous 1% to humans: Trying to auto-resolve every typo, duplicate, or HTML-only source in code creates fragile heuristics. A simple NEEDS_REVIEW queue with a manual edit button keeps data quality at 100%.
This post is licensed under CC BY 4.0 by the author.