How to Fix 'JSON parsing error during development' in AutoGen (TypeScript)

By Cyprian AaronsUpdated 2026-04-21
json-parsing-error-during-developmentautogentypescript

If you’re seeing JSON parsing error during development in AutoGen TypeScript, it usually means one of two things: the model returned text that AutoGen expected to parse as JSON, or your code passed malformed JSON into an AutoGen API that expects structured data. In practice, this shows up when you wire up tool calling, structured outputs, or agent-to-agent messages and the payload stops being valid JSON.

The fix is usually not in AutoGen itself. It’s almost always in the prompt shape, message formatting, or a tool/function schema mismatch.

The Most Common Cause

The #1 cause is asking the model for JSON but not constraining the output tightly enough. AutoGen then tries to parse something like markdown, commentary, or partially valid JSON and throws a parsing error.

A typical failure looks like this:

// Broken pattern
import { AssistantAgent } from "@autogen/agentchat";

const agent = new AssistantAgent({
  name: "support_agent",
  systemMessage: "Return JSON with fields: status and reason.",
});

const result = await agent.run("Tell me if this claim is approved.");

If the model responds with:

{
  "status": "approved",
  "reason": "Policy check passed"
}

you’re fine. But if it responds with:

Sure — here is the JSON:
{
  "status": "approved",
  "reason": "Policy check passed"
}

AutoGen can fail with errors like:

  • SyntaxError: Unexpected token S in JSON at position 0
  • JSON parsing error during development
  • Failed to parse model output as JSON

The fix is to force strict structured output and validate before AutoGen consumes it.

BrokenFixed
Loose prompt: “Return JSON”Strict schema + explicit instruction
Model may add proseModel constrained to valid JSON only
Parsing happens after generationValidation happens before use
// Fixed pattern
import { z } from "zod";
import { AssistantAgent } from "@autogen/agentchat";

const ClaimDecisionSchema = z.object({
  status: z.enum(["approved", "rejected"]),
  reason: z.string(),
});

const agent = new AssistantAgent({
  name: "support_agent",
  systemMessage:
    'Return ONLY valid JSON matching this schema: {"status":"approved"|"rejected","reason":"string"}',
});

const raw = await agent.run("Tell me if this claim is approved.");
const parsed = ClaimDecisionSchema.parse(JSON.parse(raw.toString()));

If your version of AutoGen supports structured output / response format settings, use that instead of relying on prompt discipline alone. Prompt-only JSON is fragile.

Other Possible Causes

1. You passed a JavaScript object where a JSON string was expected

This happens when a method expects serialized content and you send an object directly.

// Broken
await someTool.execute({
  payload: { claimId: "C-1001", approved: true },
});
// Fixed
await someTool.execute({
  payload: JSON.stringify({ claimId: "C-1001", approved: true }),
});

If the receiving side does JSON.parse(payload), an object will fail depending on how the library serializes it.

2. Your tool/function schema does not match the actual arguments

AutoGen tool calling will break if the schema says one thing and your implementation expects another.

// Broken schema/handler mismatch
const tools = [
  {
    name: "lookupPolicy",
    parameters: {
      type: "object",
      properties: {
        policy_id: { type: "string" },
      },
      required: ["policy_id"],
    },
  },
];

async function lookupPolicy(args: { policyId: string }) {
  return { ok: true };
}

Fix the field names exactly.

// Fixed
async function lookupPolicy(args: { policy_id: string }) {
  return { ok: true };
}

A mismatch here often surfaces as parsing failure because the tool invocation payload cannot be mapped cleanly.

3. You’re injecting unescaped text into a JSON template

Classic bug when building messages manually.

// Broken
const message = `{"query":"${userInput}"}`;

If userInput contains quotes or newlines, you get invalid JSON.

// Fixed
const message = JSON.stringify({
  query: userInput,
});

This matters a lot when user input comes from emails, claims notes, or chat transcripts.

4. The model returned fenced code blocks or extra commentary

Even if the content looks like JSON to a human, AutoGen may reject it if it includes markdown fences.

```json
{ "score": 0.91 }

Use a strict instruction:

```ts
systemMessage:
  'Output raw JSON only. Do not wrap in markdown fences. Do not include explanations.'

For production systems, don’t rely on this alone. Validate after generation.

How to Debug It

  1. Log the raw model output

    • Before any JSON.parse, print the exact string.
    • Look for markdown fences, leading text, trailing commas, or single quotes.
  2. Check where parsing happens

    • Search for JSON.parse, schema validation, or any AutoGen response parser.
    • If the stack trace mentions AssistantAgent, ToolCall, or StructuredOutput, you’re probably failing at response handling rather than transport.
  3. Validate your tool schemas

    • Compare parameter names in your tool definition vs handler signature.
    • Make sure required fields are present and types match exactly.
  4. Reproduce with a minimal prompt

    • Strip everything down to one agent and one message.
    • If it works with "Return {\"ok\":true}" but fails with real prompts, your issue is output contamination from instructions or context length.

A good debugging pattern is:

try {
  const raw = await agent.run(input);
  console.log("RAW OUTPUT:", raw);
  const parsed = JSON.parse(raw.toString());
  console.log("PARSED:", parsed);
} catch (err) {
  console.error("Parse failed:", err);
}

That tells you whether AutoGen produced invalid text or your downstream parser did.

Prevention

  • Use schema validation every time you expect structured output.
  • Prefer JSON.stringify() over manual string interpolation for payloads.
  • Keep prompts explicit:
    • “Return raw JSON only”
    • “No markdown”
    • “No explanation”
  • Test tool calls with malformed inputs early:
    • quotes in strings
    • multiline text
    • empty values
  • If your AutoGen version supports structured response formats, use them instead of prompt-only formatting

The short version: this error is rarely mysterious. In TypeScript projects using AutoGen, it usually comes down to untrusted model output or malformed input being treated as JSON too early. Lock down the schema, log raw outputs, and stop hand-building JSON strings by default.


Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides