Crux
API Reference@use-crux/core

Prompts

prompt(), createPrompts(), Prompt resolution, and request preview.

import { createPrompts, prompt } from "@use-crux/core";

prompt() creates a frozen, SDK-agnostic Prompt definition. Adapters execute it; Crux inspects, tests, caches, and instruments it.

prompt(config)

const summarize = prompt({
  id: "summarize",
  input: z.object({ text: z.string() }),
  output: z.object({ summary: z.string() }),
  system: "Summarize the text in one sentence.",
  prompt: ({ input }) => input.text,
});

Config

FieldTypeDescription
idstring?Stable identifier for registries, logs, Devtools, Evals, and cache keys.
descriptionstring?Human-readable description.
tagsreadonly string[]?Tags for filtering, discovery, and Eval grouping.
usereadonly ContextEntry[]?Composition entries. See Prompt Resolution.
inputZodType?Prompt-owned input schema, merged with composed input schemas.
outputZodType?Structured output schema. Omit for text generation.
systemstring | ContextSystemContent | PromptText | callbackRole, policy, and high-level instructions. Mutually exclusive with messages.
promptstring | PromptText | synchronous callbackSingle-turn user or task message. Mutually exclusive with messages.
messages({ input }) => Message[]Full message-list mode. Mutually exclusive with system and prompt.
settingsGenerationSettings?SDK-agnostic generation defaults.
adaptProviderAdaptations?Provider or model-specific system, prompt, and settings overrides.
hooksPromptHooks?Per-Prompt lifecycle hooks.
toolsToolSet?Prompt-local tools. Prompt-time names must be unique across composed sources.
toolMiddlewareToolMiddleware | readonly ToolMiddleware[]?Server-side Prompt tool wrappers, including audit and approval.
rawFieldsreadonly string[]?Schema-typed top-level fields skipped by auto-escape for trusted pre-formatted content.
escapeFieldsreadonly string[]?Schema-typed top-level fields recursively XML-escaped across strings, arrays, and plain records.
sanitize(input) => inputOptional parsed-input transform that runs before auto-escape and context resolution.
testsEvalCase[]?Inline Eval cases discovered by the Eval runner.
constraintsConstraintDef[]?Semantic constraints evaluated around generation.
guardrailsGuardrailDef[]?Pre- and post-generation guardrails.
cachePromptCacheOptions?Semantic response-cache options and the Prompt-owned provider-cache hint.

Return Value

prompt() returns a frozen Prompt.

PropertyDescription
_tagRuntime discriminant: "Prompt".
idPrompt identifier.
descriptionDescription string.
tagsTag array.
contextsOriginal use tuple.
inputSchemaMerged input schema, if any.
outputSchemaOutput schema, if configured.
hasOutputLiteral true when structured output is configured, otherwise literal false.
configReadonly original config.
MethodDescription
.resolve(options)Validate and return the composed ResolvedPrompt without calling a model.

PromptText

system and prompt accept ordinary strings or the opaque PromptText value created by md. See the PromptText reference for exact composition, inspection, Project Index, preview, error, and security contracts.

Prompt Resolution

See Prompt Resolution for:

  • every supported use entry and custom contributor() entries;
  • merged input inference and Context composition order;
  • system + prompt and messages modes;
  • text versus structured output; and
  • provider and model-specific adapt behavior.

Tool Model Output

Prompt tools may map raw application results to a provider-neutral model-facing value with toModelOutput. See the Tools reference for the exact shape and safety order.

.resolve(options)

.resolve() returns SDK-agnostic prepared data:

const resolved = await support.resolve({
  input: { userId: "user_123", question: "How do I configure SSO?" },
  provider: "openai",
  modelId: "gpt-4o",
});

resolved.system;
resolved.systemBlocks;
resolved.prompt;
resolved.messages;
resolved.tools;
resolved.constraints;
resolved.guardrails;
resolved.metadata;
resolved.settings;

It validates input and runs composition but does not call a model.

preview(target, options)

preview() observes whole-request planning without running provider calls, Tools, preparation callbacks, or artifact publication:

import { preview } from "@use-crux/core";

const result = await preview(support, {
  input: { userId: "user_123", question: "How do I configure SSO?" },
  model,
  inputBudget: { max: 4000 },
});

result.status;
result.inputTokens;
result.adaptations;
result.diagnostics;

Use it to understand whether a request fits and which authorized representations are ready or still require execution-time preparation. For complete evidence about an executed request, inspect its request receipt.

compilePrompt(config, { ports? })

compilePrompt() validates and compiles a Prompt config once, merges input schemas, detects conflicts, and binds resolver ports. Each resolve() call returns SDK-ready args and a free inspection view from the same pass.

import { compilePrompt, createResolverFakes } from "@use-crux/core";

const fakes = createResolverFakes();
const compiled = compilePrompt(config, { ports: fakes.ports });

const pass = await compiled.resolve({ input });
const resolved = pass.args;
const inspection = pass.inspect();

Ports are observability, skills, cache, clock, tokenizer, policy, diagnostics, and instrumentation. Omitted ports use production runtime adapters. createResolverFakes() provides a complete deterministic set for tests. Individual fakes such as recordingObservability, inMemoryContextCache, fixedClock, staticTokenizer, collectingDiagnostics, and recordingInstrumentation can replace one port.

The tokenizer port owns every reported token count. compiled.inspect() runs quietly; pass.inspect() never reruns the pipeline. compilePrompt() returns PromptResolutionPipeline; CompiledPrompt remains a deprecated alias. PromptResolution is exported from the Core package, while Resolution remains as a deprecated compatibility alias.

Adapter and primitive authors can use the exported lowered contributor contracts, including LoweredContributor, Contribution, GateResult, and MergedResolution. Application code normally does not need them.

createPrompts(tree)

Organizes Prompts into a deeply frozen, fully inferred tree:

const prompts = createPrompts({
  editor: {
    rewrite,
    classify,
  },
  support: {
    answerSupport,
  },
});

prompts.editor.rewrite;
prompts.support.answerSupport;
prompts._all;

_all is a non-enumerable flat list used by registries and Eval runners.

On this page