Skip to content

[WIP] Implement grammar-constrained generation for structured output - #245

Merged
makr-code merged 10 commits into
developfrom
copilot/implement-grammar-constraints
Jan 5, 2026
Merged

makr-code merged 10 commits into
developfrom
copilot/implement-grammar-constraints

Conversation

Copilot AI commented Jan 5, 2026

Copy link
Copy Markdown
Contributor

Thanks for assigning this issue to me. I'm starting to work on it and will keep this PR's description up to date as I form a plan and make progress.

Original prompt

This section details on the original issue you should resolve

<issue_title>05-implement-grammar-constraints.md</issue_title>
<issue_description>---
name: "🟢 Implement Grammar-Constrained Generation (Phase 3.2)"
about: Guarantee valid JSON/XML/structured output using EBNF grammars
title: "[P2] Implement Grammar-Constrained Generation - Guaranteed Structured Output"
labels: ["priority: medium", "type: feature", "component: llm", "phase-3"]
assignees: []

Priority

🟢 MEDIUM - P2 (Phase 3, high value feature)

Overview

Implement grammar-constrained generation to guarantee valid structured output (JSON, XML, custom formats) using EBNF grammars, eliminating parsing errors and retry logic.

Impact:

  • 95-99% valid outputs (vs 60-70% without constraints)
  • No retry logic needed
  • Faster generation (only valid tokens sampled)
  • Better UX for API integration

Depends On

Documentation

📄 Complete implementation guide available:
docs/en/llm/GRAMMAR_CONSTRAINED_GENERATION.md (12.8KB)

Feature Requirements

Built-in Grammars

Provide ready-to-use grammars for common formats:

  1. JSON (strict and relaxed)
  2. XML (with/without self-closing tags)
  3. CSV (quoted and unquoted)
  4. Agent Format (ReAct, thought/action/observation)

Custom Grammar Support

Allow users to define custom EBNF grammars:

root ::= object
object ::= "{" pair ("," pair)* "}"
pair ::= string ":" value
string ::= "\"" [^"]* "\""
value ::= string | number | object | array

Implementation Tasks

1. Grammar Infrastructure (include/llm/grammar.h)

  • Create Grammar class

    class Grammar {
    public:
        Grammar(const std::string& ebnf_text, const std::string& start_symbol);
        ~Grammar();
        
        bool isValid() const;
        std::string getError() const;
        
        // Internal: llama_grammar handle
        llama_grammar* getHandle() const;
        
    private:
        llama_grammar* grammar_ = nullptr;
        std::string error_;
    };
  • Add GrammarCache for compiled grammars

    class GrammarCache {
    public:
        std::shared_ptr<Grammar> get(const std::string& name);
        void put(const std::string& name, std::shared_ptr<Grammar> grammar);
        void clear();
        
    private:
        std::unordered_map<std::string, std::shared_ptr<Grammar>> cache_;
        std::mutex mutex_;
    };

2. Built-in Grammars (src/llm/grammars/)

  • Create grammar files:

    • json_strict.ebnf - Strict JSON
    • json_relaxed.ebnf - JSON with trailing commas, etc.
    • xml.ebnf - XML format
    • csv.ebnf - CSV format
    • react_agent.ebnf - ReAct agent format
  • Embed grammars in binary (CMake resource compilation)

3. LlamaWrapper Integration (src/llm/llama_wrapper.{h,cpp})

  • Add generateConstrained() method

    std::string generateConstrained(
        const std::string& prompt,
        std::shared_ptr<Grammar> grammar,
        const GenerationParams& params
    );
  • Implement token sampling with grammar

    // In generation loop
    llama_sample_grammar(ctx_, &candidates_p, grammar->getHandle());
    llama_token token = llama_sample_token(ctx_, &candidates_p);
    llama_grammar_accept_token(ctx_, grammar->getHandle(), token);
  • Add configuration support

    struct GrammarConfig {
        bool enabled = false;
        std::string default_grammar = "json";
        std::string custom_grammars_path = "/grammars/";
        bool cache_grammars = true;
        int max_cached_grammars = 100;
    };

4. Configuration Files

  • Update config/llm_config.example.yaml

    optimizations:
      grammar_constraints:
        enabled: true
        default_grammar: "json"
        custom_grammars_path: "/grammars/"
        cache_grammars: true
  • Update config/llm_config.production.yaml

5. HTTP API Integration

  • Add grammar parameter to generate endpoint

    POST /api/v1/llm/generate
    {
        "prompt": "Generate user profile",
        "grammar": "json",  // Built-in grammar
        "max_tokens": 256
    }
  • Support custom grammar upload

    POST /api/v1/llm/generate
    {
        "prompt": "Plan next action",
        "grammar_file": "/grammars/custom.ebnf",
        "max_tokens": 512
    }

6. CLI Interface

  • Add --grammar flag

    themisdb llm generate \
      --prompt "Generate JSON user data" \
      --grammar json \
      --model mistral-7b
  • Add --grammar-file flag

    themisdb llm generate \
      --prompt "Plan action" \
      --grammar-file /grammars/agent.ebnf \
      --model mistral-7b

7. Testing

  • Unit tests for Grammar class
  • Test all built-in grammars
  • Test custom grammar loadi...

💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI requested a review from makr-code January 5, 2026 16:50
@makr-code
makr-code marked this pull request as ready for review January 5, 2026 16:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

05-implement-grammar-constraints.md

2 participants