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

推荐订阅源

B
Blog RSS Feed
Spread Privacy
Spread Privacy
T
Threatpost
C
Cisco Blogs
P
Palo Alto Networks Blog
AI
AI
Cyberwarzone
Cyberwarzone
NISL@THU
NISL@THU
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
T
Tor Project blog
Latest news
Latest news
AWS News Blog
AWS News Blog
D
Docker
S
SegmentFault 最新的问题
博客园 - 聂微东
WordPress大学
WordPress大学
Vercel News
Vercel News
S
Securelist
爱范儿
爱范儿
J
Java Code Geeks
Know Your Adversary
Know Your Adversary
S
Schneier on Security
Hugging Face - Blog
Hugging Face - Blog
F
Fortinet All Blogs
Last Week in AI
Last Week in AI
D
DataBreaches.Net
宝玉的分享
宝玉的分享
D
Darknet – Hacking Tools, Hacker News & Cyber Security
MongoDB | Blog
MongoDB | Blog
Engineering at Meta
Engineering at Meta
K
Kaspersky official blog
美团技术团队
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
量子位
博客园_首页
Attack and Defense Labs
Attack and Defense Labs
S
Secure Thoughts
Google Online Security Blog
Google Online Security Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
腾讯CDC
T
Threat Research - Cisco Blogs
雷峰网
雷峰网
有赞技术团队
有赞技术团队
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed
S
Security Affairs

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Structured Output From Local LLMs: JSON That Never Breaks (Ollama + Zod)
Pavel Espitia · 2026-06-14 · via DEV Community

A 1.5B model running on your laptop will return JSON that almost parses. The closing brace is missing. A trailing comma sneaks in. The whole thing is wrapped in a markdown fence with a chirpy "Sure! Here's your JSON:" on top. Cloud models do this too, but small local models do it constantly, and that is exactly where most "just prompt it harder" advice falls apart.

I wrote about validating LLM responses with Zod before: schemas as contracts, safeParse, extracting JSON from chaos. That post is the foundation. This one is the local-model-specific layer on top: Ollama's native JSON modes, retry loops that actually converge, repairing truncated output, and a single generateStructured<T>(schema) helper that ties it all together so you never hand-roll this again.

Two JSON Modes Most People Skip

Ollama gives you two ways to force structure before you ever touch Zod. Use them. They cut your parse-failure rate dramatically.

The first is format: "json". It constrains decoding so the model can only emit syntactically valid JSON. No markdown fences, no preamble, no trailing prose.

const res = await fetch("http://localhost:11434/api/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "qwen2.5-coder:7b",
    messages: [
      { role: "system", content: "Output a JSON object describing the code." },
      { role: "user", content: "function add(a, b) { return a + b }" },
    ],
    format: "json",
    stream: false,
    options: { temperature: 0 },
  }),
});

const data = await res.json();
const obj = JSON.parse(data.message.content); // already clean JSON

format: "json" guarantees valid syntax. It does not guarantee your shape. The model can still invent fields or skip required ones. That is what Zod is for.

The second mode is the one people miss: pass a full JSON Schema to format. Ollama then constrains generation to match the schema's structure, not just "valid JSON."

const schema = {
  type: "object",
  properties: {
    language: { type: "string" },
    purpose: { type: "string" },
    isPure: { type: "boolean" },
  },
  required: ["language", "purpose", "isPure"],
};

const res = await fetch("http://localhost:11434/api/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "qwen2.5-coder:7b",
    messages: [{ role: "user", content: "Describe: function add(a,b){return a+b}" }],
    format: schema,
    stream: false,
    options: { temperature: 0 },
  }),
});

You do not want to write JSON Schema by hand and keep it in sync with your TypeScript types. You already have a Zod schema. Convert it.

import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";

const CodeInfo = z.object({
  language: z.string(),
  purpose: z.string(),
  isPure: z.boolean(),
});

const jsonSchema = zodToJsonSchema(CodeInfo, { target: "openApi3" });
// pass jsonSchema as `format` to Ollama

One source of truth. Zod drives both the generation constraint and the runtime validation.

Mode Forces valid syntax Forces your shape Cost
Plain prompt No No Free, unreliable
format: "json" Yes No Negligible
format: <schema> Yes Mostly Slower decode, fewest retries

On small models, format: <schema> is worth the slightly slower decode because it turns most three-attempt loops into one.

Repairing Truncated JSON

Schema-constrained decoding still breaks in one nasty way: the model hits its token limit mid-object. You get {"vulnerabilities": [{"id": "V1", "severity": "hi and a dead parse.

Two defenses. First, raise num_predict so the model has room to finish.

options: { temperature: 0, num_predict: 2048 }

Second, attempt a repair before you give up. The common failure is unclosed brackets and a dangling partial value. You can salvage a surprising amount by trimming to the last complete token and closing what is open.

function repairJson(raw: string): string {
  let text = raw.trim();

  // Drop a trailing partial string/number/key after the last comma or brace
  const lastSafe = Math.max(text.lastIndexOf("}"), text.lastIndexOf("]"));
  if (lastSafe !== -1) text = text.slice(0, lastSafe + 1);

  // Walk the string, tracking open brackets outside of string literals
  const stack: string[] = [];
  let inString = false;
  let escaped = false;
  for (const ch of text) {
    if (escaped) { escaped = false; continue; }
    if (ch === "\\") { escaped = true; continue; }
    if (ch === '"') inString = !inString;
    if (inString) continue;
    if (ch === "{") stack.push("}");
    else if (ch === "[") stack.push("]");
    else if (ch === "}" || ch === "]") stack.pop();
  }

  // Close whatever is still open, innermost first
  while (stack.length) text += stack.pop();
  return text;
}

This is a last resort, not a primary strategy. If you trim a truncated array, you lose the cut-off element, which is fine for "best effort" reads and wrong for anything that must be complete. I gate it: try the raw parse, then the repaired parse, and if the repaired version loses data the schema requires, Zod rejects it and the retry loop takes over.

Retry Loops That Converge

The naive retry resends the same prompt and prays. It does not converge because nothing changed. The version that works feeds the specific Zod error back into the next attempt, the same idea from the earlier post but tuned for local models: lower the temperature on retries and tighten the instruction.

async function withRetry<T>(
  attempt: (feedback: string | null) => Promise<string>,
  parse: (raw: string) => z.SafeParseReturnType<unknown, T>,
  maxAttempts = 3,
): Promise<T> {
  let feedback: string | null = null;

  for (let i = 1; i <= maxAttempts; i++) {
    const raw = await attempt(feedback);
    const parsed = parse(raw);
    if (parsed.success) return parsed.data;

    feedback = parsed.error.issues
      .map((issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`)
      .join("\n");
  }

  throw new Error(`No valid output after ${maxAttempts} attempts:\n${feedback}`);
}

The discipline is: the model never sees a generic "that was wrong." It sees vulnerabilities.0.severity: Invalid enum value. Expected 'high', received 'High'. Small models self-correct from that. They cannot self-correct from silence.

Streaming and Parsing Together

You want streaming for UX (tokens appearing live) but you cannot parse JSON until it is complete. Resolve the tension by streaming for display and accumulating for parsing. Do not try to parse each chunk.

async function streamAccumulate(
  body: object,
  onToken?: (t: string) => void,
): Promise<string> {
  const res = await fetch("http://localhost:11434/api/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ ...body, stream: true }),
  });
  if (!res.body) throw new Error("No response body from Ollama");

  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  let full = "";
  let buffer = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });

    // Ollama streams newline-delimited JSON objects, one per chunk
    const lines = buffer.split("\n");
    buffer = lines.pop() ?? "";
    for (const line of lines) {
      if (!line.trim()) continue;
      const token = JSON.parse(line).message?.content ?? "";
      full += token;
      onToken?.(token);
    }
  }

  return full;
}

The trap people fall into: Ollama's /api/chat stream is newline-delimited JSON, one envelope per line, and a single network chunk can split a line in half. That is why buffer keeps the trailing partial line and only parses complete ones. Parse the accumulated full once the stream ends. Never on a partial.

The Helper That Ties It Together

Here is the piece I actually reuse. One generic function: pass a Zod schema, get back a typed, validated object, with schema-constrained generation, repair, and retry all handled.

import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";

interface StructuredOptions {
  model?: string;
  temperature?: number;
  maxAttempts?: number;
  numPredict?: number;
}

export async function generateStructured<T>(
  schema: z.ZodType<T>,
  system: string,
  user: string,
  opts: StructuredOptions = {},
): Promise<T> {
  const {
    model = "qwen2.5-coder:7b",
    temperature = 0,
    maxAttempts = 3,
    numPredict = 2048,
  } = opts;

  const jsonSchema = zodToJsonSchema(schema, { target: "openApi3" });

  const call = async (feedback: string | null): Promise<string> => {
    const messages = [
      { role: "system", content: system },
      { role: "user", content: user },
    ];
    if (feedback) {
      messages.push({
        role: "user",
        content: `Your last response failed validation:\n${feedback}\nReturn corrected JSON only.`,
      });
    }

    const res = await fetch("http://localhost:11434/api/chat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        model,
        messages,
        format: jsonSchema,
        stream: false,
        options: { temperature, num_predict: numPredict },
      }),
    });

    const data = await res.json();
    return data.message?.content ?? "";
  };

  const parse = (raw: string): z.SafeParseReturnType<unknown, T> => {
    for (const candidate of [raw, repairJson(raw)]) {
      try {
        return schema.safeParse(JSON.parse(candidate));
      } catch {
        // not parseable, try the next candidate
      }
    }
    // Force a Zod failure with a useful message
    return schema.safeParse(undefined);
  };

  return withRetry(call, parse, maxAttempts);
}

Usage is the part that makes the abstraction worth it.

const CodeReview = z.object({
  summary: z.string(),
  issues: z.array(z.object({
    severity: z.enum(["high", "medium", "low"]),
    line: z.number().int().positive(),
    note: z.string(),
  })),
  riskScore: z.coerce.number().min(0).max(100),
});

const review = await generateStructured(
  CodeReview,
  "You are a code reviewer. Output JSON only.",
  sourceCode,
  { model: "ollama-friendly", maxAttempts: 3 },
);

// review is fully typed as z.infer<typeof CodeReview>, validated, never undefined

review.issues[0].severity is typed. Your editor autocompletes it. If the model returns "High", the z.enum rejects it, the error flows back into the retry, and the next attempt fixes it. You wrote the schema once.

What I Learned Wiring This Into spectr-ai

  1. Constrain generation, then validate. format: <schema> and Zod are not redundant. The first reduces how often you fail; the second catches what slips through.
  2. One Zod schema, two jobs. zodToJsonSchema keeps the generation constraint and the runtime check from drifting apart.
  3. Repair is a fallback, never the plan. Closing brackets salvages reads. It silently drops data on truncated arrays, so let Zod reject anything that must be complete.
  4. Stream for the eyes, accumulate for the parser. Buffer newline-delimited chunks, parse once at the end.
  5. Retries need the actual error. Feed Zod's path-and-message back in. Small models converge from specifics, not from "try again."

This is the exact pattern spectr-ai uses to run a smart-contract audit fully locally with --model ollama:qwen2.5-coder:1.5b. Every byte the model emits passes through generateStructured. The 1.5B model still fumbles the JSON. The user never sees it.