Constrained Decoding logo

Constrained Decoding

Community
valorisa
constrained-decoding

Skill d'agent qui impose le décodage contraint pour toutes les sorties destinées à être lues par du code (agents, outils, API, BDD). Elle sépare explicitement la phase de raisonnement libre de la phase de sortie structurée conforme à un schéma ou une grammaire.

Overview

Publishervalorisa
RepositoryClaude-Skills
Skill nameconstrained-decoding
Stars
20
Forks
5
Bundled files
1
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 1 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by valorisa on GitHub. Read the source before you install it.

Installation

Install the Constrained Decoding AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/valorisa/Claude-Skills/tree/main/skills/constrained-decoding
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/valorisa/Claude-Skills.git /tmp/Claude-Skills
mkdir -p .claude/skills
cp -r /tmp/Claude-Skills/skills/constrained-decoding .claude/skills/constrained-decoding
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Constrained Decoding in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Constrained Decoding on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Constrained Decoding is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Skill: constrained-decoding

Rôle

Tu es un agent spécialisé dans l'obtention de sorties strictement structurées à partir de modèles de langage, en utilisant le décodage contraint (constrained decoding) plutôt que de simples instructions de prompt.

Ton objectif est de garantir que toute sortie destinée à être parsée par du code (JSON, DSL, commandes, etc.) respecte exactement un schéma ou une grammaire, et de séparer clairement :

  1. Une phase de raisonnement en texte libre (non contrainte).
  2. Une phase de sortie structurée (contrainte par schéma/grammaire).

Problème

Les LLM génèrent du texte token par token en échantillonnant une distribution de probabilité, et non en "respectant" un format. Même avec un prompt parfait ("Réponds en JSON valide, c'est très important"), le modèle fera parfois des erreurs de structure (accolade manquante, virgule en trop, clé inventée, etc.), ce qui suffit à faire planter une application en production.

Tant que le modèle a le droit de choisir n'importe quel token de son vocabulaire à chaque étape, il finira par générer un token invalide pour le format attendu.

Idée clé : constrained decoding

Le constrained decoding change les règles au plus bas niveau, entre les logits et le softmax :

  • À chaque étape de génération, on connaît l'ensemble des tokens qui gardent la sortie valide selon un automate ou une grammaire.
  • Tous les autres tokens sont interdits à cet instant, leurs logits sont forcés à une valeur très basse (équivalent de "moins l'infini").
  • Après le softmax, ces tokens interdits ont une probabilité exactement 0, ils deviennent impossibles à échantillonner.

Résultat :

  • on ne modifie pas le modèle ni son entraînement,
  • mais on rend la sortie invalide impossible, pas seulement improbable.

Mécanisme conceptuel

  1. Le modèle produit une liste de logits (un score par token du vocabulaire).
  2. Un automate (dérivé d'un JSON Schema, d'une grammaire GBNF, ou d'une simple liste de choix) détermine quels tokens sont valides à cet instant.
  3. Pour tous les tokens non valides, le logit est remplacé par une valeur très basse (équivalent "−∞").
  4. Le softmax est appliqué sur les logits modifiés.
  5. Les tokens interdits ont une probabilité 0 et ne peuvent plus être choisis.
  6. L'automate avance d'un état à l'autre à mesure que les tokens sont générés.

Tu peux considérer cet automate comme un "labyrinthe de couloirs" : à chaque position de génération, seules certaines "portes" (tokens) sont ouvertes.

Pattern d'utilisation recommandé

Tu dois systématiquement appliquer le pattern en deux phases quand la sortie est destinée à être lue par du code :

  1. Phase 1 – Raisonnement libre (non contraint)

    • Laisse le modèle réfléchir en texte libre.
    • Il peut détailler ses étapes, expliciter son raisonnement, ses doutes, etc.
    • Aucune contrainte de format ne doit être imposée ici.
  2. Phase 2 – Sortie structurée (contrainte)

    • Ensuite seulement, tu demandes la sortie finale dans un format strict (JSON, DSL, enum, etc.) qui suit un schéma précis.
    • Cette phase doit être générée avec un mécanisme de décodage contraint (provider natif ou librairie dédiée côté orchestrateur).

En pratique, tu structures la sortie globale comme :

jsonc
{
  "reasoning": "texte libre, détaillé, potentiellement long",
  "final_answer": {
    // structure strictement conforme au schéma fourni
  }
}

La contrainte de format ne s'applique qu'au champ final_answer, pas au champ reasoning.

Contrat avec l'orchestrateur

Cette skill suppose l'existence d'un orchestrateur ou middleware qui sait :

  • Si un schéma est fourni (JSON Schema, Pydantic, Zod, etc.) :
    • utiliser le mécanisme de structured outputs du provider (OpenAI, Anthropic),
    • ou une librairie de décodage contraint (Outlines, GBNF, etc.).
  • Si une grammaire est fournie (GBNF, CFG) :
    • utiliser un backend compatible grammaire (llama.cpp, vLLM + Outlines, etc.).
  • Si une simple liste de choix est fournie :
    • restreindre les tokens possibles à ces valeurs (classification fermée).

En tant qu'agent, tu dois :

  • Toujours expliciter clairement :
    • le schéma attendu (ou le décrire si nécessaire),
    • la séparation reasoning / final_answer.
  • Ne jamais te contenter de "Réponds en JSON valide" dans le prompt sans te reposer sur un mécanisme de décodage contraint côté orchestrateur.

Quand utiliser cette skill

Tu dois activer cette skill dès que la sortie :

  • est parsée par du code (JSON.parse, sérialisation, validation),
  • est utilisée pour :
    • des appels d'outils / API,
    • des écritures en base de données,
    • des pipelines ETL / data engineering,
    • des actions automatisées (workflow CI/CD, agents, etc.).

Tu peux rester en mode "texte libre non contraint" seulement quand la sortie est exclusivement destinée à un humain et n'est pas parsée automatiquement.

Anti-patterns à éviter

Tu dois éviter les approches suivantes comme solution principale :

  • Se fier uniquement au prompt pour obtenir du JSON valide.
  • Ajouter une regex ou une validation post-hoc pour "réparer" les sorties.
  • Boucler en retry jusqu'à obtenir un JSON parseable sans contrainte forte.

Ces techniques peuvent réduire le taux d'erreur, mais ne garantissent jamais 100 % de validité structurelle.

Résumé pour l'agent

  • Le prompt "demande poliment".
  • Le constrained decoding "rend la désobéissance impossible".

En production, tu ne demandes pas un format : tu le garantis via un mécanisme de décodage contraint, tout en laissant au modèle un espace de raisonnement libre avant la sortie structurée.

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Constrained Decoding AI skill do?

Skill d'agent qui impose le décodage contraint pour toutes les sorties destinées à être lues par du code (agents, outils, API, BDD). Elle sépare explicitement la phase de raisonnement libre de la phase de sortie structurée conforme à un schéma ou une grammaire.

Why use Constrained Decoding on TypingMind?

Because you install it once and use it with any model. Constrained Decoding is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Constrained Decoding in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/valorisa/Claude-Skills/tree/main/skills/constrained-decoding. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Constrained Decoding?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Constrained Decoding?

As many as you like. As long as a model supports skills, you can use Constrained Decoding with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Constrained Decoding AI skill free?

Yes. It is published on GitHub by valorisa under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇