Your prompts are scattered, hardcoded, and untested. This framework makes them a data asset — then optimizes them for the device sitting in your pocket.


If you've built anything serious with LLMs, you know the drill. Prompts start as quick experiments in a notebook. Then they migrate — copy-pasted into source files, wedged into f-strings, version-controlled by comment blocks, and "tested" by running them once and squinting at the output. Six months later, nobody remembers which version of the system prompt is actually in production, whether the few-shot examples still make sense for the new model, or why the prompt that worked on GPT-4o produces garbage on the smaller model running locally.

prompt-better (github.com/pkcpkc/prompt-better) is a new open-source framework from Paul Hackenberger that tackles this problem at the root. Instead of treating prompts as free-text strings embedded in Python code, it defines them as structured JSON specifications — a Single Source of Truth — and then builds an entire optimization pipeline on top of that foundation.

What makes it interesting isn't just the JSON schema. It's the way the framework connects three worlds that usually live in isolation:

  1. Declarative prompt specification (JSON → Pydantic → DSPy Signatures)
  2. Automated prompt optimization (MIPROv2 compiler with student-teacher distillation)
  3. Apple on-device inference (Vapor HTTP bridges exposing LanguageModelSession as OpenAI-compatible endpoints)

Let's walk through what that means and why it matters.


The Problem: Prompts as Second-Class Citizens

In most LLM applications, prompts are treated like configuration files that someone forgot to externalize. They live in constants, docstrings, or environment variables. They're versioned informally, tested manually, and optimized by gut feel.

This creates three specific failure modes:

Fragmentation. The same prompt logic gets duplicated across services. One team tunes the classification prompt in the API layer; another team rewrites it in the data pipeline. Neither knows the other exists.

No type safety. A prompt that's supposed to return a JSON object with specific fields returns… whatever the model feels like returning. You can add output parsers, but you're always playing catch-up. The schema is implicit, not enforced.

No optimization loop. You write a prompt, you run it, you eyeball the results, you tweak a word here or there. There's no systematic way to ask: "Given this model, this hardware, and these constraints, what's the best possible version of this prompt?"

prompt-better addresses all three.


The Architecture: JSON as Prompt SSOT

At the core of prompt-better is the prompt.json file. Here's what a minimal one looks like for a topic classifier:

{
  "name": "TopicClassifierPrompt",
  "description": "Classify text into one of several topic categories.",
  "inputs": [
    {
      "name": "text",
      "type": "string",
      "desc": "The text to classify."
    }
  ],
  "outputs": [
    {
      "name": "topic",
      "type": "string",
      "desc": "The classified topic category.",
      "choices": ["technology", "sports", "politics", "entertainment", "science"]
    }
  ],
  "instructions": "Classify the given text into one of the provided topic categories.",
  "few_shots": []
}

Every prompt is a self-contained directory containing:

  • prompt.json — the specification (inputs, outputs, instructions, constraints)
  • dataset/ — training and evaluation cases
  • golden-truth/ — reference outputs for evaluation

This is the Single Source of Truth. The JSON defines the schema, the constraints, the instructions, and the evaluation criteria — all in one place.

At runtime, prompt-better parses this JSON and dynamically generates:

  1. Pydantic models — type-safe Python classes that validate model outputs against the declared schema. No more hoping the model returns the right fields; the framework enforces it.
  1. DSPy Signatures — typed mappings of the form Inputs -> Outputs that plug directly into DSPy's programming model. Instead of writing a dspy.Signature by hand, you declare your intent in JSON and the framework generates the Signature for you.

This is the key insight: the JSON isn't just documentation, it's executable. It's the contract that drives validation, optimization, and even Swift code generation (more on that below).


The Optimization Engine: Coached Student-Teacher

Here's where it gets genuinely interesting. prompt-better doesn't just store prompts — it optimizes them, using a two-model pipeline inspired by knowledge distillation:

Teacher Model (Cloud)

The teacher is a high-capacity cloud model — typically GPT-4o — that does three things:

  • Drafts instruction variations. Given your base prompt, the teacher proposes alternative phrasings, restructured instructions, and different few-shot selections.
  • Synthesizes demonstrations. It generates candidate few-shot examples tailored to the task.
  • Grades outputs. Against custom rubrics, the teacher evaluates how well the student's outputs match expectations.

Student Model (Local / On-Device)

The student is your target deployment model — the one that will actually run in production. This could be a local 3B–8B parameter model, or, critically, Apple's on-device foundation model running via LanguageModelSession.

The student executes each candidate prompt during the compilation loop. The teacher evaluates the results. Over multiple iterations, the system converges on the prompt variant that maximizes the student's performance.

The Compiler: MIPROv2

Under the hood, prompt-better uses DSPy's MIPROv2 (Multi-prompt Instruction Proposal and Few-shot Optimization) compiler. MIPROv2 is a Bayesian optimization algorithm that:

  1. Proposes instruction rewrites via the teacher
  2. Executes each candidate on the student
  3. Evaluates structural correctness, token-level similarity to golden truth, and (if the teacher is available) semantic quality
  4. Selects the winning combination of instructions and few-shot examples

The evaluation scoring is transparent and customizable:

  • Structural Score (55% weight): Do the output fields exist, have the right types, and respect constraints (like choices or mincount/maxcount for arrays)?
  • Similarity Score (45% weight): Token-level F1 overlap between generated values and golden-truth references.
  • Teacher Score (optional): The cloud model grades semantic quality on a 0.0–1.0 scale.

If the teacher is online, the aggregate score averages the base scores with the teacher score. If the teacher is offline or unconfigured, evaluation proceeds with just structural + similarity. This graceful degradation means you can iterate on evaluation even when you don't want to burn API credits.

Running the optimizer is a single command:

python3 -m prompt_better.cli optimize \
  --prompts-dir example/prompts \
  --prompt TopicClassifierPrompt \
  --no-requires-permission-to-run

The output includes:

  • optimized-prompt.json — the winning prompt specification with optimized instructions
  • optimize-report.json — metrics, comparison tables, validation summaries
  • dspy.json — serialized DSPy compile state for reproducibility

You can also run evaluation-only mode (no instruction rewriting) to baseline your current prompt:

python3 -m prompt_better.cli evaluate \
  --prompts-dir example/prompts \
  --prompt TopicClassifierPrompt

Custom Evaluators

The framework is extensible. If the default scoring doesn't match your domain, you can subclass BaseEvaluator:

from prompt_better.dspy_manager import BaseEvaluator

class CustomEvaluator(BaseEvaluator):
    def structural_score(self, spec, candidate) -> float:
        # Your domain-specific structural checks
        return 1.0

    def similarity_score(self, spec, reference, candidate) -> float:
        # Custom similarity metric
        return 0.8

Plug it in via CLI flag (--evaluator path/to/script.py:CustomEvaluator), environment variable, or the config file. The hierarchy is CLI > env > config, consistent with the rest of the framework.


The Apple Bridge: On-Device Models as First-Class Citizens

This is the part that stopped me in my tracks.

Apple's on-device foundation models — available via LanguageModelSession in iOS 26+ and macOS 26+ — are a legitimate deployment target for prompt-driven applications. They run locally, preserve privacy, and cost nothing per inference. But they're not OpenAI-compatible. You can't just point your prompt optimization pipeline at an Apple device and say "optimize for this model."

prompt-better fixes this with Vapor HTTP bridges — lightweight Swift servers that wrap Apple's LanguageModelSession API and expose it as a standard /v1/chat/completions endpoint.

The macOS Bridge

The macOS bridge is a Vapor 4 server (requires Swift Tools 6.0, targeting macOS 26.0+) that:

  1. Receives OpenAI-formatted ChatCompletionRequest objects
  2. Delegates them to Apple's local LanguageModelSession via a LocalAIBridge singleton (which runs on @MainActor for thread safety with Apple's concurrency model)
  3. Returns standard ChatCompletionResponse objects
// routes.swift — the entire OpenAI-compatibility layer
app.post("v1", "chat", "completions") { req async throws in
    let completionRequest = try req.content.decode(OpenAI.ChatCompletionRequest.self)
    let responseText = try await LocalAIBridge.shared.generate(request: completionRequest)
    return OpenAI.ChatCompletionResponse(
        id: "chatcmpl-\(UUID().uuidString)",
        created: Int(Date().timeIntervalSince1970),
        model: completionRequest.model,
        choices: [.init(index: 0, message: .init(content: responseText), finishReason: "stop")],
        usage: .init(promptTokens: 0, completionTokens: 0, totalTokens: 0)
    )
}

Start it with:

cd AIBridges/macOS
swift build && swift run App serve --hostname 127.0.0.1 --port 8080

Now your prompt optimization pipeline can target http://127.0.0.1:8080/v1 with model: "apple-intelligence" and the DSPy compiler will run its optimization loop against the actual on-device model. Not a simulation. Not a proxy. The real Apple Silicon runtime.

The iOS Bridge

There's also an iOS variant that runs directly on physical devices or simulators. Same principle: Vapor server wrapping LanguageModelSession, exposing OpenAI-compatible endpoints. This means you can optimize prompts on the actual iPhone hardware where they'll deploy, accounting for the specific quantization, memory limits, and behavioral quirks of that device.

Why This Matters

Consider what this enables:

  • Prompt optimization that's hardware-aware. A prompt optimized for GPT-4o won't necessarily work on a 3B local model. prompt-better lets you optimize for the target hardware — the actual Apple Neural Engine, the actual memory constraints, the actual model version that your users will run.
  • Privacy-preserving development. You never send user data to the cloud during optimization. The teacher generates instruction candidates; the student runs locally. The only cloud call is the teacher's instruction proposal, not the user data.
  • Zero-cost inference at scale. Once optimized, the on-device model runs for free. No per-token pricing. No rate limits. No network latency.

The CoT vs. Predict Consideration

There's an important subtlety for Apple on-device deployment. By default, DSPy uses ChainOfThought, which wraps the output with intermediate reasoning prefixes like Reasoning: and Output:. Apple's LanguageModelSession uses schema-guided structured output (via @GenerableWithPrompt), which expects clean JSON — not text prefixes.

prompt-better handles this two ways:

Option 1: Use --optimizer predict. This compiles with dspy.Predict instead of dspy.ChainOfThought, avoiding the conflicting text prefixes entirely. Simpler, faster, and recommended when you don't need step-by-step reasoning.

Option 2: Make reasoning explicit in the schema. If the model needs chain-of-thought to be accurate, declare it as an output field:

{
  "outputs": [
    { "name": "reasoning", "type": "string", "desc": "Step-by-step explanation." },
    { "name": "topic", "type": "string", "desc": "The classified topic." }
  ]
}

This aligns the DSPy reasoning step with the Swift schema, so LanguageModelSession can parse both fields naturally. When compiled to Swift, it generates:

@Generable
struct TopicClassifierPrompt: GenerableWithPrompt {
    @Guide(description: "Step-by-step explanation.")
    var reasoning: String

    @Guide(description: "The classified topic.")
    var topic: String
}

This is thoughtful design. The framework doesn't force you into a false choice between "reasoning or structured output" — it gives you both paths and explains when each is appropriate.


Configuration: Sensible Hierarchy

The configuration system follows a clean precedence chain: CLI arguments > Environment variables > Configuration file.

The prompt-better.json config file lives next to your prompts directory:

{
  "student": {
    "base_url": "http://127.0.0.1:8080/v1",
    "model": "apple-intelligence",
    "temperature": 0.2
  },
  "teacher": {
    "base_url": "https://api.openai.com/v1",
    "model": "gpt-4o",
    "temperature": 0.2,
    "eval_temperature": 0.0
  },
  "auto_mode": "light",
  "num_threads": 1
}

API keys are deliberately excluded from the config file (validation error if you try). You provide them via environment variables (PROMPTBETTERTEACHERAPIKEY) or CLI flags. This is a small but meaningful security decision — no accidental credential commits.

The auto_mode setting controls how aggressively the optimizer searches the instruction space. "light" is a reasonable default for iteration speed.


What the Evaluation Flow Actually Looks Like

Let's trace a concrete evaluation run:

1. Scan --prompts-dir for prompt.json files
2. Load dataset/ and golden-truth/ test cases
3. For each test case:
   a. Compile prompt instructions + case inputs
   b. POST to Student Model (e.g., Apple bridge at localhost:8080)
   c. Parse output against JSON schema
   d. Calculate Structural Score (55%): field types, array counts, choice constraints
   e. Calculate Similarity Score (45%): token F1 vs golden truth
   f. If Teacher is online:
      - Send structured grading request to Teacher
      - Teacher returns numeric score (0.0–1.0) + justification
      - Aggregate = average of (base scores + teacher score)
   g. If Teacher is offline:
      - Aggregate = base scores only
   h. Save EvaluationResult
4. Generate JSON report + print summary statistics

The optimization flow wraps this evaluation inside the MIPROv2 compiler loop, which proposes instruction variants, runs them through the student, evaluates each candidate, and converges on the best performer.


Why This Framework Matters

There are plenty of prompt engineering tools. There are plenty of on-device inference engines. There are plenty of evaluation frameworks. What prompt-better does that's different is connect the full loop:

  1. Declare your prompt as a typed, versioned JSON asset (not a string in a Python file)
  2. Validate outputs against the declared schema automatically (Pydantic, not hope)
  3. Optimize the prompt for your actual deployment target (MIPROv2 + student-teacher)
  4. Evaluate with structural, similarity, and semantic scoring (transparent, extensible)
  5. Deploy to Apple on-device models with a compatible bridge (OpenAI API → LanguageModelSession)

The JSON-as-SSOT pattern is the foundation that makes everything else work. Because the prompt is a structured specification — not a string template — you can:

  • Auto-generate DSPy Signatures from it
  • Auto-generate Swift @Generable structs from it
  • Run typed evaluation against it
  • Version-control it like any other data asset
  • Share it across teams and services without duplication

And because the Apple bridges make on-device models look like OpenAI endpoints, the same optimization pipeline that targets GPT-4o can seamlessly target Apple Intelligence. Same CLI, same config format, same evaluation metrics — just change the student.base_url.


Getting Started

# Clone and install
git clone https://github.com/pkcpkc/prompt-better.git
cd prompt-better
mise trust && mise install
mise exec -- uv pip install -e .

# Start the Apple Silicon bridge (macOS 26+)
cd AIBridges/macOS
swift build && swift run App serve --hostname 127.0.0.1 --port 8080

# Configure (example/prompt-better.json)
# Set your OpenAI API key:
export PROMPT_BETTER_TEACHER_API_KEY="sk-proj-..."

# Run optimization
python3 -m prompt_better.cli optimize \
  --prompts-dir example/prompts \
  --prompt TopicClassifierPrompt \
  --no-requires-permission-to-run

The framework is on PyPI (pip install prompt-better, currently at v0.1.2), MIT-licensed, and the example directory includes a complete TopicClassifier walkthrough with dataset, golden truth, and automated scripts.


Limitations and Early-Stage Considerations

prompt-better is young (created June 2026, still at v0.1.x). A few things to be aware of:

  • Apple Silicon requirement. The Vapor bridges require macOS 26+ or iOS 26+. This means Apple's latest OS releases. If you're not on that version, the bridges won't compile.
  • Token counting is stubbed. The bridge response currently returns 0 for all token usage fields. Apple's LanguageModelSession doesn't expose token counts directly, so this is a known gap.
  • Single-model responses only. The OpenAI compatibility layer returns a single choice, not the n-generation sampling that some DSPy optimizers expect. This works for the current MIPROv2 flow but may limit some advanced optimization strategies.
  • No streaming. The bridge is request-response only. For production use cases that need streaming, you'd need to extend the Vapor routes.
  • The community is small. 0 stars, 0 forks at time of writing. This is early infrastructure from a single developer. The design is sound, but the ecosystem around it is nascent.

None of these are dealbreakers. They're the normal constraints of a v0.1 framework that's solving a real problem with clean architecture. The important thing is that the core loop — JSON → Pydantic → DSPy → Apple Silicon — works end-to-end.


The Bigger Picture

prompt-better is part of a broader shift in how we think about LLM integration. The first generation of LLM apps treated prompts as strings — fragile, untyped, untested strings. The second generation added output parsers and validation layers, but the prompt itself was still a string.

The emerging third generation treats prompts as data assets with schemas, types, and optimization pipelines. prompt-better is an early but well-structured implementation of this idea:

  • The prompt specification is the contract
  • Pydantic models enforce the contract at runtime
  • DSPy Signatures operationalize the contract for optimization
  • The Apple bridges extend the contract to on-device deployment
  • The evaluation framework measures how well the contract is fulfilled

When you can declare your intent in JSON, auto-generate type-safe models in Python and Swift, optimize the instructions for the specific hardware where they'll run, and evaluate the results with transparent metrics — you're not prompt engineering anymore. You're prompt engineering.

The fact that this works with Apple's on-device models out of the box is not a gimmick. It's a preview of the deployment topology that matters: cloud teachers, local students, privacy-preserving optimization loops, and zero-cost inference at the edge.

That's worth paying attention to.


prompt-better is MIT-licensed and available at github.com/pkcpkc/prompt-better. The author, Paul Hackenberger, also wrote an introductory Medium article.