Skip to content
Blog

Customizing Agent Output Serialization: From Markdown to Raw JSON

Force structured agent output with output_schema and output_key, capture parsed values in session state, and reformat raw LLM text with after_model_callback and --jsonl.

Published on • November 24, 2026

AI Assistant

By default an LlmAgent answers the way chat models answer: a friendly Markdown string inside event.content.parts[0].text. That is perfect for a person and useless for the next service in your pipeline, which wants {"capital": "Paris"} — not a paragraph that mentions Paris.

ADK gives you three levels of control over that boundary: declare the shape the model must produce (output_schema), capture the parsed result in session state (output_key), and rewrite responses after they come back (after_model_callback). This post moves from Markdown to raw JSON in that order, with the caveats that bite in production.

LevelMechanismGuarantees
1Instruction text + few-shot examplesBest effort; model may still fence the JSON
2output_schema + output_keyFinal response conforms; parsed value lands in session.state
3after_model_callbackYou rewrite or validate the LlmResponse yourself
4--jsonl / POST /runThe run itself serializes to JSON for a pipeline

Level 1: ask for JSON in the instruction

The cheapest intervention is prose. instruction is where you state the desired format, and ADK’s own guidance is to provide few-shot examples directly in the instruction for complex output formats:

agent = LlmAgent(
    model="gemini-flash-latest",
    name="capital_agent",
    instruction="""You are a Capital Information Agent.
Given a country, respond ONLY with a JSON object containing the capital.
Format: {"capital": "capital_name"}
Example: {"country": "France"} -> {"capital": "Paris"}""",
)

This is still best-effort: the model may wrap the JSON in a Markdown fence, which is exactly the problem the next levels remove.

Level 2: enforce the contract with output_schema

output_schema defines the desired output structure; if set, the agent’s final response must be a JSON string conforming to it. In Python the supported schema types are a Pydantic model class (e.g. MySchema), lists of primitives (list[str], list[int], list[bool], list[float]), dict, and google.genai.types.Schema:

from pydantic import BaseModel, Field

class CapitalOutput(BaseModel):
    capital: str = Field(description="The capital of the country.")

structured_agent = LlmAgent(
    model="gemini-flash-latest",
    name="structured_capital_agent",
    instruction="Respond ONLY with a JSON object containing the capital.",
    output_schema=CapitalOutput,   # enforce JSON output
    output_key="found_capital",    # store result under state['found_capital']
)

Downstream code reads the parsed value straight from state — no text extraction, no json.loads:

async for event in runner.run_async(user_id=..., session_id=..., new_message=...):
    if event.is_final_response():
        capital = session.state["found_capital"]   # already a dict
        print(capital["capital"])                  # "Paris"

output_key closes the loop: the agent’s final response is saved to session.state[output_key] automatically. When output_schema is also set, ADK parses the response against the schema first and stores the parsed value — a BaseModel schema is stored as a dict, and a list[BaseModel] schema as a list[dict] — instead of the raw text.

Schema + tools together is supported in Python: tools stay available while the agent works and the schema applies only to the final response. Some models accept both in one request (Gemini models on Google Cloud, and LiteLlm models whose provider supports response schemas), and ADK passes them through directly. For other models ADK adds a set_model_response function tool and instructs the model to return its final answer through it — which may not work reliably, so the docs suggest sub-agents that handle output formatting separately.

Level 3: rewrite the response with after_model_callback

When you cannot change the schema, change the bytes. after_model_callback runs just after an LlmResponse is received from the LLM, before the agent processes it; returning a new LlmResponse replaces the model’s response:

import json, re

def strip_markdown_to_json(callback_context, llm_response) -> LlmResponse:
    text = llm_response.content.parts[0].text
    fenced = re.search(r"```(?:json)?\s*(.*?)```", text, re.S)
    raw = fenced.group(1) if fenced else text
    parsed = json.loads(raw)                    # raises if the model misbehaved
    callback_context.state["last_structured"] = parsed   # keep it for later steps
    llm_response.content = types.Content(
        role="model", parts=[types.Part.from_text(json.dumps(parsed))]
    )
    return llm_response

Returning None instead leaves the response untouched, so the same hook doubles as a passthrough logger. The documented use cases are exactly this territory: reformatting responses, censoring sensitive information, and parsing structured data from the LLM response into callback_context.state.

Level 4: serialize the whole run with --jsonl

Outside the agent, the CLI has its own serialization switch: adk run --jsonl outputs structured JSONL instead of human-readable text, which is the right hand-off point for headless pipelines (see adk-headless-cli-streaming.md). At the HTTP layer, POST /run returns the complete event list as JSON — including actions.stateDelta — so a consumer gets structure without waiting for a stream.

Pitfalls

  • Do not set response_schema in generate_content_config. Python ADK raises a ValueError if generate_content_config sets tools, system_instruction, response_schema, or http_options.base_url; route those through the agent’s tools, instruction, and output_schema fields instead.
  • input_schema is not for user messages. It only applies when the agent is invoked as a tool via AgentTool.
  • Validation failure is not an exception in every SDK. Java and Kotlin check only the structure (type, required, nullable, anyOf, items) and, on failure, log the error and store the raw response string under output_key; Python validates against the Pydantic model itself, so declared constraints are enforced there.
  • Never parse streaming chunks. Partial events are incomplete by definition — accumulate until the final event, as shown in streaming-tool-results-agent-loop.md.
  • Streaming and JSON interact poorly on purpose. If you set output_schema and also stream tokens, you display chunks but only parse at the end; that is the correct trade.

Takeaway: Move an ADK agent from Markdown to machine-readable output in deliberate steps — instruct the format, then lock it with output_schema plus output_key so session.state holds a parsed dict rather than prose, use after_model_callback to strip fences and rewrite LlmResponse when the model still misbehaves, and reach for --jsonl or /run when the consumer is a pipeline rather than a person — while remembering that generate_content_config cannot carry a response schema and that partial chunks are display-only.

Sources