Skip to content

Instantly share code, notes, and snippets.

@ochafik
Created June 10, 2025 18:50
Show Gist options
  • Select an option

  • Save ochafik/fec425c46c55eeb286b9fe561efc8bba to your computer and use it in GitHub Desktop.

Select an option

Save ochafik/fec425c46c55eeb286b9fe561efc8bba to your computer and use it in GitHub Desktop.
JSON schema examples

JSON schema examples extracted from llama.cpp

Simple recursive pydantic schema

Taken from ggml-org/llama.cpp#5978

pip install pydantic

echo "
from pydantic import BaseModel
from typing import Optional, Union, Tuple
import json

class QAPair(BaseModel):
  question: str
  concise_answer: str
  justification: str

class PyramidalSummary(BaseModel):
  title: str
  summary: str
  question_answers: list[QAPair]
  sub_sections: list['PyramidalSummary']

if __name__ == '__main__':
  print(json.dumps(PyramidalSummary.model_json_schema()))

" | python - 
{
  "$defs": {
    "PyramidalSummary": {
      "properties": {
        "title": {
          "title": "Title",
          "type": "string"
        },
        "summary": {
          "title": "Summary",
          "type": "string"
        },
        "question_answers": {
          "items": {
            "$ref": "#/$defs/QAPair"
          },
          "title": "Question Answers",
          "type": "array"
        },
        "sub_sections": {
          "items": {
            "$ref": "#/$defs/PyramidalSummary"
          },
          "title": "Sub Sections",
          "type": "array"
        }
      },
      "required": [
        "title",
        "summary",
        "question_answers",
        "sub_sections"
      ],
      "title": "PyramidalSummary",
      "type": "object"
    },
    "QAPair": {
      "properties": {
        "question": {
          "title": "Question",
          "type": "string"
        },
        "concise_answer": {
          "title": "Concise Answer",
          "type": "string"
        },
        "justification": {
          "title": "Justification",
          "type": "string"
        }
      },
      "required": [
        "question",
        "concise_answer",
        "justification"
      ],
      "title": "QAPair",
      "type": "object"
    }
  },
  "allOf": [
    {
      "$ref": "#/$defs/PyramidalSummary"
    }
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment