{"slug":"solo-sgr","title":"solo-sgr","summary":"Use when \"design schemas\", \"structured output\", \"agent loop\", \"SGR\", \"constrained decoding\", \"tool dispatch\", \"Pydantic schema for LLM\", or need to design a schema-guided reasoning pipeline for an agent or API. Do NOT use for general code review (/review) or planning (/plan).","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-09-07T19:02:22.137268Z","repo":{"url":"https://github.com/fortunto2/solo-factory","stars":18,"forks":3,"license":"MIT","updatedAt":"2026-09-14T16:23:17Z"},"bodyHtml":"<hr>\n<h2>name: solo-sgr\ndescription: Use when \"design schemas\", \"structured output\", \"agent loop\", \"SGR\", \"constrained decoding\", \"tool dispatch\", \"Pydantic schema for LLM\", or need to design a schema-guided reasoning pipeline for an agent or API. Do NOT use for general code review (/review) or planning (/plan).\nlicense: MIT\nmetadata:\nauthor: fortunto2\nversion: \"1.0.0\"\nallowed-tools: Read, Write, Edit, Glob, Grep, Bash\nargument-hint: \"&lt;task description or 'audit' to review existing schemas&gt;\"</h2>\n<h1>/sgr</h1>\n<p>Design and implement Schema-Guided Reasoning (SGR) pipelines. Translate domain expert mental checklists into structured reasoning schemas for LLMs.</p>\n<p><strong>Source:</strong> <a href=\"https://abdullin.com/schema-guided-reasoning/\">Rinat Abdullin — Schema-Guided Reasoning</a></p>\n<h2>Core Principle</h2>\n<p>SGR = guide LLM reasoning through predefined steps via constrained decoding. Instead of free-form text → enforce a schema that defines what steps, in which order, where to focus attention.</p>\n<pre><code>Domain expert mental checklist → Pydantic/Zod schema → Constrained decoding → Deterministic dispatch\n</code></pre>\n<h2>When to Use</h2>\n<ul>\n<li>Designing agent tool dispatch (NextStep pattern)</li>\n<li>Building structured analysis pipelines (compliance, code review, evaluation)</li>\n<li>Replacing prompt chains with single structured call</li>\n<li>Any place where LLM output must be parseable and actionable</li>\n</ul>\n<h2>Steps</h2>\n<ol>\n<li><p><strong>Parse task</strong> from <code>$ARGUMENTS</code>:</p>\n<ul>\n<li>If \"audit\": scan project for existing Pydantic/Zod schemas, evaluate against SGR patterns</li>\n<li>If task description: design SGR pipeline from scratch</li>\n<li>If empty: ask \"What domain/task should the SGR pipeline handle?\"</li>\n</ul>\n</li>\n<li><p><strong>Identify the reasoning cascade</strong> — interview the domain:</p>\n<ul>\n<li>What decisions does a human expert make? In what order?</li>\n<li>What information does each step need from previous steps?</li>\n<li>Where does the expert need to \"look before deciding\"?</li>\n<li>What are the possible actions at the end?</li>\n</ul>\n<p>This is the critical step. SGR quality = how well you translate the expert's mental checklist.</p>\n</li>\n<li><p><strong>Design the schema</strong> following SGR patterns:</p>\n<h3>The NextStep Pattern (agent loop)</h3>\n<pre><code>class NextStep(BaseModel):\n    current_state: str                    # thinking space\n    plan_remaining_steps: list[str]       # 1-5 steps, only first used\n    task_completed: bool                  # routing gate\n    function: Union[Tool1, Tool2, ..., ReportCompletion] = Field(\n        ..., description=\"execute first remaining step\"\n    )\n</code></pre>\n<h3>The Analysis Cascade Pattern (single-shot)</h3>\n<pre><code>class Analysis(BaseModel):\n    preliminary: str                      # initial assessment\n    classification: Literal[\"a\", \"b\", \"c\"]  # force categorization\n    evidence: list[str]                   # cite sources\n    gaps: list[GapItem]                   # structured findings\n    verdict: Literal[\"pass\", \"partial\", \"fail\"]  # final decision\n    reasoning_for_verdict: str            # explain after deciding\n</code></pre>\n<h3>The Tool Dispatch Pattern</h3>\n<pre><code>class SendEmail(BaseModel):\n    tool: Literal[\"send_email\"]           # discriminator\n    recipient: str\n    subject: str\n    body: str\n\nclass SearchDB(BaseModel):\n    tool: Literal[\"search_db\"]\n    query: str\n\n# Union with Literal discriminator = deterministic routing\nAction = Union[SendEmail, SearchDB, ReportDone]\n</code></pre>\n</li>\n<li><p><strong>Apply SGR design rules</strong> (from <code>references/sgr-rules.md</code>):</p>\n<ul>\n<li><strong>Cascade order matters</strong> — put analysis before decision, evidence before verdict</li>\n<li><strong>Constrain enums</strong> — <code>Literal[\"pass\", \"fail\"]</code> not <code>str</code></li>\n<li><strong>Limit lists</strong> — <code>Annotated[list[str], MinLen(1), MaxLen(5)]</code></li>\n<li><strong>Discriminated unions</strong> — <code>tool: Literal[\"name\"]</code> for routing</li>\n<li><strong>Verification after decision</strong> — add <code>reasoning_for_X</code> AFTER the enum field, not before</li>\n<li><strong>One schema per reasoning path</strong> — don't mix analysis and action in one model</li>\n<li><strong>Discount &gt; 50% guard</strong> — <code>Annotated[int, Le(50)]</code> — bake constraints into types</li>\n</ul>\n</li>\n<li><p><strong>Implement the dispatch loop</strong> (if agent):</p>\n<pre><code>for i in range(MAX_STEPS):\n    response = client.beta.chat.completions.parse(\n        model=MODEL,\n        response_format=NextStep,\n        messages=log,\n    )\n    job = response.choices[0].message.parsed\n\n    if isinstance(job.function, ReportCompletion):\n        break  # done\n\n    result = dispatch(job.function)  # deterministic routing\n    log.append(assistant_message(job))\n    log.append(tool_result(result))\n</code></pre>\n</li>\n<li><p><strong>Add to project</strong>:</p>\n<ul>\n<li>Schemas in <code>schemas/</code> or <code>models/</code> directory</li>\n<li>Dispatch in <code>dispatch.py</code> or equivalent</li>\n<li>Tests: validate schema parsing, test each tool independently</li>\n<li>Document the reasoning cascade in a comment or docstring</li>\n</ul>\n</li>\n<li><p><strong>Audit mode</strong> (if <code>$ARGUMENTS</code> = \"audit\"):</p>\n<ul>\n<li>Find all Pydantic BaseModel / Zod z.object in project</li>\n<li>Check: do schemas follow cascade order? Are enums constrained? Are unions discriminated?</li>\n<li>Report: which schemas are SGR-compliant, which need fixes</li>\n</ul>\n</li>\n</ol>\n<h2>Output</h2>\n<pre><code>## SGR Pipeline: {domain}\n\n**Pattern:** {NextStep | Analysis Cascade | Tool Dispatch}\n**Schemas:** {N} models\n**Tools:** {N} (if agent loop)\n\n### Reasoning Cascade\n{step 1} → {step 2} → ... → {decision/action}\n\n### Files\n- schemas/{name}.py — {N} models\n- dispatch.py — tool routing\n- tests/test_{name}.py — validation tests\n</code></pre>\n<h2>Key References</h2>\n<ul>\n<li><code>references/sgr-rules.md</code> — design rules and anti-patterns</li>\n<li><code>references/sgr-demo.py</code> — complete working example (Abdullin's CRM demo, 304 lines Python)</li>\n<li><code>references/sgr-patterns.md</code> — cascade patterns for 6 domains</li>\n<li><code>references/sgr-full-guide.md</code> — full SGR guide with theory, code, tool calling internals</li>\n</ul>\n<h2>Libraries &amp; Implementations</h2>\n<h3>Rust</h3>\n<ul>\n<li><strong>sgr-agent</strong> (crate, v0.6.1) — SGR LLM client + agent framework: structured output, function calling, agent loop, 3 agent variants. Core crate for all Rust SGR agents. Part of <a href=\"https://github.com/fortunto2/rust-code\">rust-code</a></li>\n<li><a href=\"https://github.com/fortunto2/openai-oxide\">openai-oxide</a> — typed Rust client for OpenAI API (SGR at compile time via strong types)</li>\n</ul>\n<p>In Rust, SGR is even stronger: <code>#[serde(tag = \"tool\")]</code> gives discriminated union dispatch at zero runtime cost. Enum variants = tools, serde deserialization = constrained decoding.</p>\n<h3>Python</h3>\n<ul>\n<li><a href=\"https://github.com/vamplabAI/sgr-agent-core\">sgr-agent-core</a> (1K+ stars) — SGR agentic system design framework by neuraldeep community. Reference Python implementation</li>\n<li>Abdullin's demo in <code>references/sgr-demo.py</code> — minimal standalone example (304 lines, CRM agent)</li>\n</ul>\n<h2>Common Issues</h2>\n<h3>Schema too flat</h3>\n<p><strong>Cause:</strong> Tried to put everything in one model.\n<strong>Fix:</strong> Split into analysis model + action model. Cascade, don't flatten.</p>\n<h3>LLM ignores enum constraints</h3>\n<p><strong>Cause:</strong> Model not supporting constrained decoding, or wrong API.\n<strong>Fix:</strong> Use <code>response_format=Schema</code> (OpenAI), <code>tools</code> with schema (Anthropic). Check <code>references/sgr-rules.md</code> for provider-specific notes.</p>\n<h3>Agent loops forever</h3>\n<p><strong>Cause:</strong> No <code>task_completed</code> gate or <code>ReportCompletion</code> tool.\n<strong>Fix:</strong> Always include a completion signal in the Union. Cap loop iterations.</p>\n","files":[{"path":"references/sgr-demo.py","sizeBytes":12183,"isText":true},{"path":"references/sgr-full-guide.md","sizeBytes":72200,"isText":true},{"path":"references/sgr-patterns.md","sizeBytes":3240,"isText":true},{"path":"references/sgr-rules.md","sizeBytes":2850,"isText":true},{"path":"SKILL.md","sizeBytes":7244,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-09-13T07:21:31.606061Z","sha256":"6A373D449E842D315B54777B0EA34B51F77442CF79537425DE47906ED24ADF30","sizeBytes":35632},"review":null,"source":{"repositoryUrl":"https://github.com/fortunto2/solo-factory","path":"skills/sgr","license":"MIT","commit":"a26964729df4c21e4ffb011799b9302987dfd9b2","subtreeSha":"29E151991E4A0D77AA5281DCB79EEAFF3519C2F91FB4355180E7B70041B47E82","lastSyncedAt":"2026-09-25T07:36:50.677664Z"},"reviewedAt":"2026-09-13T07:21:32.958767Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/fortunto2/solo-factory/tree/main/skills/sgr"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install fortunto2-solo-factory@llmmart"},{"target":"git","command":"git clone https://github.com/fortunto2/solo-factory.git"}]}