dspy-output-refinement-constraints

dspy-output-refinement-constraints is a skill for Claude Code from OmidZamani/dspy-skills. It costs 35 tokens per session (1,742 once invoked), scanned A, original, MIT.

A guide to improving DSPy outputs through repeated attempts and validation. It covers Refine, BestOfN, output constraints, and reward functions, where a reward function checks how well a result meets requirements.

In plain words
What is it for?
Use it to validate and refine DSPy predictions, enforce structure or word limits, run several candidate attempts, and accept results that pass a custom threshold.
Why use it?
It helps require formats such as JSON, enforce length or content rules, and select or refine results until they meet a minimum score. It also replaces older Assert and Suggest patterns.

Skill for Claude Code

Written for Claude Code: allowed-tools in frontmatter.

Part of the dspy-skills plugin — 24 skills shipped together

Good fit Use it to validate and refine DSPy predictions, enforce structure or word limits, run several candidate attempts, and accept results that pass a custom threshold.

Compare 6 skills from other repositories ↓
Install with agentmods
npx agentmods add skills/omidzamani/dspy-skills/dspy-output-refinement-constraints
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Any agent
npx skills add OmidZamani/dspy-skills --skill dspy-output-refinement-constraints
Clone the repo
git clone --depth 1 https://github.com/OmidZamani/dspy-skills

Made for: Claude Code.

Or install dspy-skills, the plugin that ships this one along with the rest of its 24 skills.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for dspy-output-refinement-constraints

README.md
[![agentmods](https://agentmods.dev/badge/skills/omidzamani/dspy-skills/dspy-output-refinement-constraints/github.svg)](https://agentmods.dev/skills/omidzamani/dspy-skills/dspy-output-refinement-constraints)
Your own site
<a href="https://agentmods.dev/skills/omidzamani/dspy-skills/dspy-output-refinement-constraints"><img src="https://agentmods.dev/badge/skills/omidzamani/dspy-skills/dspy-output-refinement-constraints/github.svg" alt="Measured on agentmods" height="20"></a>

Or the 80×15 button, for a site that already has a row of RSS and ATOM ones. Only the verdict fits; the numbers stay here.

agentmods 80×15 button for dspy-output-refinement-constraints

Your own site · 80×15
<a href="https://agentmods.dev/skills/omidzamani/dspy-skills/dspy-output-refinement-constraints"><img src="https://agentmods.dev/badge/skills/omidzamani/dspy-skills/dspy-output-refinement-constraints.svg" alt="Reviewed on agentmods" width="80" height="20"></a>
Per session 35 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 1,742 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe. Third-party audits
  • NVIDIA SkillSpector pass 7 Sept 2026
How audits are shown
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00035 $0.01742
Opus 5 $0.00017 $0.00871
Sonnet 5 $0.00007 $0.00348
Haiku 4.5 $0.00003 $0.00174

Measured 12d ago against content hash 4550331692d3, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-11, from the pricing page.

Security

Grade A, and why

dspy-output-refinement-constraints scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 12d ago.

The scan reads SKILL.md. This mod also ships 1 executable file (example.py), listed below but not scanned — reading those needs a real analyzer, not pattern matching.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/dspy-output-refinement-constraints/SKILL.md · 242 lines

How it starts

The opening of the file, as written. The whole thing — 242 lines — stays where its author put it; the contents beside it link to each section on GitHub.

DSPy Output Refinement & Constraints

Goal

Improve output quality using iterative refinement (dspy.Refine) and best-of-N selection (dspy.BestOfN) with custom constraint validation.

When to Use

  • Outputs need format validation (JSON, specific structure)
  • Length constraints (max tokens, word count)
  • Content requirements (must include X, avoid Y)
  • Quality improvement through multiple attempts
  • Replacing deprecated Assert/Suggest patterns

Inputs

Input Type Description
module dspy.Module Module to refine
reward_fn callable Constraint validation function
N int Number of attempts
threshold float Minimum reward to accept

Outputs

Output Type Description
refined_output dspy.Prediction Validated, refined result

Workflow

Phase 1: dspy.Refine for Iterative Improvement

Refine iteratively improves outputs across multiple attempts:

import dspy

dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))

# Base module
summarizer = dspy.ChainOfThought("document -> summary: str")

# Reward function: checks constraints
def summary_reward(args, pred):
    summary = pred.summary
    word_count = len(summary.split())

    if word_count > 100 or len(summary) < 50:
        return 0.0
    if "important" not in summary.lower():
        return 0.5
    return 1.0

# Refine module
refined_summarizer = dspy.Refine(
    module=summarizer,
    reward_fn=summary_reward,
    N=3,
    threshold=1.0
)

# Use it
result = refined_summarizer(document="Long document text here...")
print(result.summary)

Phase 2: dspy.BestOfN for Selection

Generate N outputs and pick the best:

Read the full file on GitHub · 242 lines

Files

What ships with it

1 file beside SKILL.md in the same directory: the scripts, references and assets a skill reads on demand. Not counted in the per-session cost; read them before you install if any of them is executable.

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 12d ago First seen · 242 lines · 35 tokens per session scan A 4550331692d3

Subscribe to this mod's changes

dspy-output-refinement-constraints is a skill published in the GitHub repository OmidZamani/dspy-skills (123 stars, last pushed 2mo ago), licensed MIT. It adds 35 tokens to every session and 1,742 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

reasoning

AI reasoning authority — prompt engineering, chain-of-thought, self-consistency, evaluation frameworks, LLM judging, structured output, and prompt versioning patterns for production AI systems.

LuuOW/meridian-mcp · 38 tokens

ai-engineering-toolkit

6 production-ready AI engineering workflows: prompt evaluation (8-dimension scoring), context budget planning, RAG pipeline design, agent security audit (65-point checklist), eval harness building, and product sense coaching.

sickn33/agentic-awesome-skills · 47 tokens

prompt-optimization

Improve a prompt on the evaluations workbench through a measured loop. Score the baseline first, then duplicate the target column, form a hypothesis from failing rows, edit the copy's prompt draft, run, compare pass rate and cost, and repeat until the numbers hold. Use when the user asks to optimize or improve a…

langwatch/langwatch · 105 tokens

prompts

Version and manage your agent's prompts with LangWatch Prompts CLI. Use for both onboarding (set up prompt versioning for an entire codebase) and targeted operations (version a specific prompt, create a new prompt version). Supports Python and TypeScript.

langwatch/langwatch · 54 tokens

prompt-master

Generates optimized prompts for AI tools. Activates only when the user explicitly asks to write, fix, improve, or adapt a prompt for a specific AI tool (LLM, Cursor, Midjourney, image AI, video AI, coding agents, etc.). Does not activate for general conversation, coding tasks, document writing, or other…

nidhinjs/prompt-master · 78 tokens

llm-engineering-expert

Build reliable applications on large language models: prompt design, structured output, evaluation, guardrails, and cost and latency control. Use when the user mentions LLMs, prompts, prompt engineering, few-shot examples, structured or JSON output, function calling, hallucination, model evaluation, token costs…

personamanagmentlayer/pcl · 92 tokens