# AQVEN > AQVEN is a TypeScript probe and AI workflow platform built on VoltAgent, with a local Studio UI and MCP server. Test hypotheses fast, prove every step with Golden benchmarks and stability matrices, and assemble verified end-to-end workflows. AQVEN builds on VoltAgent (@voltagent/core) for LLM execution, workflow DAG orchestration, checkpoints, and guardrails. --- # Welcome to AQVEN URL: https://aqvenstudio.com/start/ > Turn fragile prompts into verified, composable AI workflows. Test hypotheses fast as isolated probes, prove every step with Golden benchmarks and stability matrices, and assemble them into production pipelines. ## The problem with building AI workflows Most AI features start in a prompt playground or a quick script. They look impressive on three hand-picked examples, then silently break on real data: - Editing a prompt to fix one edge case quietly regresses five others. - Evaluation scripts live in a separate YAML harness, forcing you to rewrite everything for production and lose your checks. - Teams jump straight into multi-agent loops before proving whether a single constrained LLM call already solves the problem. - Passing one test run hides stochastic flakiness, silent provider fallbacks, and dropped input items. ## What AQVEN does **AQVEN** is a TypeScript platform—built on top of **VoltAgent**—for engineers and AI coding agents who build reliable LLM workflows. Instead of separating "evaluation tests" from "production code", AQVEN treats every LLM step as a **Probe**: a self-contained, versioned workflow unit (`InputSchema -> Pure Workflow -> ResultSchema`) paired with deterministic invariant checks, metrics, Golden benchmarks, and multi-run stability analytics. ```mermaid flowchart LR A["1. Slice
Break business process
into typed steps"] --> B["2. Prove Each Probe
Start small, check coverage,
Golden & stability"] B --> C["3. Snap Together
Unite proven workflows
with proofs out of the box"] ``` ## The 3-Act workflow 1. **Slice the business process:** Separate deterministic TypeScript logic from the exact steps where neural reasoning is needed. Give each step a strict Zod `Input -> Output` contract. 2. **Prove each probe in isolation:** Start with a single `andAgent` call. Run free static validation and mock self-tests, inspect smoke runs in **AQVEN Studio**, bootstrap a **Golden Dataset**, and measure run-to-run **Stability**. Escalate to batching, semantic merging, critic loops, or multi-model divergence *only* when metrics prove a simple call hit a ceiling. 3. **Assemble without rewriting:** Because every probe is already a pure `DefinedWorkflow`, you snap proven probes together (`chain.andWorkflow`) into one end-to-end pipeline—keeping shared rate-limit queues, durable checkpoints, hierarchical traces, and Studio visibility out of the box. ## Built for humans and AI coding agents together - **Humans** own domain meaning: reviewing visual traces in Studio, adjudicating ambiguous items into Golden datasets, and gating full runs. - **Coding agents** (Claude Code, Cursor, Codex, Antigravity) own rapid iteration: editing one variable at a time, running zero-cost checks, inspecting bounded traces via `aqven mcp`, and drafting candidate verdicts. ## Where to go next - [Platform architecture](/start/architecture/) — How AQVEN builds on VoltAgent and how its 4 parts fit together. - [Mental model & complexity ladder](/start/mental-model/) — How to decompose processes and decide when to escalate patterns. - [Quickstart](/start/quickstart/) — Scaffold a workspace, write your first probe, and inspect a live smoke run in 10 minutes. --- # Platform architecture URL: https://aqvenstudio.com/start/architecture/ > How AQVEN builds on top of VoltAgent (@voltagent/core) for LLM execution, DAG orchestration, and guardrails—and how its four modular parts work together. ## In short AQVEN does not reinvent LLM networking, model routing, or workflow execution. It builds on **[VoltAgent](https://github.com/VoltAgent/voltagent)** (`@voltagent/core`) for execution infrastructure and adds an experiment runtime, declarative constraint layer, append-only trace journal, **Studio UI**, and **MCP/CLI** harness on top. ```mermaid flowchart TB subgraph Top["AQVEN Surfaces"] Studio["Studio UI
(@aqven/studio)"] CLI["CLI & JSON API
(platform)"] MCP["MCP Server & Skills
(aqven mcp / harness)"] end subgraph Mid["AQVEN Platform Layer"] Runtime["Experiment Runtime & Journal
(@aqven/runtime, journal, db, core)"] SDK["Patterns & Matching SDK
(@aqven/patterns, matching)"] end subgraph Base["VoltAgent Foundation (@voltagent/core)"] VA["Agent · Model Router & Fallbacks · createWorkflowChain
Durable Checkpoints & timeTravel · Input/Output Guardrails · Embedders"] end Studio --> Runtime CLI --> Runtime MCP --> Runtime Runtime --> SDK SDK --> VA ``` ## What comes from VoltAgent Under the hood, AQVEN uses `@voltagent/core` directly for core AI runtime infrastructure: - **LLM & multimodal calls:** `Agent`, AI SDK model routing (`provider/model` or fallback arrays), `ModelMessage[]` turns (text, images, audio, files), `AiSdkEmbeddingAdapter`, tools, memory, and subagents. - **DAG orchestration & durable checkpoints:** `createWorkflowChain`, native steps (`andThen`, `andAll`, `andRace`, `andBranch`, `andWhen`, `andTap`, `andGuardrail`), and `timeTravel` step replay. - **Built-in safety & PII guardrails:** Ready-to-use `inputGuardrails` and `outputGuardrails` for prompt injection blocking, PII redaction (emails, phones, sensitive numbers), HTML sanitization, and length limits. Because AQVEN is a library—not a closed sandbox—you can drop down to native VoltAgent features at any point inside a probe. ## The four parts of AQVEN | Part | Packages | What it gives you | |---|---|---| | **1. Patterns & Matching SDK** | `@aqven/patterns`, `@aqven/matching` | Declarative `defineAgent`, `definePrompt`, `defineInference` (with `promptedEnum`, `allowedField`, `withCompleteness`, bounded schema `repair`), higher-order patterns (`andForEach`, `andMerge`, `andCriticLoop`, `andDivergent`), and an extensible `FieldMatcher` algebra for any data type. | | **2. Experiment Runtime & Journal** | `@aqven/runtime`, `@aqven/journal`, `@aqven/db`, `@aqven/core` | `defineProbe`, content-hashed `probe_hash` versioning, zero-cost `probe validate`, deterministic mock `probe test`, Smoke Gate, `LlmQueue` rate limiting + circuit breakers, append-only SQLite + file trace journaling (`.aqven/`), Golden dataset versioning, and 3-layer Stability matrices. | | **3. AQVEN Studio UI** | `@aqven/studio` (`aqven ui`) | Local web control plane showing interactive workflow DAGs, side-by-side run diffs, full rendered prompts vs. raw/parsed LLM outputs, stability heatmaps (`PresenceStrip`, `RepSquares`), and human Golden verdict queues. | | **4. CLI, API & Agent Harness** | `aqven` CLI, `aqven api`, `aqven mcp`, `@aqven/harness`, `@aqven/boilerplate` | One-command trace triage (`conclude`, `run --trace`, `step`), paginated MCP server, 6-skill coding-agent harness (`aqven-loop`, `aqven-models`, `aqven-build`, …), and one-command project scaffolding. | ## Domain- and language-agnostic by design Every shared package in AQVEN is strictly domain- and language-agnostic. No niche dictionaries or hardcoded entity types live in the library. Domain schemas, prompts, provider pins, and custom matchers live strictly in your project (`aqven.config.ts`, `agents/`, `probes/*`). ## See also - [Mental model & complexity ladder](/start/mental-model/) - [Extensibility & overrides](/core/extensibility/) - [Packages API reference](/reference/) --- # Mental model & complexity ladder URL: https://aqvenstudio.com/start/mental-model/ > How to decompose a business process into sequential probes, start with a single LLM call, escalate architecture only on evidence, and split work between humans and AI agents. ## In short Never build a complex multi-agent workflow before proving a single constrained LLM call cannot solve the task. Slice your business process into typed steps, prove Step `N` against real data before starting Step `N+1`, and escalate patterns only when trace metrics reveal a structural ceiling. ## 1. Decompose the business process A reliable AI workflow puts deterministic code around small, sharply defined neural steps: - **Keep in TypeScript:** arithmetic, totals, ID lookups, payload joins, filtering by exact rules, formatting, and schema assembly. - **Give to an LLM Probe:** classification, unstructured extraction, ambiguity resolution, policy interpretation, or semantic synthesis. Work **strictly sequentially**: do not design Step `N+1` until Step `N`'s probe passes its checks, Golden benchmark, and stability threshold. Step `N`'s real output reveals edge cases that change how Step `N+1` should be designed—and frozen Step `N` results double as fast local input datasets for Step `N+1`. ## 2. The Complexity Ladder: start small Jump straight to a reflection loop or multi-model ensemble and you multiply latency, cost, and debugging surface area before knowing whether a clearer enum description would have fixed the bug. | Stage | Primitive | When to use it | Typical cost multiplier | |---|---|---|---| | **Level 1: Single call** | `chain.andAgent` + `promptedEnum` + `allowedField` + `withCompleteness` | Default starting point for every probe. Solves ~80% of tasks. | `1x` | | **Level 2: Batched Map-Reduce** | `chunkByBudget` + `chain.andForEach` | Context saturation ("lost in the middle") or large input collections cause recall drops or timeouts. | `1x–1.3x` (parallelized) | | **Level 3: Algorithmic & Vector Merge** | `@aqven/matching` + `chain.andMerge` | Cross-batch duplicates or paraphrased items need deterministic/vector reconciliation before LLM reasoning. | Embeddings only (pennies) | | **Level 4: Multi-Model & Reflexive** | `chain.andCriticLoop`, `chain.andDivergent` | Single-prompt iterations plateau due to conflicting rules or single-model blind spots on the hardest 5–10% of cases. | `2x–4x` | ## 3. Change one variable per iteration Every experiment follows one disciplined loop: 1. Run `aqven conclude ` and inspect the actual failing prompt/raw pair. 2. Classify the failure by evidence (*wiring, schema, prompt, coverage, routing,* or *infra flake*). 3. Record **one hypothesis and one variable** with `aqven note --run "..."`. 4. Edit that single variable, run free checks (`probe validate` + `probe test`), run `--smoke`, and read the automatic metric delta. ## 4. Human + AI agent division of labor | Responsibility | Owner | Why | |---|---|---| | Write/edit probe files, run `validate`, `probe test`, `--smoke` | **AI Agent** | Fast, mechanical, zero human drudgery. | | Triage traces (`conclude`, `run --trace`, `aqven mcp`) | **AI Agent** | Reads structured JSON and pinpoints root causes in seconds. | | Draft candidate Golden verdicts (`keep / drop / fix`) | **AI Agent** | Prepares full context + rationale per item. | | Define domain truth & adjudicate ambiguous verdicts | **Human** | Business semantics belong to the owner, never guesswork. | | Approve Golden sets & unlock `--full` / `stabilize` runs | **Human** | Prevents silent benchmark drift and unapproved API spend. | ## See also - [Quickstart](/start/quickstart/) - [Universal LLM failure modes](/core/llm-failure-modes/) - [Escalating workflow patterns](/workflows/) --- # Quickstart URL: https://aqvenstudio.com/start/quickstart/ > Scaffold an AQVEN workspace, build a single-step classification probe in ~50 lines of TypeScript, validate it for free, and inspect your first live smoke run in Studio UI. ## What you'll have at the end In under 10 minutes you will have a working TypeScript probe with compile-time prompt checks, dynamic allowed ID sets, 100% input completeness enforcement, a passing mock self-test, and a live 3-item smoke run visible in **AQVEN Studio**. ## Before you start - Node.js `20.19+` - An OpenRouter API key (or any VoltAgent-supported AI SDK provider key) in `.env` ## 1. Scaffold a workspace (`npm create @aqven@latest`) Create a standalone AQVEN project with published `@aqven/*` packages, pre-wired MCP configs (`.mcp.json`, `opencode.json`, `.codex/config.toml`), `AGENTS.md` / `CLAUDE.md`, and the 6-skill `@aqven/harness` suite: ```bash npm create @aqven@latest my-project -- --install cd my-project cp .env.example .env # Add OPENROUTER_API_KEY=... (or your provider key) to .env ``` Your scaffolded project has a clean, auto-discovered layout: ```text my-project/ aqven.config.ts # Provider rate limits, embedder, workflow config AGENTS.md # Coding-agent rules & skill routing table .agents/skills/ # 6-skill @aqven/harness suite (aqven-docs, aqven-loop, ...) .mcp.json # Pre-wired stdio MCP server (`aqven mcp`) agents/ # Shared defineAgent(...) declarations & .with() variants datasets/ # Input JSON fixtures probes/ example/ schema.ts # Zod schemas (single source of truth) prompt.ts # Compile-time checked prompt template inferences.ts # Declarative LLM calls + constraints workflow.ts # Pure defineWorkflow(...) DAG (zero I/O) probe.ts # prepareInput + workflow + stability + golden + evaluate ``` ## 2. Inspect your first single-step probe A minimal probe stays under ~50 lines of business logic: ```ts // probes/example/schema.ts import { allowedField, nonBlankString, promptedEnum } from "@aqven/patterns"; import { z } from "zod"; export const priorityEnum = promptedEnum("priority", [ { value: "urgent", description: "Service outage, security incident, or blocked revenue" }, { value: "normal", description: "Standard customer request or non-blocking bug" }, { value: "low", description: "Feature idea, feedback, or informational message" }, ]); export const ticketSchema = z.object({ id: z.string(), subject: z.string(), body: z.string(), }); export const decisionSchema = z.object({ ticketId: allowedField("ticketId"), priority: priorityEnum.schema, summary: nonBlankString, }).strict(); export const inputSchema = z.object({ items: z.array(ticketSchema) }); export const outputSchema = z.object({ decisions: z.array(decisionSchema) }).strict(); export const resultSchema = z.object({ universe: z.array(z.string()), records: z.array(decisionSchema), }); ``` ```ts // probes/example/inferences.ts import { defineInference, definePrompt, withCompleteness } from "@aqven/patterns"; import { defaultAgent } from "../../agents"; import { inputSchema, outputSchema } from "./schema"; export const triagePrompt = definePrompt({ template: "Classify every support ticket in {{items}}.", vars: { items: (input: { items: unknown[] }) => input.items }, }); export const triageTickets = defineInference({ agent: defaultAgent, input: inputSchema, prompt: triagePrompt, allowedSets: { ticketId: (input) => input.items.map((t) => t.id) }, // allowedField prevents invented IDs (subset); withCompleteness guarantees every input ID appears once (no silent drops or duplicates) output: withCompleteness(outputSchema, { universe: "ticketId", refs: (out) => out.decisions.map((d) => d.ticketId), }), }); ``` ```ts // probes/example/workflow.ts & probe.ts import { defineWorkflow, prepareJsonItems } from "@aqven/patterns"; import { defineProbe, errorRate, exactCoverCheck } from "@aqven/runtime"; import * as R from "remeda"; import { triageTickets } from "./inferences"; import { inputSchema, resultSchema } from "./schema"; export const triageWorkflow = defineWorkflow({ id: "example.triage", name: "Ticket Triage", input: inputSchema, result: resultSchema, inferences: { triageTickets }, build: (deps, { chain }) => chain.andAgent({ id: "triage", inference: deps.triageTickets, map: (out, { initialInput }) => ({ universe: initialInput.items.map((t) => t.id), records: out.decisions, }), }), }); export const probe = defineProbe({ version: 1, description: "Assign priority and concise summary to each incoming ticket.", workflow: triageWorkflow, prepareInput: prepareJsonItems({ select: (dataset: { items: unknown[] }) => dataset.items }), evaluate: { checks: [ exactCoverCheck({ name: "ticket-id-conservation", universe: ({ result }) => result.universe, refs: ({ result }) => result.records.map((r) => r.ticketId), }), ], metrics: [ errorRate(), { name: "priority-counts", primary: true, run: ({ result }) => R.countBy(result.records, (r) => r.priority), }, ], }, }); ``` ## 3. Validate for free before spending a cent Always run static validation (`0` LLM calls) and the deterministic mock self-test before hitting a live provider: ```bash npm run validate npm run test:probe -- --chaos 1 ``` ### Check Both commands exit with code `0`. `probe validate` verifies prompt variables, `allowedField` wiring, strict output schemas, and workflow dry-build; `probe test` proves input delivery, prompt determinism, and retry logging on a local mock model. ## 4. Run your first live smoke test and open Studio ```bash npm run smoke npx aqven conclude ``` Launch **AQVEN Studio** to inspect the interactive workflow graph, full rendered prompt (including auto-appended `promptedEnum` descriptions and `allowedSets`), Golden coverage (`10/10`), Partition agreement (`ARI` / `F1`), parsed JSON, and token cost: ```bash npm run studio ``` ![AQVEN Studio — Verified support ticket triage run showing 10/10 Golden coverage, ARI 1.00 partition agreement, 5 incident clusters, and 2/2 contract checks](/screenshots/studio-run-golden.webp) ## What's next - [Your first scientific iteration](/start/first-iteration/) — Diagnose a failure with `conclude`, change one variable, and measure the delta. - [Schema-first contracts](/core/schemas/) — Dive deeper into constraints and variations. --- # Your first scientific iteration URL: https://aqvenstudio.com/start/first-iteration/ > Diagnose a smoke run with aqven conclude, record a single-variable hypothesis, edit your probe, and compare automatic deltas across versions. ## What you'll have at the end You will complete one full AQVEN iteration loop: reading real trace evidence, logging a hypothesis, making a single targeted change, and verifying the delta between `Run 1` and `Run 2`. ## 1. Read the full diagnosis kit (`conclude`) Never edit a prompt by guessing from the final JSON. Inspect the complete evidence bundle for your smoke run: ```bash npm run aqven -- conclude ``` `conclude` prints checks, metrics, failed or repaired attempts (with rendered prompt and raw output), prior notes, and deltas against the previous run. To drill into a specific step and its attempts in one call: ```bash npm run aqven -- step :triage --input --output --attempts ``` ## 2. Classify the failure and pick ONE variable Before touching code, check `npm run aqven -- history ` so you do not repeat a rejected hypothesis. Then record what you learned and the **single** variable you are changing: ```bash npm run aqven -- note --run "Ticket #2 labeled urgent despite having a workaround. Hypothesis: clarify 'urgent' description in priorityEnum to exclude issues with an active workaround. Variable: promptedEnum description only." ``` ## 3. Edit, validate, and re-run smoke Update only that single enum description in `schema.ts`. Editing any `.ts` file inside the probe folder automatically computes a new `probe_hash`—you never overwrite prior runs. ```bash npm run aqven -- probe validate example.triage npm run aqven -- run example.triage --dataset datasets/example.json --smoke 3 ``` ## 4. Inspect the delta Run `aqven conclude ` or open **Studio UI → Compare (`/compare`)** to compare the two runs side by side: - Check statuses and `check flips` - Primary metric `Δ`, latency, and provider-reported cost - Structural diff between the two `probe_hash` versions in **VersionDiffDrawer** ## What's next - [Golden datasets](/evaluate/golden-datasets/) — Turn your verified smoke output into an immutable benchmark. - [Universal LLM failure modes](/core/llm-failure-modes/) — Learn which primitive fixes each class of model error. --- # Core building blocks URL: https://aqvenstudio.com/core/ > Master Level 1 probe authoring—schema-first contracts, declarative agents and inferences, pure workflows, full extensibility, and solutions to universal LLM failure modes. ## Why Level 1 matters most Roughly 80% of production LLM problems do not need multi-agent reflection loops or complex ensembles. They fail because of weak schemas, missing foreign-key constraints, desynchronized enum descriptions, or unmeasured prompt edits. AQVEN gives you composable TypeScript primitives that solve structural reliability right at the single-call level—while letting you override or extend any piece whenever your domain requires it. ## What is in this section - [Schema-first contracts](/core/schemas/) — Zod as the single source of truth, `promptedEnum`, `allowedField`, `withCompleteness`, and `exactCover`. - [Agents, prompts & inferences](/core/agents-prompts-inferences/) — `defineAgent` + `.with()`, compile-time `definePrompt`, `defineInference`, custom `validate()`, automatic schema repair, and multimodal `messages()`. - [Workflows & probes](/core/workflows-and-probes/) — Pure `defineWorkflow`, `prepareInput`, typed `workflow.config`, and end-to-end type inference in `defineProbe`. - [Extensibility & overrides](/core/extensibility/) — Override anything with `.with()`, match any data type (including images via `customMatcher` + `prepare`), and drop down to native VoltAgent APIs. - [Universal LLM failure modes](/core/llm-failure-modes/) — A domain-agnostic catalog of how LLMs fail in production, which AQVEN or VoltAgent primitive fixes each class, and upcoming [Roadmap](/roadmap/) primitives. --- # Schema-first contracts URL: https://aqvenstudio.com/core/schemas/ > Design Zod v4 schemas that serve as the single source of truth for TypeScript types, rendered prompts, dynamic ID conservation, and reliable constrained decoding across providers. ## The problem When TypeScript interfaces, JSON schemas, and prompt instructions live in separate files, they inevitably drift apart. Worse, naive JSON schemas fail in two subtle ways in production: 1. They validate syntactic *shape* while allowing invented IDs, silently skipped input records, or fabricated fallback values. 2. They violate constrained-decoding physics—putting labels before reasoning, nesting `5` levels deep, or multiplying large enums across arrays until providers reject the grammar (`OUTPUT_SCHEMA_REJECTED`) or accuracy drops. ## Core principles 1. **Derive types, never duplicate:** Every TypeScript domain type comes from `z.infer`. 2. **Ask decisions, compute derivations:** Ask the LLM only for irreducible semantic choices (IDs, classifications, merge/drop verdicts); compute counts, offsets, totals, and nested trees deterministically in TypeScript (`remeda`). 3. **Keep workflow schemas JSON-durable & `.strict()`:** Use JSON-serializable Zod primitives (`object`, `array`, `string`, `number`, `boolean`, `nullable`, `discriminatedUnion`) so checkpoints and `aqven resume` replay losslessly—avoid `z.date()`, `z.map()`, `z.set()`, `z.bigint()`, and `z.transform()` in workflow I/O, and mark every LLM output object `.strict()`. --- ## Schema design rules for reliable decoding ### 1. Place `evidence` / `rationale` BEFORE `decision` / `label` Under constrained decoding, models generate JSON keys strictly left-to-right. If `tier` comes first and `rationale` comes second, the model commits to `tier` on token 1 without thinking and uses `rationale` to rationalize its guess (paying a **3–9 pp "Format Tax"**). Always order supporting evidence/reasoning fields *before* the classification or verdict field. ### 2. Model the 5 states of an answer (`present`, `absent`, `cannot_tell`, `other`) - **Only ask what the input can actually show:** Never require a non-nullable field (e.g., `paidAt` on an invoice PDF that shows only amount due) or the model will hallucinate a value. Use `.nullable()` when a scalar may legitimately be absent. - **Separate `absent` from `cannot_tell`:** On blurry scans, truncated clips, or ambiguous snippets, binary `yes | no` forces the model to lie. Give real-world enums explicit `cannot_tell` (input is insufficient) and `other` (input falls outside nominal categories) values—and ensure retry checks accept `cannot_tell`. - **Ask about the subject, not model ability:** Never ask *"Can you read this document?"* (models answer `"yes"` even on blank pages); ask for the concrete target property directly. ### 3. Keep state space flat, bounded & portable across providers - **Nesting ceiling (`<= 2–3` levels) & field count (`<= 20` fields):** Deep nesting (`4+` levels) causes `17–30+ pp` accuracy drops; `50+` fields risk grammar compilation failure. Keep LLM schemas flat and reshape in code. - **Enum sizing (`<= 20` values):** Keep closed `promptedEnum` sets tight (`~5–15` values). For `50+` database codes, pass narrowed candidates via `allowedField` + `allowedSets` instead of giant static enums. - **Empty-array (`[]`) permission:** Constrained decoders statistically disfavor closing `[]` immediately, causing phantom extractions on clean inputs. Explicitly note *"Return `[]` if none exist"* in `.describe(...)`. - **Portable unions:** Always use `z.discriminatedUnion("kind", [...])` with explicit `z.literal(...)` tags (compiles cleanly to `anyOf` + discriminator; bare `oneOf` fails on OpenAI strict mode and is ignored by Gemini). ### 4. Final outputs vs. intermediate step schemas "Fewest possible fields" applies to **final** outputs. When Step A feeds Step B, design Step A's schema around **the exact pairs Step B confuses** (e.g., to stop Step B from confusing *refund request* vs. *billing error*, Step A must extract `moneyAlreadyCharged`). Pilot intermediate schemas on ~10 varied cases: any field taking the same constant value on `>80%` of cases carries near-zero signal. --- ## Variation A: Self-documenting enums (`promptedEnum`) Never hand-copy enum lists into prompt templates. Declare values and decision boundaries once with `promptedEnum`; `defineInference` injects them automatically, and `probe validate` warns on bare enums or duplicated text. ```ts import { promptedEnum } from "@aqven/patterns"; import { z } from "zod"; export const riskTierEnum = promptedEnum("riskTier", [ { value: "high", description: "Immediate regulatory, financial, or security exposure" }, { value: "medium", description: "Requires human review before release; no immediate block" }, { value: "low", description: "Standard compliant clause with no material exposure" }, { value: "cannot_tell", description: "Clause text is cut off, illegible, or references missing exhibits" }, ]); export type RiskTier = z.infer; ``` ## Variation B: Dynamic foreign keys & 100% completeness (`allowedField` vs. `withCompleteness`) These two primitives enforce **two distinct mathematical invariants**: - **`allowedField("key")` + `allowedSets.key` (Subset `⊆` — zero invented IDs):** Every returned ID must belong to the live request's input set. Use alone when partial selection is valid (e.g., citing `sourceId`s where some pages contain no findings). - **`withCompleteness(schema, { universe, refs })` (Exact 1-to-1 cover `=` — zero silent drops or duplicates):** Every ID in `universe` must appear **once and only once**. Use whenever every input item requires a decision. `allowedField("key")` already returns `z.string().meta(...)` (do not append `.pipe(z.string())`): ```ts import { allowedField, nonBlankString, withCompleteness } from "@aqven/patterns"; import { z } from "zod"; const findingSchema = z.object({ clauseId: allowedField("clauseId"), // Evidence/rationale BEFORE tier prevents post-hoc rationalization: rationale: nonBlankString.describe("Concrete clause evidence or reason why cannot_tell"), tier: riskTierEnum.schema, }).strict(); const rawOutputSchema = z.object({ findings: z.array(findingSchema), }).strict(); export const auditOutputSchema = withCompleteness(rawOutputSchema, { universe: "clauseId", refs: (out) => out.findings.map((f) => f.clauseId), }); ``` ## Variation C: Reusable `exactCover` & deterministic `verify` Declare a partition invariant once with `exactCover` and reuse it across Zod validation, deterministic post-assembly checks, and `probe.evaluate`: ```ts import { exactCover, nonBlankFields, referencesWithin, uniqueValues, verify } from "@aqven/patterns"; export const decisionCover = exactCover<{ universe: string[]; keep: string[]; drop: string[] }>({ universe: (d) => d.universe, refs: (d) => [...d.keep, ...d.drop], }); // Deterministic post-assembly invariant check (throws ViolationsError on failure) verify(assembledResult, [ uniqueValues((r) => r.records.map((x) => x.id), "duplicate-record-id"), referencesWithin((r) => r.records.map((x) => x.id), (r) => r.universe, "unknown-record-id"), nonBlankFields((r) => r.records.map((x) => x.rationale), "blank-rationale"), ]); ``` ## Variation D: Schema-driven multimodal & rich-text content (`@aqven/patterns`) Declare media and rich-text semantics directly in your Zod schemas so **AQVEN Studio** renders `` previews automatically across Run traces, Step I/O, Golden tables, `/compare`, and Stability heatmaps—without leaking non-standard JSON Schema keywords to strict LLM providers: - **`mediaPath(mediaType, { timeRange?, description? })`** — Workspace- or dataset-relative file path (e.g. `"images/01.jpg"`, `"clips/call.mp4#t=12.5,24"`). - **`mediaUrl(mediaType, { timeRange?, description? })`** — `https://...`, `data:...`, or `/api/media/...` URI, supporting `#t=start,end` media fragments and `#page=N` PDF anchors. - **`mediaBase64(mediaType, { description? })`** — Inline base64 payload; payloads exceeding `4096` chars are offloaded automatically on journal write to content-addressed `.aqven/blobs` (`{ __media: { sha256, mediaType, sizeBytes, href } }`) so SQLite and step JSON files stay fast. - **`contentText("markdown" | "code" | "plain", { language?, allowEmpty?, description? })`** — Sanitized Markdown, syntax-highlighted source code, or plain text. - **`withContent(schema, meta)`** — Attaches content metadata to an existing schema such as `allowedField("assetId")` or a composite `z.object(...)` clip descriptor (`fields: { src, mediaType?, startSec?, endSec?, page?, label? }`). ```ts import { allowedField, contentText, mediaBase64, mediaPath, mediaUrl, withContent, } from "@aqven/patterns"; import { z } from "zod"; export const mediaAssetInputSchema = z.object({ assetId: z.string(), framePath: mediaPath("image/jpeg", { description: "Inspection camera frame" }), manualPdfUrl: mediaUrl("application/pdf", { description: "Reference manual (#page=N)" }), scanBase64: mediaBase64("image/png").optional(), clip: withContent( z.object({ clipPath: z.string(), startSec: z.number(), endSec: z.number(), label: z.string(), }).strict(), { mediaType: "video/mp4", fields: { src: "clipPath", startSec: "startSec", endSec: "endSec", label: "label" }, }, ), }).strict(); export const inspectionOutputSchema = z.object({ assetId: allowedField("assetId"), reportMarkdown: contentText("markdown"), patchSnippet: contentText("code", { language: "typescript" }).nullable(), }).strict(); ``` > **Automatic provider sanitization (`sanitizeProviderJsonSchema`):** Before calling structured-output providers, `defineInference` strips UI/annotation-only JSON Schema keywords (`contentMediaType`, `contentEncoding`, `x-content`, `x-prompted-enum`, `x-allowed-set`, and `format: "uri-reference"` / content-annotated `format: "uri"`), preventing `OUTPUT_SCHEMA_REJECTED` errors on strict OpenAI, Gemini, and OpenRouter endpoints while keeping full `ContentDescriptor` metadata in the probe contract snapshot for Studio `` (images, HTTP Range-streamed audio/video, PDFs, Markdown, and code). ## See also - [Agents, prompts & inferences](/core/agents-prompts-inferences/) - [Playbooks C & D: Extraction & multimodal assembly](/playbooks/extraction-and-multimodal/) - [Production LLM failure modes & mitigations](/core/llm-failure-modes/) --- # Agents, prompts & inferences URL: https://aqvenstudio.com/core/agents-prompts-inferences/ > Declare immutable agents with .with() cloning, compile-time checked prompts, declarative inferences with custom validators, bounded schema repair, and multimodal messages. ## The problem Copy-pasting model calls across files makes swapping models, testing reasoning effort, adding safety guardrails, or sending multimodal payloads error-prone. Worse, when a structured output fails one cross-field rule, blind retries discard the response without telling the model what went wrong. ## 1. Agents (`defineAgent` & `.with()`) `defineAgent(config: PlatformAgentConfig)` declares an immutable agent configuration. Use `.with(overrides)` to clone variants with deep-merged `providerOptions`, `callDefaults`, and `hooks`: ```ts import { defineAgent } from "@aqven/patterns"; import { createDefaultInputSafetyGuardrails, createDefaultPIIGuardrails } from "@voltagent/core"; export const baseAgent = defineAgent({ name: "triage-fast", model: "deepseek/deepseek-v4.1-flash-1017", instructions: "Classify each record accurately. Return structured JSON only.", callDefaults: { temperature: 0 }, attemptTimeoutMs: 120_000, retryPolicy: "standard", inputGuardrails: createDefaultInputSafetyGuardrails(), outputGuardrails: createDefaultPIIGuardrails(), }); // One-line clone overriding model or reasoning parameters export const reasoningAgent = baseAgent.with({ name: "triage-reasoning", model: "google/gemini-2.5-pro", }); ``` Key `PlatformAgentConfig` fields: | Field | Required | Notes | |---|---|---| | `name`, `model`, `instructions` | Yes | `model` accepts any VoltAgent `AgentModelValue` (router ID string, `LanguageModel`, or fallback array). | | `providerOptions`, `callDefaults` | No | Deep-merged across `.with()`. Use project helpers (e.g. `pinOpenRouter`) to pin providers. | | `attemptTimeoutMs` | No | Default `300_000` ms so stalled upstream connections fail cleanly instead of hanging. | | `retryPolicy`, `maxRetries` | No | Platform-owned retries (`standard`, `aggressive`, `none`) journal every `llm_retry` event. | | `inputGuardrails`, `outputGuardrails` | No | Native `@voltagent/core` guardrails (PII, prompt injection, profanity, length, custom). | ## 2. Compile-time checked prompts (`definePrompt`) `definePrompt` uses VoltAgent's `ExtractVariableNames