FACET Language: From Prompt Chaos to Engineering Contracts
Update (March 2026): FACET has evolved significantly since this v1.1 article. The standard is now at v2.1.3 (REC-PROD), featuring a formal Policy Model, capability classes, and fail-closed Runtime Guards. The core philosophy described here remains the foundation, but the implementation is now industrial-grade.
For too long, AI development has suffered from non-deterministic chaos. Same prompt, different results. No contracts. No reproducibility. Even temperature=0 doesn't solve the fundamental problem.
Frustrated by this "dark art," I built FACET — a deterministic markup language that transforms prompt engineering into an actual engineering discipline.
The Problem: Prompt Engineering Is Broken
Three Critical Pain Points
1. Non-Determinism
Run the same prompt twice, get different outputs. Debugging is impossible. A/B testing is a nightmare.
2. No Contracts
LLMs hallucinate freely. No schema validation. No output guarantees. Runtime surprises instead of compile-time checks.
3. Zero Modularity
Prompts scattered across codebases. Copy-paste everywhere. No version control. No reuse.
Why Existing Approaches Fail
YAML/JSON: Syntax without AI semantics. No validation, no transforms, no guarantees.
Jinja/Mustache: String interpolation without contracts. Doesn't prevent hallucinations.
Langchain: Imperative code, not declarative specs. Hard to test, version, and reproduce.
For a detailed comparison of why FACET outperforms YAML and JSON for AI systems, I break it down in a separate article with examples from years of working with these formats.
The industry needed something fundamentally different.
Our Solution: FACET Language v1.1
One
.facetfile = One canonical JSON = Deterministic result
FACET (Feature-Aware Contracted Extension for Text) is a deterministic markup language designed for AI systems. Every document compiles to a single, canonical JSON representation.
Real-World Validation
In production testing, a meta-agent without its runtime read the declarative blueprint of a tool, synthesized its own interpreter, and completed the task successfully.
Conclusion: Structure doesn't limit AI — it makes it more reliable and more creative.
Core Architecture
A Complete FACET Specification
@vars
username: "Alex"
mode: "expert"
seed: 42
greetings: ["Hi", "Hello", "Hey"]
@var_types
username: { type: "string" }
mode: { type: "string", enum: ["novice", "expert"] }
seed: { type: "int", min: 0 }
@system(role="Expert", if="mode=='expert'")
constraints:
- "Use precise terminology"
- "Provide benchmarks"
@user
request: """
{{greetings |> choose(seed=$seed)}}, {{username}}!
Explain recursion with tail-call optimization.
""" |> dedent |> trim
@output
schema:
type: "object"
required: ["summary", "examples", "complexity"]
properties:
summary: { type: "string", minLength: 100 }
examples: { type: "array", minItems: 2 }
complexity: { type: "string", enum: ["O(n)", "O(log n)"] }
Why This Works
Declarative Specification
Define what you want, not how to get it. System handles validation and execution.
Built-in Validation
JSON Schema contracts on outputs. Compile-time type checking. Static analysis catches errors before LLM is invoked.
Deterministic Transforms
Lenses (|>) are pure functions with explicit seeds. choose(seed=42) always returns the same result.
One Canonical JSON
Reproducible across machines, teams, time. Perfect for CI/CD pipelines.
Five Key Features
1. Deterministic Lenses (Pure Pipeline Transforms)
@vars
options: ["Plan A", "Plan B", "Plan C"]
chosen: $options |> choose(seed=42) # Always same element
@user
prompt: """
Please explain Docker.
""" |> dedent |> trim |> squeeze_spaces
Built-in Lenses:
trim,dedent,squeeze_spaces— Text cleanuplower,upper,limit(n)— Formattingchoose(seed),shuffle(seed)— Deterministic selection
Performance: SIMD-accelerated, 3.7× faster than regex approaches.
2. Compile-Time Type System
@vars
retries: 3
env: "prod"
@var_types
retries: { type: "int", min: 0, max: 10 }
env: { type: "string", enum: ["dev", "staging", "prod"] }
Type violations raise F451/F452 errors before LLM invocation.
3. Modularity Through Imports
@import "common/system_prompts.facet"
@import(path="configs/prod.facet", strategy="merge")
@user
request: "Analyze data"
Features:
- Relative paths only (security)
- Allowlist enforcement
- Cycle detection
- Two merge strategies:
merge(deep) orreplace
4. Conditional Logic
@vars
env: "prod"
@system(if="env=='dev'")
logging: "verbose"
@system(if="env=='prod'")
logging: "errors-only"
@plan
steps:
- "Validate input"
- "Run chaos tests" (if="env!='dev'")
Expression Language: ==, !=, <, >, in, and, or, not
5. Output Contracts
@output
schema:
type: "object"
required: ["analysis", "confidence"]
require:
- "No hallucinations — cite all facts"
- "All code must be runnable"
JSON Schema validation catches violations before they reach production.
The Canonization Pipeline
.facet file
↓
1. Parse (strict 2-space indent)
↓
2. Expand imports (allowlist, cycles)
↓
3. Resolve variables ($name, {{path}})
↓
4. Validate types (@var_types)
↓
5. Evaluate conditionals (if="expr")
↓
6. Resolve anchors (&name, *name)
↓
7. Apply lenses (|> choose(seed))
↓
8. Construct JSON
↓
Canonical JSON ✅
Key Property: Same input → byte-for-byte identical output
Practical Example: A/B Testing
The Use Case
Test two prompt strategies:
- Variant A: Concise (150 tokens max)
- Variant B: Detailed (500 tokens max)
Implementation
@vars
variant: "B"
seed: 12345
@system(if="variant=='A'")
style: "concise"
max_tokens: 150
@system(if="variant=='B'")
style: "detailed"
max_tokens: 500
@user
request: "Explain Docker containerization."
@output
schema:
required: ["explanation", "token_count", "variant_id"]
Results from Production
| Metric | Variant A | Variant B |
|---|---|---|
| Avg Tokens | 147 | 312 |
| Latency (p95) | 1.2s | 2.8s |
| User Satisfaction | 7.2/10 | 8.9/10 |
| Reproducibility | ✅ 100% | ✅ 100% |
Key Insight: Variant B delivered better satisfaction despite higher latency. Deterministic seeds allowed exact reproduction for debugging.
Production Use Cases
1. Enterprise Prompt Management
Challenge: 50+ teams, 200+ prompts, compliance requirements
Solution:
@import "company/brand_voice.facet"
@import "legal/disclaimers.facet"
@vars
customer_tier: "enterprise"
region: "eu-west"
@system(if="region=='eu-west'")
compliance: ["GDPR", "ISO-27001"]
Results:
- Compliance: 100% audit-ready
- Reusability: 80% reduction in duplication
- Deployment Velocity: Deploy prompts in <1 hour (was 1 day)
2. Multi-Environment Orchestration
@vars
env: "staging"
@safety(if="env=='dev'")
dry_run: true
@safety(if="env=='prod'")
dry_run: false
confirm_dangerous_ops: true
Benefits: Safety guarantees per environment, audit trail via Git.
3. Seeded Randomness for ML
@vars
experiment_id: 42
variants: ["Style A", "Style B", "Style C"]
@user
prompt: $variants |> choose(seed=$experiment_id)
Results: 100% reproducibility across runs, machines, teams.
Common Anti-Patterns
❌ Over-Engineering Simple Cases
# BAD: Unnecessary complexity
@vars
greeting: "Hello"
@var_types
greeting: { type: "string", pattern: "^[A-Z][a-z]+$" }
# GOOD: Keep it simple
@system
greeting: "Hello"
❌ Lens Chain Abuse
# BAD: 10+ lenses
text: $input |> trim |> lower |> dedent |> squeeze |> ...
# GOOD: Preprocess outside FACET
text: $preprocessed |> trim
❌ Forgetting Seeds
# ERROR: F804
choice: $options |> choose()
# CORRECT:
choice: $options |> choose(seed=42)
Performance Benchmarks
Canonization Performance
| Operation | Latency (p50) | Latency (p95) |
|---|---|---|
| Parse | 0.2ms | 0.5ms |
| Import Resolution | 1.2ms | 3.8ms |
| Variable Substitution | 0.3ms | 0.9ms |
| Type Validation | 0.4ms | 1.1ms |
| Lens Application | 0.8ms | 2.2ms |
| Total (end-to-end) | 3.7ms | 10.6ms |
Benchmark: MacBook Pro M1, 2000-line spec with 10 imports
Lens Performance (SIMD-accelerated)
| Lens | Operations/sec | vs. Regular Expressions |
|---|---|---|
trim |
1.2M | 3.7× faster |
squeeze_spaces |
890K | 4.1× faster |
dedent |
650K | 2.9× faster |
Production Deployment Checklist
Before deploying FACET specs:
Type Safety
- [ ] All variables typed via
@var_types - [ ] No forward references in
@vars - [ ] Enums for categorical variables
Imports & Modularity
- [ ] Import paths use allowlist
- [ ] No import cycles
- [ ] Versioning for shared facets
Lenses
- [ ] No chains longer than 5 operations
- [ ] All
choose()/shuffle()have seeds
Contracts
- [ ] Output schema for critical requests
- [ ] Business rules in
requireclauses
Testing
- [ ] Unit tests for canonization
- [ ] Integration tests with LLMs
- [ ] A/B results reproducible
Tools and Resources
Official Resources
- Specification: FACET v1.1 Spec
- Parser (Python):
pip install facet-lang - MCP Server: FACET MCP
- Agents: 15+ FACET Agents
- Orchestration: RMCP Protocol
Quick Start
# Install
pip install facet-lang
# Canonize a spec
facet canon my-prompt.facet
# With variables
facet canon --resolve=all --var "env=prod" my-prompt.facet
# Validate
facet validate my-prompt.facet
Python Integration
from facet_lang import canonize
result = canonize(
document=open('prompt.facet').read(),
resolve_mode='all',
host_vars={'username': 'Alice', 'env': 'prod'}
)
print(result['canonical_json'])
Comparison with Alternatives
| Feature | YAML | JSON | Langchain | FACET |
|---|---|---|---|---|
| Readability | ⭐⭐⭐ | ⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| Determinism | ❌ | ✅ | ❌ | ✅ |
| Contracts | ❌ | ❌ | ❌ | ✅ |
| Type Safety | ❌ | ❌ | Partial | ✅ |
| Modularity | ❌ | ❌ | Code-level | ✅ |
Conclusion
FACET v1.1 transforms prompt engineering from a dark art into an engineering discipline.
Key Takeaways:
- Determinism is achievable: canonical JSON + seeded lenses
- Contracts prevent chaos: output schemas catch errors early
- Types eliminate surprises: compile-time checks beat runtime failures
- Modularity scales: imports + version control = maintainable prompts
Recommendations:
Week 1: Convert 1-2 critical prompts to FACET
Week 2-4: Add @var_types and output contracts
Month 2: Extract common patterns into imports
Month 3+: Full production with monitoring
Metrics to Track:
- Reproducibility rate: % of runs with identical outputs
- Contract violations: % of outputs failing validation
- Deployment velocity: Time from spec change to production
Next Steps:
- Read the full specification
- Try the MCP server with Claude
- Explore RMCP orchestration
- Study real agents
P.S. Structure makes AI not only reliable but more creative. This isn't a limitation — it's the foundation for scalable AI systems.
By Emil Rokossovskiy — creator of the FACET ecosystem. Want to contribute? Join the discussion.