# dspy_rs::adapter
Source: https://dsrs.herumbshandilya.com/docs/api/adapter
Prompt formatting and LM response parsing.
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
Prompt formatting and LM response parsing.
## Re-exports
| Item | Description |
| --------- | --------------- |
| `chat::*` | Glob re-export. |
## Modules
| Item | Description |
| ------------------------------------------------------------------------ | ----------- |
| [`chat`](https://docs.rs/dspy-rs/latest/dspy_rs/adapter/chat/index.html) | |
## `adapter::chat`
### Structs
| Item | Description |
| -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| [`ChatAdapter`](https://docs.rs/dspy-rs/latest/dspy_rs/adapter/chat/struct.ChatAdapter.html) | Builds prompts and parses responses using the `[ ## field ## ]` delimiter protocol. |
# dspy_rs::augmentation
Source: https://dsrs.herumbshandilya.com/docs/api/augmentation
Public API of the augmentation module
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
## Structs
| Item | Description |
| ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [`Augmented`](https://docs.rs/dspy-rs/latest/dspy_rs/augmentation/struct.Augmented.html) | Type-level combinator: signature `S` with augmentation `A` applied to its output. |
## Traits
| Item | Description |
| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| [`Augmentation`](https://docs.rs/dspy-rs/latest/dspy_rs/augmentation/trait.Augmentation.html) | Adds fields to a signature's output that the LM actually produces. |
## Type aliases
| Item | Description |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| [`AugmentedOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/augmentation/type.AugmentedOutput.html) | Convenience alias: the output type of `Augmented`. |
# dspy_rs::core
Source: https://dsrs.herumbshandilya.com/docs/api/core
The foundational abstractions everything else is built on.
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
The foundational abstractions everything else is built on.
## Re-exports
| Item | Description |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| [`CallMetadata`](https://docs.rs/dspy-rs/latest/dspy_rs/core/predicted/struct.CallMetadata.html) | Re-export of `predicted::CallMetadata`. |
| [`ConstraintResult`](https://docs.rs/dspy-rs/latest/dspy_rs/core/predicted/struct.ConstraintResult.html) | Re-export of `predicted::ConstraintResult`. |
| [`ConversionError`](https://docs.rs/dspy-rs/latest/dspy_rs/core/errors/enum.ConversionError.html) | Re-export of `errors::ConversionError`. |
| [`ErrorClass`](https://docs.rs/dspy-rs/latest/dspy_rs/core/errors/enum.ErrorClass.html) | Re-export of `errors::ErrorClass`. |
| [`FieldMeta`](https://docs.rs/dspy-rs/latest/dspy_rs/core/predicted/struct.FieldMeta.html) | Re-export of `predicted::FieldMeta`. |
| [`FieldMetadataSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/core/schema/struct.FieldMetadataSpec.html) | Re-export of `schema::FieldMetadataSpec`. |
| [`FieldPath`](https://docs.rs/dspy-rs/latest/dspy_rs/core/schema/struct.FieldPath.html) | Re-export of `schema::FieldPath`. |
| [`FieldSchema`](https://docs.rs/dspy-rs/latest/dspy_rs/core/schema/struct.FieldSchema.html) | Re-export of `schema::FieldSchema`. |
| [`InputRenderSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/core/schema/enum.InputRenderSpec.html) | Re-export of `schema::InputRenderSpec`. |
| [`JsonishError`](https://docs.rs/dspy-rs/latest/dspy_rs/core/errors/struct.JsonishError.html) | Re-export of `errors::JsonishError`. |
| `lm::*` | Glob re-export. |
| [`LmError`](https://docs.rs/dspy-rs/latest/dspy_rs/core/errors/enum.LmError.html) | Re-export of `errors::LmError`. |
| `module::*` | Glob re-export. |
| [`ModuleState`](https://docs.rs/dspy-rs/latest/dspy_rs/core/state/struct.ModuleState.html) | Re-export of `state::ModuleState`. |
| [`ParseError`](https://docs.rs/dspy-rs/latest/dspy_rs/core/errors/enum.ParseError.html) | Re-export of `errors::ParseError`. |
| [`Predicted`](https://docs.rs/dspy-rs/latest/dspy_rs/core/predicted/struct.Predicted.html) | Re-export of `predicted::Predicted`. |
| [`PredictError`](https://docs.rs/dspy-rs/latest/dspy_rs/core/errors/enum.PredictError.html) | Re-export of `errors::PredictError`. |
| [`PredictState`](https://docs.rs/dspy-rs/latest/dspy_rs/core/state/struct.PredictState.html) | Re-export of `state::PredictState`. |
| `settings::*` | Glob re-export. |
| `signature::*` | Glob re-export. |
| [`SignatureSchema`](https://docs.rs/dspy-rs/latest/dspy_rs/core/schema/struct.SignatureSchema.html) | Re-export of `schema::SignatureSchema`. |
| [`ToInput`](https://docs.rs/dspy-rs/latest/dspy_rs/core/example/trait.ToInput.html) | Re-export of `example::ToInput`. |
| [`ToOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/core/example/trait.ToOutput.html) | Re-export of `example::ToOutput`. |
## Modules
| Item | Description |
| ------------------------------------------------------------------------------- | ------------------------------------- |
| [`example`](https://docs.rs/dspy-rs/latest/dspy_rs/core/example/index.html) | How trainset rows connect to modules. |
| [`lm`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/index.html) | |
| [`module`](https://docs.rs/dspy-rs/latest/dspy_rs/core/module/index.html) | |
| [`settings`](https://docs.rs/dspy-rs/latest/dspy_rs/core/settings/index.html) | |
| [`signature`](https://docs.rs/dspy-rs/latest/dspy_rs/core/signature/index.html) | |
## `core::example`
How trainset rows connect to modules.
### Traits
| Item | Description |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| [`ToInput`](https://docs.rs/dspy-rs/latest/dspy_rs/core/example/trait.ToInput.html) | Projects a trainset row into a module's input type. |
| [`ToOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/core/example/trait.ToOutput.html) | Projects a trainset row into a signature's output type — the gold label. |
### Functions
| Item | Description |
| -------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| [`project`](https://docs.rs/dspy-rs/latest/dspy_rs/core/example/fn.project.html) | Field-name projection: serializes `row` and deserializes `U` out of it. |
## `core::lm`
### Re-exports
| Item | Description |
| -------------------- | --------------- |
| `chat::*` | Glob re-export. |
| `client_registry::*` | Glob re-export. |
| `usage::*` | Glob re-export. |
### Structs
| Item | Description |
| ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| [`LM`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/struct.LM.html) | The live half: an `LMConfig` plus the initialized provider client and response cache. Constructed via `LM::builder()` or `LM::from_config`. |
| [`LMConfig`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/struct.LMConfig.html) | The data half of an LM: every generation parameter, no live state. |
| [`LMConfigBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/struct.LMConfigBuilder.html) | Use builder syntax to set the inputs and finish with `__internal_build()`). |
| [`LMResponse`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/struct.LMResponse.html) | |
| [`ToolSet`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/struct.ToolSet.html) | Pre-fetched tool definitions plus name-indexed executors. |
### Enums
| Item | Description |
| --------------------------------------------------------------------------------------- | ----------- |
| [`ToolLoopMode`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/enum.ToolLoopMode.html) | |
## `core::lm::chat`
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------ | ----------- |
| [`Chat`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/chat/struct.Chat.html) | |
| [`Message`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/chat/struct.Message.html) | |
### Enums
| Item | Description |
| -------------------------------------------------------------------------------------------- | ----------- |
| [`ContentBlock`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/chat/enum.ContentBlock.html) | |
| [`Role`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/chat/enum.Role.html) | |
## `core::lm::client_registry`
### Structs
| Item | Description |
| ----------------------------------------------------------------------------------------------------------------------- | ----------- |
| [`TestCompletionModel`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/client_registry/struct.TestCompletionModel.html) | |
### Enums
| Item | Description |
| ----------------------------------------------------------------------------------------------- | ----------- |
| [`LMClient`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/client_registry/enum.LMClient.html) | |
### Traits
| Item | Description |
| -------------------------------------------------------------------------------------------------------------------- | ----------- |
| [`CompletionProvider`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/client_registry/trait.CompletionProvider.html) | |
## `core::lm::usage`
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------- | ----------- |
| [`LmUsage`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/usage/struct.LmUsage.html) | |
## `core::module`
### Traits
| Item | Description |
| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| [`Module`](https://docs.rs/dspy-rs/latest/dspy_rs/core/module/trait.Module.html) | Strategy-swapping interface for prompting modules. |
| [`PredictorInfo`](https://docs.rs/dspy-rs/latest/dspy_rs/core/module/trait.PredictorInfo.html) | What optimizers read from — and, at explicit boundaries, write to — a `Predict` leaf. |
| [`Predictors`](https://docs.rs/dspy-rs/latest/dspy_rs/core/module/trait.Predictors.html) | Explicit predictor-leaf discovery: a module *names* its optimizable `Predict` leaves. |
### Functions
| Item | Description |
| --------------------------------------------------------------------------------------- | ------------------------------------------ |
| [`forward_all`](https://docs.rs/dspy-rs/latest/dspy_rs/core/module/fn.forward_all.html) | Runs a module on many inputs concurrently. |
## `core::settings`
### Structs
| Item | Description |
| --------------------------------------------------------------------------------------- | ----------- |
| [`Settings`](https://docs.rs/dspy-rs/latest/dspy_rs/core/settings/struct.Settings.html) | |
### Functions
| Item | Description |
| ------------------------------------------------------------------------------------- | ----------- |
| [`configure`](https://docs.rs/dspy-rs/latest/dspy_rs/core/settings/fn.configure.html) | |
| [`get_lm`](https://docs.rs/dspy-rs/latest/dspy_rs/core/settings/fn.get_lm.html) | |
### Statics
| Item | Description |
| ----------------------------------------------------------------------------------------------------- | ----------- |
| [`GLOBAL_SETTINGS`](https://docs.rs/dspy-rs/latest/dspy_rs/core/settings/static.GLOBAL_SETTINGS.html) | |
## `core::signature`
### Structs
| Item | Description |
| ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| [`ConstraintSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/core/signature/struct.ConstraintSpec.html) | A compile-time constraint declared on a signature field via `#check(...)` or `#assert(...)`. |
### Enums
| Item | Description |
| -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| [`ConstraintKind`](https://docs.rs/dspy-rs/latest/dspy_rs/core/signature/enum.ConstraintKind.html) | Whether a constraint is a soft check (reported but not fatal) or a hard assert (fails the call). |
### Traits
| Item | Description |
| ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| [`Signature`](https://docs.rs/dspy-rs/latest/dspy_rs/core/signature/trait.Signature.html) | Declares the input/output fields and instruction for a prompting task. |
# dspy_rs::data
Source: https://dsrs.herumbshandilya.com/docs/api/data
Data loading.
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
Data loading.
## Re-exports
| Item | Description |
| --------------- | --------------- |
| `dataloader::*` | Glob re-export. |
| `utils::*` | Glob re-export. |
## Modules
| Item | Description |
| --------------------------------------------------------------------------------- | ----------- |
| [`dataloader`](https://docs.rs/dspy-rs/latest/dspy_rs/data/dataloader/index.html) | |
| [`utils`](https://docs.rs/dspy-rs/latest/dspy_rs/data/utils/index.html) | |
## `data::dataloader`
### Structs
| Item | Description |
| --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| [`DataLoader`](https://docs.rs/dspy-rs/latest/dspy_rs/data/dataloader/struct.DataLoader.html) | Typed dataset ingress for JSON/CSV/Parquet/HuggingFace sources. |
| [`RowRecord`](https://docs.rs/dspy-rs/latest/dspy_rs/data/dataloader/struct.RowRecord.html) | Raw parsed row passed to custom mapper closures in `load_*_with` APIs. |
| [`TypedLoadOptions`](https://docs.rs/dspy-rs/latest/dspy_rs/data/dataloader/struct.TypedLoadOptions.html) | Options for shape-driven typed loading. |
### Enums
| Item | Description |
| ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| [`DataLoadError`](https://docs.rs/dspy-rs/latest/dspy_rs/data/dataloader/enum.DataLoadError.html) | Row-aware errors produced by typed data loading. |
| [`UnknownFieldPolicy`](https://docs.rs/dspy-rs/latest/dspy_rs/data/dataloader/enum.UnknownFieldPolicy.html) | Controls how typed loaders handle source fields that are not part of the target row struct. |
## `data::utils`
### Functions
| Item | Description |
| ---------------------------------------------------------------------------- | ------------------------------------------------------- |
| [`is_url`](https://docs.rs/dspy-rs/latest/dspy_rs/data/utils/fn.is_url.html) | Returns `true` if the string looks like an HTTP(S) URL. |
# dspy_rs (crate root)
Source: https://dsrs.herumbshandilya.com/docs/api/dspy-rs
Everything importable directly from dspy_rs
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
The crate root re-exports the surface most programs use, so `use dspy_rs::{Predict, Signature, configure}` works without module paths. Items are listed here once with their home module linked; the module pages list everything else.
## Re-exports
| Item | Description |
| -------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| `adapter::chat::*` | Glob re-export. |
| `augmentation::*` | Glob re-export. |
| [`begin_span`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.begin_span.html) | Re-export of `trace::begin_span`. |
| [`Capability`](https://docs.rs/dspy-rs/latest/dsrs_tools/capability/struct.Capability.html) | Re-export of `dsrs_tools::Capability`. |
| [`capture_with_meta`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.capture_with_meta.html) | Re-export of `trace::capture_with_meta`. |
| [`capture`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/index.html) | Re-export of `trace::capture`. |
| [`capture`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.capture.html) | Re-export of `trace::capture`. |
| [`CodeModeTool`](https://docs.rs/dspy-rs/latest/dsrs_tools/code_mode/struct.CodeModeTool.html) | Re-export of `dsrs_tools::CodeModeTool`. |
| [`CompId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.CompId.html) | Re-export of `trace::CompId`. |
| [`Constraint`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/struct.Constraint.html) | Re-export of `typesys::Constraint`. |
| [`ConstraintLevel`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/type.ConstraintLevel.html) | Re-export of `typesys::ConstraintLevel`. |
| `core::*` | Glob re-export. |
| `data::dataloader::*` | Glob re-export. |
| `data::utils::*` | Glob re-export. |
| `dsrs_macros::*` | Glob re-export. |
| [`Eval`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Eval.html) | Re-export of `trace::Eval`. |
| `evaluate::*` | Glob re-export. |
| [`Facet`](https://docs.rs/dspy-rs/latest/facet_core/trait.Facet.html) | Re-export of `facet::Facet`. |
| [`Facet`](https://docs.rs/dspy-rs/latest/facet_macros/derive.Facet.html) | Re-export of `facet::Facet`. |
| [`FieldType`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/enum.FieldType.html) | Re-export of `typesys::FieldType`. |
| [`Flag`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/coerce/enum.Flag.html) | Re-export of `typesys::Flag`. |
| [`is_capturing`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.is_capturing.html) | Re-export of `trace::is_capturing`. |
| [`is_replaying`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/fn.is_replaying.html) | Re-export of `trace::is_replaying`. |
| [`JsonMap`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/type.JsonMap.html) | Re-export of `trace::JsonMap`. |
| [`ModelEntry`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.ModelEntry.html) | Re-export of `trace::ModelEntry`. |
| [`ModelId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.ModelId.html) | Re-export of `trace::ModelId`. |
| `modules::*` | Glob re-export. |
| `optimizer::*` | Glob re-export. |
| [`OutputSchema`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.OutputSchema.html) | Re-export of `typesys::OutputSchema`. |
| `predictors::*` | Glob re-export. |
| [`PrefixEntry`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.PrefixEntry.html) | Re-export of `trace::PrefixEntry`. |
| [`PrefixId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.PrefixId.html) | Re-export of `trace::PrefixId`. |
| [`replay`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/index.html) | Re-export of `trace::replay`. |
| [`replay`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/fn.replay.html) | Re-export of `trace::replay`. |
| [`ReplayError`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/enum.ReplayError.html) | Re-export of `trace::ReplayError`. |
| [`ReplayMode`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/enum.ReplayMode.html) | Re-export of `trace::ReplayMode`. |
| [`ReplayReport`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/struct.ReplayReport.html) | Re-export of `trace::ReplayReport`. |
| [`RUN_JS_TOOL_NAME`](https://docs.rs/dspy-rs/latest/dsrs_tools/code_mode/constant.RUN_JS_TOOL_NAME.html) | Re-export of `dsrs_tools::RUN_JS_TOOL_NAME`. |
| [`SandboxConfig`](https://docs.rs/dspy-rs/latest/dsrs_tools/quickjs/struct.SandboxConfig.html) | Re-export of `dsrs_tools::SandboxConfig`. |
| [`Schema`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/trait.Schema.html) | Re-export of `typesys::Schema`. |
| [`Shape`](https://docs.rs/dspy-rs/latest/facet_core/types/shape/struct.Shape.html) | Re-export of `facet::Shape`. |
| [`Span`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Span.html) | Re-export of `trace::Span`. |
| [`SpanError`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.SpanError.html) | Re-export of `trace::SpanError`. |
| [`SpanErrorKind`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/enum.SpanErrorKind.html) | Re-export of `trace::SpanErrorKind`. |
| [`SpanEvent`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/enum.SpanEvent.html) | Re-export of `trace::SpanEvent`. |
| [`SpanGuard`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/struct.SpanGuard.html) | Re-export of `trace::SpanGuard`. |
| [`SpanId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.SpanId.html) | Re-export of `trace::SpanId`. |
| [`SpanOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/struct.SpanOutcome.html) | Re-export of `trace::SpanOutcome`. |
| [`SpanRequest`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/struct.SpanRequest.html) | Re-export of `trace::SpanRequest`. |
| [`Trace`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Trace.html) | Re-export of `trace::Trace`. |
| [`TraceMeta`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.TraceMeta.html) | Re-export of `trace::TraceMeta`. |
| [`TraceOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.TraceOutcome.html) | Re-export of `trace::TraceOutcome`. |
| `utils::*` | Glob re-export. |
## Macros
| Item | Description |
| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| [`predictors`](https://docs.rs/dspy-rs/latest/dspy_rs/macro.predictors.html) | Implements `Predictors` for a module struct from a list of predictor fields, using each field's identifier as its leaf name. |
## Modules
| Module | Description |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [`adapter`](/docs/api/adapter) | Prompt formatting and LM response parsing. |
| [`augmentation`](/docs/api/augmentation) | |
| [`core`](/docs/api/core) | The foundational abstractions everything else is built on. |
| [`data`](/docs/api/data) | Data loading. |
| [`evaluate`](/docs/api/evaluate) | Evaluation and metrics for measuring module performance. |
| [`fx`](/docs/api/fx) | Functional DSRs (experimental): harnesses as plain async functions. |
| [`ir`](/docs/api/ir) | The intermediate representation (RFC 0002). |
| [`modules`](/docs/api/modules) | |
| [`optimizer`](/docs/api/optimizer) | Automatic prompt optimization. |
| [`predictors`](/docs/api/predictors) | |
| [`prelude`](/docs/api/prelude) | The curated core surface — the recommended import for DSRs programs. |
| [`trace`](/docs/api/trace) | Execution trace capture (RFC 0001). |
| [`typesys`](/docs/api/typesys) | In-house type system that replaces the vendored BAML stack (`bamltype`, `baml_types`, `internal_baml_jinja`, `jsonish`). |
| [`utils`](/docs/api/utils) | LM response caching. |
# dsrs_syntax
Source: https://dsrs.herumbshandilya.com/docs/api/dsrs-syntax
Shared syntax layer for the `.dsrs` text format (RFC 0002 §4).
Generated from rustdoc JSON at `dsrs-syntax v0.1.0` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
Shared syntax layer for the `.dsrs` text format (RFC 0002 §4).
## Re-exports
| Item | Description |
| --------------------------------------------------------------------------------- | -------------------------------- |
| [`check`](https://docs.rs/dsrs-syntax/latest/dsrs_syntax/structure/fn.check.html) | Re-export of `structure::check`. |
## Modules
| Item | Description |
| ---------------------------------------------------------------------- | ------------------------------------------------ |
| [`lex`](https://docs.rs/dsrs-syntax/latest/dsrs_syntax/lex/index.html) | Lexer for the `.dsrs` text format (RFC 0002 §4). |
## Structs
| Item | Description |
| ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| [`ParseError`](https://docs.rs/dsrs-syntax/latest/dsrs_syntax/struct.ParseError.html) | A parse failure with the source position and what was expected — designed to be actionable feedback for a model regenerating the program. |
## `dsrs_syntax::lex`
### Structs
| Item | Description |
| ------------------------------------------------------------------------------- | --------------------------------------------------------- |
| [`Lexed`](https://docs.rs/dsrs-syntax/latest/dsrs_syntax/lex/struct.Lexed.html) | One lexed token with its source position and byte extent. |
| [`Lexer`](https://docs.rs/dsrs-syntax/latest/dsrs_syntax/lex/struct.Lexer.html) | |
| [`Span`](https://docs.rs/dsrs-syntax/latest/dsrs_syntax/lex/struct.Span.html) | A source position, 1-based. |
### Enums
| Item | Description |
| ------------------------------------------------------------------------- | ----------- |
| [`Tok`](https://docs.rs/dsrs-syntax/latest/dsrs_syntax/lex/enum.Tok.html) | |
# dsrs_tools
Source: https://dsrs.herumbshandilya.com/docs/api/dsrs-tools
# dsrs-tools: sandboxed tool execution for DSRs
Generated from rustdoc JSON at `dsrs-tools v0.1.0` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
# dsrs-tools: sandboxed tool execution for DSRs
## Re-exports
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| [`CacheStats`](https://docs.rs/dsrs-tools/latest/dsrs_tools/quickjs/struct.CacheStats.html) | Re-export of `quickjs::CacheStats`. |
| [`Capability`](https://docs.rs/dsrs-tools/latest/dsrs_tools/capability/struct.Capability.html) | Re-export of `capability::Capability`. |
| [`CapabilityHandler`](https://docs.rs/dsrs-tools/latest/dsrs_tools/capability/type.CapabilityHandler.html) | Re-export of `capability::CapabilityHandler`. |
| [`code_mode_description`](https://docs.rs/dsrs-tools/latest/dsrs_tools/code_mode/fn.code_mode_description.html) | Re-export of `code_mode::code_mode_description`. |
| [`CodeModeTool`](https://docs.rs/dsrs-tools/latest/dsrs_tools/code_mode/struct.CodeModeTool.html) | Re-export of `code_mode::CodeModeTool`. |
| [`ExecError`](https://docs.rs/dsrs-tools/latest/dsrs_tools/error/enum.ExecError.html) | Re-export of `error::ExecError`. |
| [`Executor`](https://docs.rs/dsrs-tools/latest/dsrs_tools/executor/trait.Executor.html) | Re-export of `executor::Executor`. |
| [`js_identifier`](https://docs.rs/dsrs-tools/latest/dsrs_tools/capability/fn.js_identifier.html) | Re-export of `capability::js_identifier`. |
| [`QuickJsExecutor`](https://docs.rs/dsrs-tools/latest/dsrs_tools/quickjs/struct.QuickJsExecutor.html) | Re-export of `quickjs::QuickJsExecutor`. |
| [`QuickJsExecutorBuilder`](https://docs.rs/dsrs-tools/latest/dsrs_tools/quickjs/struct.QuickJsExecutorBuilder.html) | Re-export of `quickjs::QuickJsExecutorBuilder`. |
| [`RegisteredTool`](https://docs.rs/dsrs-tools/latest/dsrs_tools/executor/struct.RegisteredTool.html) | Re-export of `executor::RegisteredTool`. |
| [`RegisterError`](https://docs.rs/dsrs-tools/latest/dsrs_tools/error/enum.RegisterError.html) | Re-export of `error::RegisterError`. |
| [`RigToolError`](https://docs.rs/dsrs-tools/latest/rig/tool/enum.ToolError.html) | Re-export of the rig tool traits that sandbox tools plug into, so downstream users don't need a direct (version-matched) rig dependency. |
| [`run_js_parameters`](https://docs.rs/dsrs-tools/latest/dsrs_tools/code_mode/fn.run_js_parameters.html) | Re-export of `code_mode::run_js_parameters`. |
| [`RUN_JS_TOOL_NAME`](https://docs.rs/dsrs-tools/latest/dsrs_tools/code_mode/constant.RUN_JS_TOOL_NAME.html) | Re-export of `code_mode::RUN_JS_TOOL_NAME`. |
| [`run_script`](https://docs.rs/dsrs-tools/latest/dsrs_tools/quickjs/fn.run_script.html) | Re-export of `quickjs::run_script`. |
| [`SandboxConfig`](https://docs.rs/dsrs-tools/latest/dsrs_tools/quickjs/struct.SandboxConfig.html) | Re-export of `quickjs::SandboxConfig`. |
| [`SandboxTool`](https://docs.rs/dsrs-tools/latest/dsrs_tools/rig_tool/struct.SandboxTool.html) | Re-export of `rig_tool::SandboxTool`. |
| [`ToolApi`](https://docs.rs/dsrs-tools/latest/dsrs_tools/code_mode/struct.ToolApi.html) | Re-export of `code_mode::ToolApi`. |
| [`ToolDyn`](https://docs.rs/dsrs-tools/latest/rig/tool/trait.ToolDyn.html) | Re-export of the rig tool traits that sandbox tools plug into, so downstream users don't need a direct (version-matched) rig dependency. |
| [`ToolInvocation`](https://docs.rs/dsrs-tools/latest/dsrs_tools/executor/struct.ToolInvocation.html) | Re-export of `executor::ToolInvocation`. |
| [`ToolSource`](https://docs.rs/dsrs-tools/latest/dsrs_tools/source/struct.ToolSource.html) | Re-export of `source::ToolSource`. |
# dspy_rs::evaluate
Source: https://dsrs.herumbshandilya.com/docs/api/evaluate
Evaluation and metrics for measuring module performance.
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
Evaluation and metrics for measuring module performance.
## Re-exports
| Item | Description |
| -------------- | --------------- |
| `evaluator::*` | Glob re-export. |
## Modules
| Item | Description |
| ----------------------------------------------------------------------------------- | ----------- |
| [`evaluator`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/index.html) | |
## `evaluate::evaluator`
### Re-exports
| Item | Description |
| ---------------------------------------------------------------------------- | ---------------------------------- |
| [`Eval`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Eval.html) | Re-export of `crate::trace::Eval`. |
### Traits
| Item | Description |
| ------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| [`TypedMetric`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/trait.TypedMetric.html) | How you tell the optimizer what "good" means. |
### Functions
| Item | Description |
| -------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| [`average_score`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/fn.average_score.html) | Arithmetic mean of scores from a slice of `Eval`s. |
| [`evaluate_trainset_with_concurrency`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/fn.evaluate_trainset_with_concurrency.html) | `evaluate_trainset` with an explicit concurrency level. |
| [`evaluate_trainset`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/fn.evaluate_trainset.html) | Runs a module on every example in a trainset and scores each with a metric. |
### Type aliases
| Item | Description |
| ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| [`Rollout`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/type.Rollout.html) | One evaluated rollout: the metric result plus the execution trace that produced it (with `Trace::outcome` filled in). |
### Constants
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------- |
| [`DEFAULT_EVAL_CONCURRENCY`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/constant.DEFAULT_EVAL_CONCURRENCY.html) | Default number of examples evaluated concurrently by `evaluate_trainset`. |
# dspy_rs::fx
Source: https://dsrs.herumbshandilya.com/docs/api/fx
Functional DSRs (experimental): harnesses as plain async functions.
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
Functional DSRs (experimental): harnesses as plain async functions.
## Re-exports
| Item | Description |
| --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`with_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/bridge/fn.with_overlay.html) | Runs a future with an `ir::Overlay` as the ambient candidate — the overlay is unbound against the program into `Params` and scoped exactly like `with_params`. See `ir::bridge`. |
## Structs
| Item | Description |
| ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| [`FnModule`](https://docs.rs/dspy-rs/latest/dspy_rs/fx/struct.FnModule.html) | Adapts a plain async function into a `Module`, so functional harnesses plug into `evaluate_trainset`, metrics, and every other module consumer. |
| [`Params`](https://docs.rs/dspy-rs/latest/dspy_rs/fx/struct.Params.html) | The optimizable state of a functional harness: named `PredictState`s — instructions and demos keyed by the names passed to `predict`. |
## Functions
| Item | Description |
| ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
| [`module`](https://docs.rs/dspy-rs/latest/dspy_rs/fx/fn.module.html) | Wraps an async function as a `Module`. See `FnModule`. |
| [`predict`](https://docs.rs/dspy-rs/latest/dspy_rs/fx/fn.predict.html) | The atomic LM call of functional DSRs: one signature, one named parameter slot, one prediction. |
| [`with_params`](https://docs.rs/dspy-rs/latest/dspy_rs/fx/fn.with_params.html) | Runs a future with `params` as the ambient parameter set for every `predict` call inside it. |
# API Reference
Source: https://dsrs.herumbshandilya.com/docs/api/index
Auto-generated index of every public item in the DSRs crates, linked to full rustdoc
This tab is an auto-generated index of the public API: every public struct, enum, trait, function, macro, and re-export across the DSRs crates, with its doc summary. It is produced from rustdoc JSON, the compiler's own view of the code, so it cannot drift from the source.
Every item links to its page on docs.rs, which carries the full signatures, methods, trait implementations, and long-form documentation:
The main crate: signatures, predictors, modules, IR, traces, optimizers
Sandboxed tool execution and Code Mode
The proc-macro crate behind the derive and attribute surface
The shared .dsrs lexer and structural grammar both frontends read from
For explanations and usage, the [component pages](/docs/components/signatures) are the right place; this tab answers "what exists and where does it live."
## Regenerating
The pages are rebuilt from the working tree, not fetched from a registry, so they track your branch. From the repository root:
```bash theme={null}
RUSTC_BOOTSTRAP=1 cargo rustdoc -p dspy-rs --lib --all-features -- -Z unstable-options --output-format json
RUSTC_BOOTSTRAP=1 cargo rustdoc -p dsrs-tools --lib -- -Z unstable-options --output-format json
RUSTC_BOOTSTRAP=1 cargo rustdoc -p dsrs_macros --lib -- -Z unstable-options --output-format json
RUSTC_BOOTSTRAP=1 cargo rustdoc -p dsrs-syntax --lib -- -Z unstable-options --output-format json
python3 docs/scripts/gen_api.py
```
Each generated page carries the crate version and commit it was built from. Run the five commands after any public-API change; CI can run them and fail on a dirty diff to keep this tab honest.
# dspy_rs::ir
Source: https://dsrs.herumbshandilya.com/docs/api/ir
The intermediate representation (RFC 0002).
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
The intermediate representation (RFC 0002).
## Re-exports
| Item | Description |
| ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
| [`agent`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.agent.html) | Re-export of `builder::agent`. |
| [`AgentLoopNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.AgentLoopNode.html) | Re-export of `graph::AgentLoopNode`. |
| [`AgentStepOpts`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/struct.AgentStepOpts.html) | Re-export of `step::AgentStepOpts`. |
| [`ApplyError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.ApplyError.html) | Re-export of `edit::ApplyError`. |
| [`AsNodeName`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/trait.AsNodeName.html) | Re-export of `builder::AsNodeName`. |
| [`BakeError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.BakeError.html) | Re-export of `graph::BakeError`. |
| [`Binding`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Binding.html) | Re-export of `graph::Binding`. |
| [`Budget`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.Budget.html) | Re-export of `interp::Budget`. |
| [`BudgetMeter`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.BudgetMeter.html) | Re-export of `interp::BudgetMeter`. |
| [`BudgetPolicy`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.BudgetPolicy.html) | Re-export of `graph::BudgetPolicy`. |
| [`build_module_program`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/fn.build_module_program.html) | Re-export of `module_build::build_module_program`. |
| [`BuildError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/enum.BuildError.html) | Re-export of `builder::BuildError`. |
| [`CapSet`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.CapSet.html) | Re-export of `graph::CapSet`. |
| [`carried`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.carried.html) | Re-export of `builder::carried`. |
| [`ClassDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.ClassDef.html) | Re-export of `crate::typesys::ClassDef`. |
| [`code_hash`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/fn.code_hash.html) | Re-export of `params::code_hash`. |
| [`CodeK`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.CodeK.html) | Re-export of `params::CodeK`. |
| [`CodeLang`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.CodeLang.html) | Re-export of `params::CodeLang`. |
| [`ConstraintDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.ConstraintDef.html) | Re-export of `sig::ConstraintDef`. |
| [`ContextK`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ContextK.html) | Re-export of `params::ContextK`. |
| [`ContextPolicy`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.ContextPolicy.html) | Re-export of `params::ContextPolicy`. |
| [`ConversationTurn`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/enum.ConversationTurn.html) | Re-export of `interp::ConversationTurn`. |
| [`cot`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.cot.html) | Re-export of `builder::cot`. |
| [`current_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/bridge/fn.current_overlay.html) | Re-export of `bridge::current_overlay`. |
| [`default_lm`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/fn.default_lm.html) | Re-export of `module_build::default_lm`. |
| [`DemoRow`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.DemoRow.html) | Re-export of `params::DemoRow`. |
| [`Demos`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.Demos.html) | Re-export of `params::Demos`. |
| [`DsrsFileError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/text/enum.DsrsFileError.html) | Re-export of `text::DsrsFileError`. |
| [`Edit`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.Edit.html) | Re-export of `edit::Edit`. |
| [`EditError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.EditError.html) | Re-export of `edit::EditError`. |
| [`EditKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.EditKind.html) | Re-export of `edit::EditKind`. |
| [`EnumDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.EnumDef.html) | Re-export of `crate::typesys::EnumDef`. |
| [`EnumValueDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.EnumValueDef.html) | Re-export of `crate::typesys::EnumValueDef`. |
| [`Exhausted`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.Exhausted.html) | Re-export of `interp::Exhausted`. |
| [`extern_hole`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.extern_hole.html) | Re-export of `builder::extern_hole`. |
| [`FieldDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.FieldDef.html) | Re-export of `sig::FieldDef`. |
| [`FieldType`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/enum.FieldType.html) | Re-export of `crate::typesys::FieldType`. |
| [`fork`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.fork.html) | Re-export of `builder::fork`. |
| [`ForkJoinNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ForkJoinNode.html) | Re-export of `graph::ForkJoinNode`. |
| [`hole`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.hole.html) | Re-export of `builder::hole`. |
| [`HoleImpl`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.HoleImpl.html) | Re-export of `graph::HoleImpl`. |
| [`HoleNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.HoleNode.html) | Re-export of `graph::HoleNode`. |
| [`HoleReport`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/struct.HoleReport.html) | Re-export of `step::HoleReport`. |
| [`HostHoleFn`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/type.HostHoleFn.html) | Re-export of `interp::HostHoleFn`. |
| [`input_schema_of`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/fn.input_schema_of.html) | Re-export of `interp::input_schema_of`. |
| [`input`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.input.html) | Re-export of `builder::input`. |
| [`Instruction`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.Instruction.html) | Re-export of `params::Instruction`. |
| [`Interner`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Interner.html) | Re-export of `graph::Interner`. |
| [`Interpreter`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.Interpreter.html) | Re-export of `interp::Interpreter`. |
| [`KindTag`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/trait.KindTag.html) | Re-export of `params::KindTag`. |
| [`LeafOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.LeafOutcome.html) | Re-export of `interp::LeafOutcome`. |
| [`Lineage`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Lineage.html) | Re-export of `graph::Lineage`. |
| [`lit`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.lit.html) | Re-export of `builder::lit`. |
| [`LoadError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/enum.LoadError.html) | Re-export of `interp::LoadError`. |
| [`loop_`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.loop_.html) | Re-export of `builder::loop_`. |
| [`LoopNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.LoopNode.html) | Re-export of `graph::LoopNode`. |
| [`migrate_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/fn.migrate_overlay.html) | Re-export of `edit::migrate_overlay`. |
| [`ModelDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ModelDef.html) | Re-export of `graph::ModelDef`. |
| [`ModelId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ModelId.html) | Re-export of `graph::ModelId`. |
| [`ModelRefK`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ModelRefK.html) | Re-export of `params::ModelRefK`. |
| [`ModuleBuildError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/enum.ModuleBuildError.html) | Re-export of `module_build::ModuleBuildError`. |
| [`ModuleSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/struct.ModuleSpec.html) | Re-export of `module_build::ModuleSpec`. |
| [`ModuleStep`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/struct.ModuleStep.html) | Re-export of `module_build::ModuleStep`. |
| [`ModuleStepKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/enum.ModuleStepKind.html) | Re-export of `module_build::ModuleStepKind`. |
| [`Node`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.Node.html) | Re-export of `graph::Node`. |
| [`NodeBudget`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.NodeBudget.html) | Re-export of `graph::NodeBudget`. |
| [`NodeId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.NodeId.html) | Re-export of `graph::NodeId`. |
| [`NodeSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/struct.NodeSpec.html) | Re-export of `builder::NodeSpec`. |
| [`out`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.out.html) | Re-export of `builder::out`. |
| [`Overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.Overlay.html) | Re-export of `params::Overlay`. |
| [`OverlayError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.OverlayError.html) | Re-export of `params::OverlayError`. |
| [`ParamId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.ParamId.html) | Re-export of `params::ParamId`. |
| [`ParamKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ParamKind.html) | Re-export of `params::ParamKind`. |
| [`ParamOwner`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ParamOwner.html) | Re-export of `params::ParamOwner`. |
| [`ParamSlot`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.ParamSlot.html) | Re-export of `params::ParamSlot`. |
| [`ParamValue`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ParamValue.html) | Re-export of `params::ParamValue`. |
| [`ParseError`](https://docs.rs/dspy-rs/latest/dsrs_syntax/struct.ParseError.html) | Re-export of `text::ParseError`. |
| [`Port`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/enum.Port.html) | Re-export of `builder::Port`. |
| [`PortRef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.PortRef.html) | Re-export of `graph::PortRef`. |
| [`PortSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/enum.PortSpec.html) | Re-export of `module_build::PortSpec`. |
| [`predict`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.predict.html) | Re-export of `builder::predict`. |
| [`PredictNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.PredictNode.html) | Re-export of `graph::PredictNode`. |
| [`Program`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Program.html) | Re-export of `graph::Program`. |
| [`ProgramBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/struct.ProgramBuilder.html) | Re-export of `builder::ProgramBuilder`. |
| [`ProgramMeta`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ProgramMeta.html) | Re-export of `graph::ProgramMeta`. |
| [`refine`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.refine.html) | Re-export of `builder::refine`. |
| [`RefineNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.RefineNode.html) | Re-export of `graph::RefineNode`. |
| [`RenderSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/enum.RenderSpec.html) | Re-export of `sig::RenderSpec`. |
| [`retry`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.retry.html) | Re-export of `builder::retry`. |
| [`RetryNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.RetryNode.html) | Re-export of `graph::RetryNode`. |
| [`route`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.route.html) | Re-export of `builder::route`. |
| [`RouteNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.RouteNode.html) | Re-export of `graph::RouteNode`. |
| [`RunError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/enum.RunError.html) | Re-export of `interp::RunError`. |
| [`RunOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.RunOutput.html) | Re-export of `interp::RunOutput`. |
| [`RuntimeEnv`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.RuntimeEnv.html) | Re-export of `interp::RuntimeEnv`. |
| [`seq`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.seq.html) | Re-export of `builder::seq`. |
| [`SeqNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.SeqNode.html) | Re-export of `graph::SeqNode`. |
| [`SigError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/enum.SigError.html) | Re-export of `sig::SigError`. |
| [`SigId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.SigId.html) | Re-export of `graph::SigId`. |
| [`SigMismatch`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.SigMismatch.html) | Re-export of `sig::SigMismatch`. |
| [`SignatureBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.SignatureBuilder.html) | Re-export of `sig::SignatureBuilder`. |
| [`SignatureDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.SignatureDef.html) | Re-export of `sig::SignatureDef`. |
| [`Slot`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.Slot.html) | Re-export of `params::Slot`. |
| [`StepDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/struct.StepDef.html) | Re-export of `step::StepDef`. |
| [`StepKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/enum.StepKind.html) | Re-export of `step::StepKind`. |
| [`StopSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.StopSpec.html) | Re-export of `graph::StopSpec`. |
| [`SwapTarget`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.SwapTarget.html) | Re-export of `edit::SwapTarget`. |
| [`Sym`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Sym.html) | Re-export of `graph::Sym`. |
| [`ToolDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ToolDef.html) | Re-export of `graph::ToolDef`. |
| [`ToolDesc`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ToolDesc.html) | Re-export of `params::ToolDesc`. |
| [`ToolId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ToolId.html) | Re-export of `graph::ToolId`. |
| [`ToolKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.ToolKind.html) | Re-export of `graph::ToolKind`. |
| [`ToolSetK`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ToolSetK.html) | Re-export of `params::ToolSetK`. |
| [`ToolStepDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/struct.ToolStepDef.html) | Re-export of `step::ToolStepDef`. |
| [`ToolSuspension`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.ToolSuspension.html) | Re-export of `interp::ToolSuspension`. |
| [`TypeTable`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.TypeTable.html) | Re-export of `crate::typesys::TypeTable`. |
| [`unbound_model_config`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/fn.unbound_model_config.html) | Re-export of `module_build::unbound_model_config`. |
| [`ValidateError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/validate/enum.ValidateError.html) | Re-export of `validate::ValidateError`. |
| [`with_ambient_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/bridge/fn.with_ambient_overlay.html) | Re-export of `bridge::with_ambient_overlay`. |
| [`with_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/bridge/fn.with_overlay.html) | Re-export of `bridge::with_overlay`. |
## Modules
| Item | Description |
| ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`bridge`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/bridge/index.html) | The fx/ModuleState ↔ `Overlay` bridge (RFC 0002 §2.4 migration contract). |
| [`builder`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/index.html) | The Rust builder frontend (RFC 0002 §4.3–4.4): constructs the same runtime `Program` value the text parser will. |
| [`edit`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/index.html) | The graph-edit calculus: the *structural* mutation half of the IR. |
| [`graph`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/index.html) | The IR graph core (RFC 0002 §2): entity ids, the `Interner`, the closed `Node` enum, field-level `Binding`/`PortRef` dataflow, and `Program` — arenas over value-level signatures. |
| [`interp`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/index.html) | The IR interpreter (RFC 0002 §3): async evaluation of a loaded `Program`. |
| [`module_build`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/index.html) | RFC 0003 stage M-3 library support: the module "linker". |
| [`params`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/index.html) | Parameters (RFC 0002 §2.4): every mutable thing is a named, addressable slot; a candidate is an `Overlay` read through at render time, never a mutation. |
| [`sig`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/index.html) | Value-level signatures (RFC 0002 §1) — `SignatureDef` and friends. |
| [`step`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/index.html) | RFC 0003 stage M-2: step metadata. |
| [`text`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/text/index.html) | The `.dsrs` text format (RFC 0002 §4, stage IR-5). |
| [`validate`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/validate/index.html) | Load-time validation (RFC 0002 §2.3): builder `finish()`, the loader, and `Program::validate()` run the same code path. Nothing is checked lazily at call time. |
## `ir::sig`
Value-level signatures (RFC 0002 §1) — `SignatureDef` and friends.
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| [`ConstraintDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.ConstraintDef.html) | Owned runtime form of `ConstraintSpec` (which stays `&'static` for the derive). |
| [`FieldDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.FieldDef.html) | One input or output field of a `SignatureDef`. |
| [`SigMismatch`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.SigMismatch.html) | Structural mismatch reported by `SignatureDef::matches`. |
| [`SignatureBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.SignatureBuilder.html) | Builder for `SignatureDef`; validation happens at `finish`. |
| [`SignatureDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/struct.SignatureDef.html) | A signature as an owned value: what the derive macro knows at compile time, available at runtime with no `'static` requirement (RFC 0002 §1.1). |
### Enums
| Item | Description |
| ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`RenderSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/enum.RenderSpec.html) | Owned runtime form of `InputRenderSpec`. |
| [`SigError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/sig/enum.SigError.html) | Validation failure from `SignatureBuilder::finish`. What the derive macro rejects, this rejects — same closed subset in both lanes (RFC 0002 §1.3). |
## `ir::bridge`
The fx/ModuleState ↔ `Overlay` bridge (RFC 0002 §2.4 migration contract).
### Functions
| Item | Description |
| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`current_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/bridge/fn.current_overlay.html) | The ambient overlay, if a `with_ambient_overlay` scope is active on this task. Read by `#module`-generated executable fns immediately before `Interpreter::run`. |
| [`with_ambient_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/bridge/fn.with_ambient_overlay.html) | Runs `fut` with `overlay` as the ambient candidate for every `#module` fn called on this task — the interpreter-lane sibling of `fx::with_params`. |
| [`with_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/bridge/fn.with_overlay.html) | Runs `fut` with `overlay` (unbound against `program`) as the ambient `fx::Params` scope — the fx-lane equivalent of passing the overlay to `Interpreter::run`. |
## `ir::builder`
The Rust builder frontend (RFC 0002 §4.3–4.4): constructs the same runtime `Program` value the text parser will.
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`NodeSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/struct.NodeSpec.html) | An unregistered node: the builder-side mirror of `Node` with name-based ports and inline children. |
| [`ProgramBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/struct.ProgramBuilder.html) | Builds a `Program`. Declarations (caps, models, sigs, tools) accumulate; `main` lowers the node tree, materializes param slots, seals the hash, and validates. |
### Enums
| Item | Description |
| -------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| [`BuildError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/enum.BuildError.html) | |
| [`Port`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/enum.Port.html) | A name-based port, resolved to a `PortRef` at `main()`. |
### Traits
| Item | Description |
| --------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| [`AsNodeName`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/trait.AsNodeName.html) | Anything that names a node: a string, or a leaf/step spec. |
### Functions
| Item | Description |
| -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| [`agent`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.agent.html) | The LLM+tool loop. |
| [`carried`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.carried.html) | `^field` — the previous iteration's carried value (Loop bodies only). |
| [`cot`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.cot.html) | Chain-of-thought sugar: a Predict over `sig.augmented_with(reasoning)`. |
| [`extern_hole`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.extern_hole.html) | An extern (host-backed) typed hole (RFC 0003 §4): a native fn bound by leaf name from the runtime environment at load. |
| [`fork`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.fork.html) | Concurrent branches, joined all-success / fail-fast. |
| [`hole`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.hole.html) | A typed hole: sandboxed JS with a declared signature and capability set. |
| [`input`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.input.html) | `$.field` — the enclosing scope's input. |
| [`lit`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.lit.html) | A JSON literal port. |
| [`loop_`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.loop_.html) | Bounded loop. |
| [`out`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.out.html) | `node.field` — an earlier node's output. `node` accepts a name string or a leaf spec (anything `AsNodeName`). |
| [`predict`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.predict.html) | One LM call over `sig`. |
| [`refine`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.refine.html) | Judge-gated refinement of a child. |
| [`retry`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.retry.html) | Bounded retry of a child. |
| [`route`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.route.html) | Enum-discriminated branching. |
| [`seq`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/builder/fn.seq.html) | Sequential composition. |
## `ir::edit`
The graph-edit calculus: the *structural* mutation half of the IR.
### Enums
| Item | Description |
| ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`ApplyError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.ApplyError.html) | A locally-checkable application failure. |
| [`Edit`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.Edit.html) | One structural edit. Serde values: an optimizer's proposal is data, not code — it can be logged, replayed against the same parent, and diffed. |
| [`EditError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.EditError.html) | Why `Program::edited` refused. |
| [`EditKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.EditKind.html) | A lightweight, serializable descriptor of an edit kind admissible at a node — the menu `Program::legal_edits` returns, suitable for prompting an LLM proposer. |
| [`SwapTarget`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.SwapTarget.html) | Target kind of `Edit::SwapLeaf`. |
### Functions
| Item | Description |
| ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`migrate_overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/fn.migrate_overlay.html) | Carries tuned values across a structural edit: for every entry in `overlay` (minted against `parent`), re-mint it against `child` when the child has a slot at the same `ParamPath`... |
## `ir::graph`
The IR graph core (RFC 0002 §2): entity ids, the `Interner`, the closed `Node` enum, field-level `Binding`/`PortRef` dataflow, and `Program` — arenas over value-level signatures.
### Structs
| Item | Description |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`AgentLoopNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.AgentLoopNode.html) | The LLM+tool loop as the first-class unit. |
| [`Binding`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Binding.html) | One field-level wire: `dst` input field (or exported name) fed from `src`. |
| [`CapSet`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.CapSet.html) | Capability names: namespaced, colon-separated (`"net:search"`, `"fs:read"`). `BTreeSet`: set ops happen at load only, never on the hot path. |
| [`ForkJoinNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ForkJoinNode.html) | |
| [`HoleNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.HoleNode.html) | LACUNA-style typed hole: opaque-but-typed code. The optimizer sees a signature (and, when sandboxed, a Code gene); the type system sees a normal node. |
| [`Interner`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Interner.html) | Graph-side string interner. Signatures speak strings (`SignatureDef` is constructible with zero context); the *graph* speaks `Sym`s. |
| [`Lineage`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Lineage.html) | |
| [`LoopNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.LoopNode.html) | |
| [`ModelDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ModelDef.html) | `LMConfig` is already serde with `api_key` `#serde(skip)` — reused verbatim: model entries carry provider/URL/sampling only, never secrets. |
| [`ModelId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ModelId.html) | Model reference id. Distinct from the trace format's per-trace `trace::ModelId` — this one indexes `Program::models`. |
| [`NodeBudget`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.NodeBudget.html) | |
| [`NodeId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.NodeId.html) | |
| [`PredictNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.PredictNode.html) | One LM call. No tools. `cot` in the surface syntax lowers to a Predict over `sig.augmented_with(reasoning)`. |
| [`Program`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Program.html) | A loaded IR program: arenas + interner + capability ceiling. |
| [`ProgramMeta`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ProgramMeta.html) | |
| [`RefineNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.RefineNode.html) | |
| [`RetryNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.RetryNode.html) | |
| [`RouteNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.RouteNode.html) | |
| [`SeqNode`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.SeqNode.html) | |
| [`SigId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.SigId.html) | |
| [`StopSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.StopSpec.html) | |
| [`Sym`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Sym.html) | Interned string: node names, field references in bindings, tool names. |
| [`ToolDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ToolDef.html) | |
| [`ToolId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.ToolId.html) | |
### Enums
| Item | Description |
| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| [`BakeError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.BakeError.html) | Why `Program::bake` refused. |
| [`BudgetPolicy`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.BudgetPolicy.html) | |
| [`HoleImpl`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.HoleImpl.html) | How a hole is implemented (RFC 0003 §4.1) — mirrors `ToolKind`. |
| [`Node`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.Node.html) | The closed node vocabulary. `Predict` carries no tools — tool use is `AgentLoop`; `cot` is signature sugar, not a node kind. |
| [`PortRef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.PortRef.html) | |
| [`ToolKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/enum.ToolKind.html) | |
## `ir::interp`
The IR interpreter (RFC 0002 §3): async evaluation of a loaded `Program`.
### Structs
| Item | Description |
| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`Budget`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.Budget.html) | Run-level spend limits. `None` = unlimited. |
| [`BudgetMeter`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.BudgetMeter.html) | Check-before-call metering: calls and deadline are hard-gated pre-call; token budgets are soft (checked against accumulated usage, since usage is only known post-hoc). |
| [`Exhausted`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.Exhausted.html) | Budget reservation failure. |
| [`Interpreter`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.Interpreter.html) | A loaded, executable program: validated graph + bound models/tools + registered sandbox code. Cheap to share; run state never lives here. |
| [`LeafOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.LeafOutcome.html) | Parse/coercion metadata from one successful `Predict`-leaf evaluation, collected by `Interpreter::run_collecting` in execution order. |
| [`RunOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.RunOutput.html) | Program output plus per-leaf metadata, returned by `Interpreter::run_collecting`. |
| [`RuntimeEnv`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.RuntimeEnv.html) | What the host supplies at load: live models, host tool bindings, the sandbox, and the capability grants. |
| [`ToolSuspension`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.ToolSuspension.html) | A caller-managed agent turn suspended on pending tool calls (RFC 0004 §2). |
### Enums
| Item | Description |
| ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| [`ConversationTurn`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/enum.ConversationTurn.html) | One caller-driven conversation turn, returned by `Interpreter::run_conversation_caller_managed` and `Interpreter::resume_conversation`. |
| [`LoadError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/enum.LoadError.html) | |
| [`RunError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/enum.RunError.html) | |
### Functions
| Item | Description |
| --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| [`input_schema_of`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/fn.input_schema_of.html) | Projects a tool/hole signature's *input* side to a JSON Schema object — the declared interface is the schema the model sees. |
### Type aliases
| Item | Description |
| ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| [`HostHoleFn`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/type.HostHoleFn.html) | A native extern-hole implementation: resolved input map in, JSON value out (coerced against the hole's output signature by the interpreter). |
## `ir::module_build`
RFC 0003 stage M-3 library support: the module "linker".
### Structs
| Item | Description |
| --------------------------------------------------------------------------------------------- | ---------------------------------------- |
| [`ModuleSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/struct.ModuleSpec.html) | The parsed shape of a `#module` fn body. |
| [`ModuleStep`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/struct.ModuleStep.html) | |
### Enums
| Item | Description |
| ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
| [`ModuleBuildError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/enum.ModuleBuildError.html) | Why a `#module` body could not be linked into a program. |
| [`ModuleStepKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/enum.ModuleStepKind.html) | |
| [`PortSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/enum.PortSpec.html) | A macro-emitted port: name-based, resolved by the linker. |
### Functions
| Item | Description |
| ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`build_module_program`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/fn.build_module_program.html) | Links a `ModuleSpec` into a validated `Program`. Deterministic: the same spec produces the same canonical text and therefore the same program hash. |
| [`default_lm`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/fn.default_lm.html) | The globally-configured LM (`configure`), used by generated module code to bind the `default` model ref at load. |
| [`unbound_model_config`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/module_build/fn.unbound_model_config.html) | The placeholder config a module program declares for model ref `name`. Loading it unbound fails loudly; the real client arrives by name through `RuntimeEnv::bind_model`. |
## `ir::params`
Parameters (RFC 0002 §2.4): every mutable thing is a named, addressable slot; a candidate is an `Overlay` read through at render time, never a mutation.
### Structs
| Item | Description |
| --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| [`ContextPolicy`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.ContextPolicy.html) | The open-lane optimizable slot (vision §6.6). Minimal v1; additive later. |
| [`DemoRow`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.DemoRow.html) | One few-shot demonstration row: input and output field maps. |
| [`Overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.Overlay.html) | A candidate = dense data overlay over a fixed skeleton. Clone is a vec clone. |
| [`ParamId`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.ParamId.html) | |
| [`ParamSlot`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.ParamSlot.html) | One optimizable slot: canonical path, owner, kind, and the incumbent value. |
| [`Slot`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.Slot.html) | Typed slot handle: optimizer-side mutation mistakes are compile errors. |
### Enums
| Item | Description |
| ----------------------------------------------------------------------------------------- | ----------- |
| [`CodeK`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.CodeK.html) | |
| [`CodeLang`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.CodeLang.html) | |
| [`ContextK`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ContextK.html) | |
| [`Demos`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.Demos.html) | |
| [`Instruction`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.Instruction.html) | |
| [`ModelRefK`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ModelRefK.html) | |
| [`OverlayError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.OverlayError.html) | |
| [`ParamKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ParamKind.html) | |
| [`ParamOwner`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ParamOwner.html) | |
| [`ParamValue`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ParamValue.html) | |
| [`ToolDesc`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ToolDesc.html) | |
| [`ToolSetK`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/enum.ToolSetK.html) | |
### Traits
| Item | Description |
| -------------------------------------------------------------------------------- | ----------- |
| [`KindTag`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/trait.KindTag.html) | |
### Functions
| Item | Description |
| --------------------------------------------------------------------------------- | -------------------------------------------- |
| [`code_hash`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/fn.code_hash.html) | Stable content hash of a code gene's source. |
## `ir::step`
RFC 0003 stage M-2: step metadata.
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| [`AgentStepOpts`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/struct.AgentStepOpts.html) | `#agent(...)` attribute options, mirroring the `AgentLoopNode` surface. |
| [`HoleReport`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/struct.HoleReport.html) | One hole-ized expression in a `#module` body (RFC 0003 §6) — the opacity report entry. |
| [`StepDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/struct.StepDef.html) | One step declaration — what a `#predict`/`#cot`/`#agent` fn *is*, as data. |
| [`ToolStepDef`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/struct.ToolStepDef.html) | One `#tool` declaration: metadata plus the host implementation. |
### Enums
| Item | Description |
| ------------------------------------------------------------------------------- | ----------- |
| [`StepKind`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/step/enum.StepKind.html) | |
## `ir::text`
The `.dsrs` text format (RFC 0002 §4, stage IR-5).
### Re-exports
| Item | Description |
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| [`ParseError`](https://docs.rs/dspy-rs/latest/dsrs_syntax/struct.ParseError.html) | A parse failure with the source position and what was expected — designed to be actionable feedback for a model regenerating the program. |
### Enums
| Item | Description |
| ----------------------------------------------------------------------------------------- | -------------------------------------------------- |
| [`DsrsFileError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/text/enum.DsrsFileError.html) | Failure loading or saving a `.dsrs` artifact file. |
## `ir::validate`
Load-time validation (RFC 0002 §2.3): builder `finish()`, the loader, and `Program::validate()` run the same code path. Nothing is checked lazily at call time.
### Enums
| Item | Description |
| --------------------------------------------------------------------------------------------- | ----------- |
| [`ValidateError`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/validate/enum.ValidateError.html) | |
# dspy_rs::modules
Source: https://dsrs.herumbshandilya.com/docs/api/modules
Public API of the modules module
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
## Re-exports
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------ |
| [`ChainOfThought`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/type.ChainOfThought.html) | Re-export of `chain_of_thought::ChainOfThought`. |
| [`ChainOfThoughtOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/type.ChainOfThoughtOutput.html) | Re-export of `chain_of_thought::ChainOfThoughtOutput`. |
| [`Reasoning`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/struct.Reasoning.html) | Re-export of `chain_of_thought::Reasoning`. |
| [`WithReasoning`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/struct.WithReasoning.html) | Re-export of `chain_of_thought::WithReasoning`. |
## Modules
| Item | Description |
| ------------------------------------------------------------------------------------------------ | ----------- |
| [`chain_of_thought`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/index.html) | |
## `modules::chain_of_thought`
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
| [`Reasoning`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/struct.Reasoning.html) | Augmentation that prepends a `reasoning: String` field to a signature's output. |
| [`WithReasoning`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/struct.WithReasoning.html) | |
### Type aliases
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- |
| [`ChainOfThought`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/type.ChainOfThought.html) | Asks the LM to reason step-by-step before producing the answer. |
| [`ChainOfThoughtOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/type.ChainOfThoughtOutput.html) | Convenience alias for `ChainOfThought`'s output type. |
# dspy_rs::optimizer
Source: https://dsrs.herumbshandilya.com/docs/api/optimizer
Automatic prompt optimization.
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
Automatic prompt optimization.
## Re-exports
| Item | Description |
| ------------------------------------------------------------------------------------------------------ | -------------------------------------- |
| `bootstrap::*` | Glob re-export. |
| `copro::*` | Glob re-export. |
| `engine::*` | Glob re-export. |
| `gepa::*` | Glob re-export. |
| [`LeafInfo`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/target/struct.LeafInfo.html) | Re-export of `target::LeafInfo`. |
| `mipro::*` | Glob re-export. |
| [`OptimizeTarget`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/target/struct.OptimizeTarget.html) | Re-export of `target::OptimizeTarget`. |
| [`ProgramMetric`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/target/trait.ProgramMetric.html) | Re-export of `target::ProgramMetric`. |
| `simba::*` | Glob re-export. |
| `structural::*` | Glob re-export. |
## Modules
| Item | Description |
| -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| [`bootstrap`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/bootstrap/index.html) | BootstrapFewShot: the minimal end-to-end exercise of the optimizer contract (vision §5. |
| [`copro`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/copro/index.html) | |
| [`engine`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/index.html) | The shared evaluation engine (vision §5.4): every optimizer is a thin strategy over this core. |
| [`gepa`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/gepa/index.html) | |
| [`mipro`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/mipro/index.html) | |
| [`simba`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/simba/index.html) | SIMBA: Stochastic Introspective Mini-Batch Ascent (vision §4.3) — the cheap agentic default. |
| [`structural`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/structural/index.html) | Structural: LM-guided hill-climbing over the graph-edit calculus (RFC 0004 §6) — the sixth strategy over the shared `Engine`. |
| [`target`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/target/index.html) | What an optimizer optimizes: `OptimizeTarget`, the lane-erased pair of (thing under optimization, evaluation harness). |
## Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| [`OptimizerCommon`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/struct.OptimizerCommon.html) | The engine/RNG knobs shared by every optimizer builder: evaluation concurrency, budget caps, cache salt, and the sampling seed. |
## Enums
| Item | Description |
| ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| [`Report`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/enum.Report.html) | What an optimization run produced. Strategy-specific payloads for the optimizers that report more than "done". |
## Traits
| Item | Description |
| ------------------------------------------------------------------------------------ | ------------------------------------------- |
| [`Optimizer`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/trait.Optimizer.html) | A tuning strategy over the shared `Engine`. |
## `optimizer::bootstrap`
BootstrapFewShot: the minimal end-to-end exercise of the optimizer contract (vision §5.
### Structs
| Item | Description |
| --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| [`BootstrapFewShot`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/bootstrap/struct.BootstrapFewShot.html) | Few-shot demo bootstrapper — the simplest complete optimizer. |
| [`BootstrapFewShotBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/bootstrap/struct.BootstrapFewShotBuilder.html) | Use builder syntax to set the inputs and finish with `build()`). |
| [`BootstrapReport`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/bootstrap/struct.BootstrapReport.html) | What a `BootstrapFewShot` run did. |
## `optimizer::copro`
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| [`COPRO`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/copro/struct.COPRO.html) | Breadth-first instruction optimizer. |
| [`COPROBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/copro/struct.COPROBuilder.html) | Use builder syntax to set the inputs and finish with `build()`). |
## `optimizer::engine`
The shared evaluation engine (vision §5.4): every optimizer is a thin strategy over this core.
### Structs
| Item | Description |
| ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| [`Budget`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.Budget.html) | Hard caps on evaluation spend. `None` = unlimited. |
| [`Candidate`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.Candidate.html) | A candidate is *data*: name-keyed per-leaf overlays plus a stable content hash (`Candidate::stable_hash`). |
| [`CandidateEval`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.CandidateEval.html) | A candidate's results over one evaluation batch, in request order. |
| [`CandidateSlot`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.CandidateSlot.html) | One leaf's slice of a `Candidate`: which optimizable values to inject. |
| [`Engine`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.Engine.html) | The shared evaluation core (vision §5.4). |
| [`EngineConfig`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.EngineConfig.html) | Engine tuning knobs. |
| [`ParetoStatistics`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.ParetoStatistics.html) | Snapshot of the Pareto frontier at a point in the search. |
| [`ParetoView`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.ParetoView.html) | Dominance snapshot computed from a `ScoreMatrix`: which candidates win (or tie, within tolerance) on at least one example. |
| [`RolloutCache`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.RolloutCache.html) | In-memory rollout cache: `(baseline, candidate, example, salt)` → `Eval`. |
| [`RolloutOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.RolloutOutcome.html) | One evaluated (or cache-served) rollout. |
| [`ScoreMatrix`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.ScoreMatrix.html) | Per-instance score matrix: candidates × examples. |
| [`Spend`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.Spend.html) | What the engine has consumed so far. Reported to strategies. |
### Enums
| Item | Description |
| -------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| [`BatchEvalOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/enum.BatchEvalOutcome.html) | Result of `Engine::evaluate_many`. |
| [`EvalOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/enum.EvalOutcome.html) | Result of `Engine::evaluate`. |
| [`GateOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/enum.GateOutcome.html) | Result of `Engine::evaluate_gated`. |
## `optimizer::gepa`
### Structs
| Item | Description |
| ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| [`GEPA`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/gepa/struct.GEPA.html) | Genetic-Pareto instruction optimizer with feedback-driven evolution. |
| [`GEPABuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/gepa/struct.GEPABuilder.html) | Use builder syntax to set the inputs and finish with `build()`). |
| [`GEPACandidate`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/gepa/struct.GEPACandidate.html) | A single instruction candidate tracked through GEPA's evolutionary search. |
| [`GEPAResult`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/gepa/struct.GEPAResult.html) | Full report from a `GEPA` optimization run. |
| [`ReflectOnInstructionOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/gepa/struct.ReflectOnInstructionOutput.html) | |
## `optimizer::mipro`
### Structs
| Item | Description |
| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| [`MIPROv2`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/mipro/struct.MIPROv2.html) | Trace-guided instruction and demo optimizer. |
| [`MIPROv2Builder`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/mipro/struct.MIPROv2Builder.html) | Use builder syntax to set the inputs and finish with `build()`). |
| [`PromptingTips`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/mipro/struct.PromptingTips.html) | Library of general prompting best practices used to seed candidate generation. |
## `optimizer::simba`
SIMBA: Stochastic Introspective Mini-Batch Ascent (vision §4.3) — the cheap agentic default.
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| [`IntrospectRolloutsOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/simba/struct.IntrospectRolloutsOutput.html) | |
| [`SIMBA`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/simba/struct.SIMBA.html) | Minibatch introspective ascent — the cheap agentic default (vision §4.3). |
| [`SIMBABuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/simba/struct.SIMBABuilder.html) | Use builder syntax to set the inputs and finish with `build()`). |
| [`SimbaReport`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/simba/struct.SimbaReport.html) | What a `SIMBA` run did. |
| [`SimbaStep`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/simba/struct.SimbaStep.html) | What one SIMBA step did. |
### Enums
| Item | Description |
| ----------------------------------------------------------------------------------------- | ------------------------------------------- |
| [`SimbaMove`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/simba/enum.SimbaMove.html) | Which of SIMBA's two moves a step proposed. |
## `optimizer::structural`
Structural: LM-guided hill-climbing over the graph-edit calculus (RFC 0004 §6) — the sixth strategy over the shared `Engine`.
### Structs
| Item | Description |
| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| [`ChooseEditOutput`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/structural/struct.ChooseEditOutput.html) | |
| [`Structural`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/structural/struct.Structural.html) | Structural optimizer over the graph-edit calculus (RFC 0004 §6). |
| [`StructuralBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/structural/struct.StructuralBuilder.html) | Use builder syntax to set the inputs and finish with `build()`). |
| [`StructuralReport`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/structural/struct.StructuralReport.html) | What a `Structural` run did. The winner is returned, not installed: bake it (\`report.program.bake(\&report. |
| [`StructuralStep`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/structural/struct.StructuralStep.html) | What one Structural generation did. |
## `optimizer::target`
What an optimizer optimizes: `OptimizeTarget`, the lane-erased pair of (thing under optimization, evaluation harness).
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| [`LeafInfo`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/target/struct.LeafInfo.html) | The read surface strategies build candidates from: one optimizable leaf's name, current values, and field contract. |
| [`OptimizeTarget`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/target/struct.OptimizeTarget.html) | The thing an `Optimizer` optimizes: a module or a program, packaged with its example set and metric. See the module docs for the two lanes. |
### Traits
| Item | Description |
| --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`ProgramMetric`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/target/trait.ProgramMetric.html) | How a program-lane strategy tells the engine what "good" means: score one interpreter output (`JsonMap` of the program's output signature fields) against a labeled example. |
# dspy_rs::predictors
Source: https://dsrs.herumbshandilya.com/docs/api/predictors
Public API of the predictors module
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
## Re-exports
| Item | Description |
| ------------ | --------------- |
| `predict::*` | Glob re-export. |
## Modules
| Item | Description |
| --------------------------------------------------------------------------------- | ----------- |
| [`predict`](https://docs.rs/dspy-rs/latest/dspy_rs/predictors/predict/index.html) | |
## `predictors::predict`
### Structs
| Item | Description |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| [`AgentLoopSpec`](https://docs.rs/dspy-rs/latest/dspy_rs/predictors/predict/struct.AgentLoopSpec.html) | Loop options for a tooled predictor's 1-node `agent` program. |
| [`Demo`](https://docs.rs/dspy-rs/latest/dspy_rs/predictors/predict/struct.Demo.html) | A typed input/output pair for few-shot prompting. |
| [`Predict`](https://docs.rs/dspy-rs/latest/dspy_rs/predictors/predict/struct.Predict.html) | The leaf module. The only thing in the system that actually calls the LM. |
| [`PredictBuilder`](https://docs.rs/dspy-rs/latest/dspy_rs/predictors/predict/struct.PredictBuilder.html) | Builder for `Predict` with demos, tools, and instruction override. |
# dspy_rs::prelude
Source: https://dsrs.herumbshandilya.com/docs/api/prelude
The curated core surface — the recommended import for DSRs programs.
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
The curated core surface — the recommended import for DSRs programs.
## Re-exports
| Item | Description |
| -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| [`average_score`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/fn.average_score.html) | Re-export of `crate::evaluate::average_score`. |
| [`BootstrapFewShot`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/bootstrap/struct.BootstrapFewShot.html) | Re-export of `crate::optimizer::BootstrapFewShot`. |
| [`CallMetadata`](https://docs.rs/dspy-rs/latest/dspy_rs/core/predicted/struct.CallMetadata.html) | Re-export of `crate::core::CallMetadata`. |
| [`Candidate`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.Candidate.html) | Re-export of `crate::optimizer::Candidate`. |
| [`capture_with_meta`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.capture_with_meta.html) | Re-export of `crate::trace::capture_with_meta`. |
| [`capture`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/index.html) | Re-export of `crate::trace::capture`. |
| [`capture`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.capture.html) | Re-export of `crate::trace::capture`. |
| [`ChainOfThought`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/type.ChainOfThought.html) | Re-export of `crate::modules::ChainOfThought`. |
| [`configure`](https://docs.rs/dspy-rs/latest/dspy_rs/core/settings/fn.configure.html) | Re-export of `crate::core::settings::configure`. |
| [`COPRO`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/copro/struct.COPRO.html) | Re-export of `crate::optimizer::COPRO`. |
| [`DataLoader`](https://docs.rs/dspy-rs/latest/dspy_rs/data/dataloader/struct.DataLoader.html) | Re-export of `crate::data::dataloader::DataLoader`. |
| [`Demo`](https://docs.rs/dspy-rs/latest/dspy_rs/predictors/predict/struct.Demo.html) | Re-export of `crate::predictors::Demo`. |
| [`Edit`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/edit/enum.Edit.html) | Re-export of `crate::ir::Edit`. |
| [`Engine`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/engine/struct.Engine.html) | Re-export of `crate::optimizer::Engine`. |
| [`Eval`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Eval.html) | Re-export of `crate::trace::Eval`. |
| [`evaluate_trainset_with_concurrency`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/fn.evaluate_trainset_with_concurrency.html) | Re-export of `crate::evaluate::evaluate_trainset_with_concurrency`. |
| [`evaluate_trainset`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/fn.evaluate_trainset.html) | Re-export of `crate::evaluate::evaluate_trainset`. |
| [`Example`](https://docs.rs/dspy-rs/latest/dsrs_macros/derive.Example.html) | Re-export of `dsrs_macros::Example`. |
| [`GEPA`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/gepa/struct.GEPA.html) | Re-export of `crate::optimizer::GEPA`. |
| [`init_tracing`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/telemetry/fn.init_tracing.html) | Re-export of `crate::utils::init_tracing`. |
| [`Interpreter`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/interp/struct.Interpreter.html) | Re-export of `crate::ir::Interpreter`. |
| [`is_capturing`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.is_capturing.html) | Re-export of `crate::trace::is_capturing`. |
| [`is_replaying`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/fn.is_replaying.html) | Re-export of `crate::trace::is_replaying`. |
| [`LM`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/struct.LM.html) | Re-export of `crate::core::lm::LM`. |
| [`LMConfig`](https://docs.rs/dspy-rs/latest/dspy_rs/core/lm/struct.LMConfig.html) | Re-export of `crate::core::lm::LMConfig`. |
| [`MIPROv2`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/mipro/struct.MIPROv2.html) | Re-export of `crate::optimizer::MIPROv2`. |
| [`Module`](https://docs.rs/dspy-rs/latest/dspy_rs/core/module/trait.Module.html) | Re-export of `crate::core::Module`. |
| [`ModuleState`](https://docs.rs/dspy-rs/latest/dspy_rs/core/state/struct.ModuleState.html) | Re-export of `crate::core::ModuleState`. |
| [`Optimizer`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/trait.Optimizer.html) | Re-export of `crate::optimizer::Optimizer`. |
| [`OptimizeTarget`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/target/struct.OptimizeTarget.html) | Re-export of `crate::optimizer::OptimizeTarget`. |
| [`Overlay`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/params/struct.Overlay.html) | Re-export of `crate::ir::Overlay`. |
| [`Predict`](https://docs.rs/dspy-rs/latest/dspy_rs/predictors/predict/struct.Predict.html) | Re-export of `crate::predictors::Predict`. |
| [`Predicted`](https://docs.rs/dspy-rs/latest/dspy_rs/core/predicted/struct.Predicted.html) | Re-export of `crate::core::Predicted`. |
| [`PredictError`](https://docs.rs/dspy-rs/latest/dspy_rs/core/errors/enum.PredictError.html) | Re-export of `crate::core::PredictError`. |
| [`Predictors`](https://docs.rs/dspy-rs/latest/dspy_rs/core/module/trait.Predictors.html) | Re-export of `crate::core::Predictors`. |
| [`predictors`](https://docs.rs/dspy-rs/latest/dspy_rs/predictors/index.html) | Re-export of `crate::predictors`. |
| [`predictors`](https://docs.rs/dspy-rs/latest/dspy_rs/macro.predictors.html) | Re-export of `crate::predictors`. |
| [`PredictState`](https://docs.rs/dspy-rs/latest/dspy_rs/core/state/struct.PredictState.html) | Re-export of `crate::core::PredictState`. |
| [`Program`](https://docs.rs/dspy-rs/latest/dspy_rs/ir/graph/struct.Program.html) | Re-export of `crate::ir::Program`. |
| [`replay`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/index.html) | Re-export of `crate::trace::replay`. |
| [`replay`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/fn.replay.html) | Re-export of `crate::trace::replay`. |
| [`ReplayMode`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/enum.ReplayMode.html) | Re-export of `crate::trace::ReplayMode`. |
| [`ReplayReport`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/struct.ReplayReport.html) | Re-export of `crate::trace::ReplayReport`. |
| [`Signature`](https://docs.rs/dspy-rs/latest/dspy_rs/core/signature/trait.Signature.html) | Re-export of `crate::core::signature::Signature`. |
| [`Signature`](https://docs.rs/dspy-rs/latest/dsrs_macros/derive.Signature.html) | Re-export of `dsrs_macros::Signature`. |
| [`SIMBA`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/simba/struct.SIMBA.html) | Re-export of `crate::optimizer::SIMBA`. |
| [`SpanId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.SpanId.html) | Re-export of `crate::trace::SpanId`. |
| [`Structural`](https://docs.rs/dspy-rs/latest/dspy_rs/optimizer/structural/struct.Structural.html) | Re-export of `crate::optimizer::Structural`. |
| [`Trace`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Trace.html) | Re-export of `crate::trace::Trace`. |
| [`TypedLoadOptions`](https://docs.rs/dspy-rs/latest/dspy_rs/data/dataloader/struct.TypedLoadOptions.html) | Re-export of `crate::data::dataloader::TypedLoadOptions`. |
| [`TypedMetric`](https://docs.rs/dspy-rs/latest/dspy_rs/evaluate/evaluator/trait.TypedMetric.html) | Re-export of `crate::evaluate::TypedMetric`. |
| [`WithReasoning`](https://docs.rs/dspy-rs/latest/dspy_rs/modules/chain_of_thought/struct.WithReasoning.html) | Re-export of `crate::modules::WithReasoning`. |
# dspy_rs::trace
Source: https://dsrs.herumbshandilya.com/docs/api/trace
Execution trace capture (RFC 0001).
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
Execution trace capture (RFC 0001).
## Re-exports
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `capture::*` | Glob re-export. |
| [`is_replaying`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/fn.is_replaying.html) | Re-export of `replay::is_replaying`. |
| [`replay`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/fn.replay.html) | Re-export of `replay::replay`. |
| [`ReplayError`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/enum.ReplayError.html) | Re-export of `replay::ReplayError`. |
| [`ReplayMode`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/enum.ReplayMode.html) | Re-export of `replay::ReplayMode`. |
| [`ReplayReport`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/struct.ReplayReport.html) | Re-export of `replay::ReplayReport`. |
| `span::*` | Glob re-export. |
| [`TRACE_FORMAT_VERSION`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/serialize/constant.TRACE_FORMAT_VERSION.html) | Re-export of `serialize::TRACE_FORMAT_VERSION`. |
## Modules
| Item | Description |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| [`capture`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/index.html) | Task-local capture scope for the unified trace format. |
| [`replay`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/index.html) | Replay scope: serve `Predict` calls from a recorded `Trace` (RFC 0001 §4d/§4e). |
| [`serialize`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/serialize/index.html) | JSONL wire format for `Trace`: header line, span lines, optional footer. |
| [`span`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/index.html) | The unified trace format (RFC 0001): one `Span` per `Predict` invocation, one `Trace` per rollout. |
## `trace::capture`
Task-local capture scope for the unified trace format.
### Structs
| Item | Description |
| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`SpanGuard`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/struct.SpanGuard.html) | Owns a `SpanId` — event/close attribution travels with the guard, never through "innermost open span" lookups, so interleaved `Predict`s on one task (`futures::join!`) cannot cross... |
| [`SpanOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/struct.SpanOutcome.html) | Everything recorded lazily at span close. |
| [`SpanRequest`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/struct.SpanRequest.html) | Everything recorded eagerly at span open. |
| [`TraceSink`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/struct.TraceSink.html) | Shared handle to an in-progress trace. |
### Functions
| Item | Description |
| ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`begin_span`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.begin_span.html) | Opens a span in the active capture scope. Returns `None` when no scope is active — the caller does nothing else in that case (zero-overhead path). |
| [`capture_with_meta`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.capture_with_meta.html) | `capture` with caller-provided rollout metadata (input, candidate hash, tags). Missing `trace_id`/`started_at_us` are minted at scope start. |
| [`capture`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.capture.html) | Runs `f` while recording every `Predict` call on this task into a `Trace`. |
| [`is_capturing`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/capture/fn.is_capturing.html) | Returns `true` if the current task is inside a `capture` scope. |
## `trace::replay`
Replay scope: serve `Predict` calls from a recorded `Trace` (RFC 0001 §4d/§4e).
### Structs
| Item | Description |
| ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| [`ReplayReport`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/struct.ReplayReport.html) | What a replay scope did, returned by `replay` alongside the closure's result. |
### Enums
| Item | Description |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- |
| [`ReplayError`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/enum.ReplayError.html) | Why a call could not be served from the recording. |
| [`ReplayMode`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/enum.ReplayMode.html) | How a replay scope treats a call that does not match its recording. |
### Functions
| Item | Description |
| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`is_replaying`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/fn.is_replaying.html) | Returns `true` if the current task is inside a `replay` scope. |
| [`replay`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/replay/fn.replay.html) | Runs `f` with `trace` as the canned-response source for every `Predict` call on this task. Returns the closure's result and a `ReplayReport` of what was served versus live. |
## `trace::serialize`
JSONL wire format for `Trace`: header line, span lines, optional footer.
### Constants
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| [`TRACE_FORMAT_VERSION`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/serialize/constant.TRACE_FORMAT_VERSION.html) | Highest format version this reader understands. |
## `trace::span`
The unified trace format (RFC 0001): one `Span` per `Predict` invocation, one `Trace` per rollout.
### Structs
| Item | Description |
| -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`CompId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.CompId.html) | Per-trace interned component index. The component *name* is the same string the params system addresses: an fx slot name (`"drafter"`) or a facet dotted path (`"pipeline.rater"`). |
| [`Eval`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Eval.html) | The metric result type: one score, optional textual feedback. |
| [`ModelEntry`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.ModelEntry.html) | Interned model configuration: `LMConfig` minus live state, minus secrets. |
| [`ModelId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.ModelId.html) | Per-trace interned model configuration. |
| [`PrefixEntry`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.PrefixEntry.html) | |
| [`PrefixId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.PrefixId.html) | Per-trace interned prompt prefix (system message + demo turns). One entry per distinct (component, candidate) configuration — demos serialize once per trace, not once per span. |
| [`Span`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Span.html) | One `Predict` invocation: one rendered prompt in, one parsed output out, with the tool loop's inner structure as ordered events. |
| [`SpanError`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.SpanError.html) | |
| [`SpanId`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.SpanId.html) | Index of a span within its trace. Dense, assigned in insertion order. |
| [`Trace`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.Trace.html) | One rollout: ordered spans plus per-trace intern tables. |
| [`TraceMeta`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.TraceMeta.html) | |
| [`TraceOutcome`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/struct.TraceOutcome.html) | |
### Enums
| Item | Description |
| -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| [`SpanErrorKind`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/enum.SpanErrorKind.html) | |
| [`SpanEvent`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/enum.SpanEvent.html) | Ordered events inside a span. Tagged; readers skip unknown tags — this is the streaming seam (RFC 0001 §6). |
### Type aliases
| Item | Description |
| -------------------------------------------------------------------------------- | ----------- |
| [`JsonMap`](https://docs.rs/dspy-rs/latest/dspy_rs/trace/span/type.JsonMap.html) | |
# dspy_rs::typesys
Source: https://dsrs.herumbshandilya.com/docs/api/typesys
In-house type system that replaces the vendored BAML stack (`bamltype`, `baml_types`, `internal_baml_jinja`, `jsonish`).
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
In-house type system that replaces the vendored BAML stack (`bamltype`, `baml_types`,
`internal_baml_jinja`, `jsonish`).
## Re-exports
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- |
| [`ClassDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.ClassDef.html) | Re-export of `schema::ClassDef`. |
| [`coerce`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/coerce/fn.coerce.html) | Re-export of `coerce::coerce`. |
| [`Coerced`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/coerce/struct.Coerced.html) | Re-export of `coerce::Coerced`. |
| [`Constraint`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/struct.Constraint.html) | Re-export of `constraint::Constraint`. |
| [`ConstraintKind`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/enum.ConstraintKind.html) | Re-export of `constraint::ConstraintKind`. |
| [`ConstraintLevel`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/type.ConstraintLevel.html) | Re-export of `constraint::ConstraintLevel`. |
| [`EnumDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.EnumDef.html) | Re-export of `schema::EnumDef`. |
| [`EnumValueDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.EnumValueDef.html) | Re-export of `schema::EnumValueDef`. |
| [`evaluate_expression`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/fn.evaluate_expression.html) | Re-export of `constraint::evaluate_expression`. |
| [`field_type_from_shape`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/fn.field_type_from_shape.html) | Re-export of `schema::field_type_from_shape`. |
| [`FieldDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.FieldDef.html) | Re-export of `schema::FieldDef`. |
| [`FieldType`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/enum.FieldType.html) | Re-export of `schema::FieldType`. |
| [`Flag`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/coerce/enum.Flag.html) | Re-export of `coerce::Flag`. |
| [`internal_name_for_shape`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/fn.internal_name_for_shape.html) | Re-export of `schema::internal_name_for_shape`. |
| [`OutputSchema`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.OutputSchema.html) | Re-export of `schema::OutputSchema`. |
| [`schema_block`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/render/fn.schema_block.html) | Re-export of `render::schema_block`. |
| [`Schema`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/trait.Schema.html) | Re-export of `schema::Schema`. |
| [`type_name`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/render/fn.type_name.html) | Re-export of `render::type_name`. |
| [`TypeTable`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.TypeTable.html) | Re-export of `schema::TypeTable`. |
## Modules
| Item | Description |
| ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| [`coerce`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/coerce/index.html) | Tolerant coercion of raw LM field text into `serde_json::Value`, guided by `FieldType`. |
| [`constraint`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/index.html) | In-house constraint model + evaluation, replacing BAML's `Constraint` / `run_user_checks`. |
| [`render`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/render/index.html) | Prompt rendering for the in-house type model, replacing BAML's jinja `OutputFormatContent::render` and the adapter's backtick-token pipeline. |
| [`schema`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/index.html) | In-house type model that replaces BAML's `TypeIR` / `OutputFormatContent`. |
## Functions
| Item | Description |
| ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| [`format_value`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/fn.format_value.html) | Renders a value for an input field, honoring an explicit `#format(...)` hint. |
## `typesys::coerce`
Tolerant coercion of raw LM field text into `serde_json::Value`, guided by `FieldType`.
### Structs
| Item | Description |
| -------------------------------------------------------------------------------------- | --------------------------------------------------- |
| [`Coerced`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/coerce/struct.Coerced.html) | The result of coercing raw text into a typed value. |
### Enums
| Item | Description |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| [`Flag`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/coerce/enum.Flag.html) | A non-fatal observation made while coercing a value (e.g. a code fence was stripped). |
### Functions
| Item | Description |
| -------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| [`coerce`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/coerce/fn.coerce.html) | Coerces `raw` into a `serde_json::Value` matching `field_type`. |
## `typesys::constraint`
In-house constraint model + evaluation, replacing BAML's `Constraint` / `run_user_checks`.
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------- |
| [`Constraint`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/struct.Constraint.html) | A single `#check`/`#assert` constraint attached to a field. |
### Enums
| Item | Description |
| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- |
| [`ConstraintKind`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/enum.ConstraintKind.html) | Whether a constraint is a soft `check` (reported) or a hard `assert` (fails the call). |
### Functions
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| [`evaluate_constraint_expression`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/fn.evaluate_constraint_expression.html) | Evaluates a `'static` constraint expression against `value`, compiling it at most once per process. |
| [`evaluate_expression`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/fn.evaluate_expression.html) | Evaluates a runtime (non-`'static`) constraint expression against `value`, binding it as `this`. |
### Type aliases
| Item | Description |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| [`ConstraintLevel`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/constraint/type.ConstraintLevel.html) | Back-compat alias for the old public name. |
## `typesys::render`
Prompt rendering for the in-house type model, replacing BAML's jinja `OutputFormatContent::render` and the adapter's backtick-token pipeline.
### Functions
| Item | Description |
| -------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| [`schema_block`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/render/fn.schema_block.html) | Renders the expanded schema block for a field type. |
| [`type_name`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/render/fn.type_name.html) | Renders the short, inline type label for a field. |
## `typesys::schema`
In-house type model that replaces BAML's `TypeIR` / `OutputFormatContent`.
### Structs
| Item | Description |
| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`ClassDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.ClassDef.html) | A struct definition reachable from a signature's output type. |
| [`EnumDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.EnumDef.html) | A unit-enum definition reachable from a signature's output type. |
| [`EnumValueDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.EnumValueDef.html) | A single value of a unit enum. |
| [`FieldDef`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.FieldDef.html) | A single field inside a `ClassDef`. |
| [`OutputSchema`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.OutputSchema.html) | The full type description for a value: the root `FieldType` plus the `TypeTable` of every class/enum definition it references. Replaces BAML's `OutputFormatContent`. |
| [`TypeTable`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/struct.TypeTable.html) | Owned registry of the class/enum definitions reachable from a signature (RFC 0002 §1.3). |
### Enums
| Item | Description |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| [`FieldType`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/enum.FieldType.html) | Structural type of a signature/nested field, mirroring the subset of BAML's `TypeIR` that DSRs actually uses. |
### Traits
| Item | Description |
| ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [`Schema`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/trait.Schema.html) | Runtime trait exposing the type model + serde-backed value conversion for a type. |
### Functions
| Item | Description |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| [`field_type_from_shape`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/fn.field_type_from_shape.html) | Builds just the `FieldType` for a shape, discarding the class/enum registry. |
| [`internal_name_for_shape`](https://docs.rs/dspy-rs/latest/dspy_rs/typesys/schema/fn.internal_name_for_shape.html) | Computes the internal name for a shape: module path + type identifier when available. |
# dspy_rs::utils
Source: https://dsrs.herumbshandilya.com/docs/api/utils
LM response caching.
Generated from rustdoc JSON at `dspy-rs v0.7.3` (commit `f7d67a6`). Do not edit by hand; regenerate with `python3 docs/scripts/gen_api.py` (see the script header for the rustdoc commands). Item links lead to full signatures and method docs on docs.rs.
LM response caching.
## Re-exports
| Item | Description |
| ----------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| [`CacheEntry`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/cache/struct.CacheEntry.html) | Re-export of `cache::CacheEntry`. |
| [`CacheKey`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/cache/type.CacheKey.html) | Re-export of `cache::CacheKey`. |
| [`init_tracing`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/telemetry/fn.init_tracing.html) | Re-export of `telemetry::init_tracing`. |
| [`ResponseCache`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/cache/struct.ResponseCache.html) | Re-export of `cache::ResponseCache`. |
| [`TelemetryInitError`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/telemetry/enum.TelemetryInitError.html) | Re-export of `telemetry::TelemetryInitError`. |
| [`truncate`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/telemetry/fn.truncate.html) | Re-export of `telemetry::truncate`. |
## Modules
| Item | Description |
| -------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| [`cache`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/cache/index.html) | |
| [`hash`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/hash/index.html) | Stable 64-bit hashing for trace request hashes and LM cache keys. |
| [`telemetry`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/telemetry/index.html) | |
## `utils::cache`
### Structs
| Item | Description |
| ----------------------------------------------------------------------------------------------- | --------------------------------------- |
| [`CacheEntry`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/cache/struct.CacheEntry.html) | A cached prompt-response pair. |
| [`ResponseCache`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/cache/struct.ResponseCache.html) | Hybrid memory + disk LM response cache. |
### Type aliases
| Item | Description |
| ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| [`CacheKey`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/cache/type.CacheKey.html) | Response-cache key: a 64-bit hash over the prompt + generation parameters. |
## `utils::hash`
Stable 64-bit hashing for trace request hashes and LM cache keys.
### Structs
| Item | Description |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`HashWriter`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/hash/struct.HashWriter.html) | Adapts a `Hasher` into a `std::fmt::Write` sink so values can be hashed through their `Debug`/`Display` representation without materializing a string. |
| [`StableHasher`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/hash/struct.StableHasher.html) | FNV-1a 64-bit hasher: deterministic across platforms and Rust versions. |
### Functions
| Item | Description |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| [`stable_hash_debug`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/hash/fn.stable_hash_debug.html) | Hashes a `Debug`-formatted value with the stable hasher. |
## `utils::telemetry`
### Enums
| Item | Description |
| ----------------------------------------------------------------------------------------------------------- | ----------- |
| [`TelemetryInitError`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/telemetry/enum.TelemetryInitError.html) | |
### Functions
| Item | Description |
| --------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
| [`init_tracing`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/telemetry/fn.init_tracing.html) | Installs process-global, pretty tracing output for DSRs. |
| [`truncate`](https://docs.rs/dspy-rs/latest/dspy_rs/utils/telemetry/fn.truncate.html) | |
# Adapters
Source: https://dsrs.herumbshandilya.com/docs/components/adapters
Turn signatures into prompts and parse LM responses
An adapter sits between a signature and the LM: it formats inputs into the prompt the model sees and parses the LM's response back into typed outputs. The default adapter is `ChatAdapter`, and [Predict](/docs/components/predict) drives it for you (via the IR interpreter), so you touch it directly only to inspect what the model sees.
## What adapters do
```
SignatureDef + Input → Adapter.format() → Prompt for LM
LM Response → Adapter.parse() → Typed Output
```
`ChatAdapter` handles both formatting and parsing. It has one lane: every method is parameterized by an owned [`SignatureDef`](/docs/components/program-and-nodes) — the IR's value-level signature — whether the def came from a derived `Signature` type (`SignatureDef::of::()`) or from a loaded `.dsrs` program. There is no separate "static" formatting path.
## ChatAdapter
### Prompt structure
The system message has four parts (in this order):
1. **Field descriptions** - Lists input/output fields with types and descriptions
2. **Field structure** - Shows the marker format + type schemas
3. **Response instructions** - "Respond with `[[ ## field ## ]]`..."
4. **Task description** - Your instruction from the signature docstring (at the **end**)
Example system message (simplified):
```
Your input fields are:
1. `question` (string): The question to answer
Your output fields are:
1. `answer` (string): A clear, direct answer
All interactions will be structured in the following way...
[[ ## question ## ]]
question
[[ ## answer ## ]]
Output field `answer` should be of type: string
[[ ## completed ## ]]
Respond with the corresponding output fields, starting with `[[ ## answer ## ]]`,
and then ending with the marker for `[[ ## completed ## ]]`.
In adhering to this structure, your objective is:
Answer questions accurately and concisely.
```
### Marker protocol
Fields are delimited by markers:
```
[[ ## field_name ## ]]
value here
[[ ## another_field ## ]]
another value
[[ ## completed ## ]]
```
This protocol (inspired by DSPy) allows mixing natural language with structured output.
### Type schemas
For complex types, the adapter renders full schemas with `typesys::render`: `type_name` produces the short inline label, and `schema_block` expands class field layouts and enum value lists:
```
[[ ## analysis ## ]]
Output field `analysis` should be of type: Analysis
Definitions (used below):
Sentiment
----
- Positive
- Negative
- Neutral
{
"sentiment": Sentiment,
"confidence": float,
"keywords": string[]
}
```
Type names are simplified for readability:
* Module paths stripped: `my_crate::Sentiment` → `Sentiment`
* `class`/`enum` prefixes removed
* `" | "` → `" or "` (more natural)
### Tolerant parsing with typesys::coerce
Response parsing uses `typesys::coerce`, a tolerant coercer that turns raw LM field text into typed values, guided by the expected field type. It handles:
* **Markdown fences** - Strips \`\`\`json fences before parsing
* **Lists from prose** - Parses bulleted or numbered lists into arrays
* **Type coercion** - `"42"` → `42`, `"yes"` → `true` (loose bool and number spellings)
* **Surrounding text** - Ignores extra prose around a JSON object or array
* **Partial recovery** - Per-field failures aggregate; you get every error plus what did parse
```rust theme={null}
// Internally, per output field:
typesys::coerce(raw_text, field_type, &output_schema.types)
```
Each non-fatal fix (a stripped fence, a coerced scalar) is recorded as a `Flag` on the returned `Coerced` value.
### Constraint evaluation
After parsing, the adapter runs [constraints](/docs/components/signatures):
* `#[check]` results → stored in metadata
* `#[assert]` failures → returns `ParseError::AssertFailed`
### Error handling
Parse errors aggregate - you get all problems, not just the first:
```rust theme={null}
ParseError::Multiple {
errors: vec![...], // all field errors
partial: Some(serde_json::Value::Object(...)), // what did parse
}
```
## Using the adapter directly
Usually you do not touch the adapter - `Predict` handles it. The public surface is five building blocks, all parameterized by `&SignatureDef`:
| Method | Produces |
| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `build_system_def(def, types, instruction_override)` | The system message (field descriptions, structure template, response instructions, task description) |
| `format_input_def(def, input)` | The user message: input fields with `[[ ## field ## ]]` markers plus response instructions. `input` is a `JsonMap`; absent fields are skipped |
| `format_output_def(def, output)` | An assistant message for few-shot demos, ending with `[[ ## completed ## ]]` |
| `parse_output_def(def, types, response)` | `(JsonMap, IndexMap)` — the parsed output map plus per-field parse metadata |
| `ChatAdapter::parse_sections(content)` | Ordered map of `field_name → section_content` split by the delimiters |
For debugging what the LM sees from a derived signature:
```rust theme={null}
use dspy_rs::{ChatAdapter, ir::SignatureDef};
let adapter = ChatAdapter;
let def = SignatureDef::of::();
let types = SignatureDef::types_of::();
let system = adapter.build_system_def(def, types, None);
println!("System:\n{system}");
```
## Input formatting options
Input fields support two rendering paths:
```rust theme={null}
#[derive(Signature, Clone, Debug)]
struct Search {
#[input]
query: String, // plain text
#[input]
#[format("yaml")]
filters: Vec, // serialized as YAML
#[input]
#[render(jinja = "{{ this.text }}\nQuestion: {{ input.query }}")]
context: Context, // custom Jinja rendering
#[output]
results: Vec,
}
```
* `#[format("json" | "yaml" | "toon")]`: serialize a field using that format.
* `#[render(jinja = "...")]`: render a field with a MiniJinja template.
* `#[format]` and `#[render]` are mutually exclusive on the same field.
`#[render]` context in `ChatAdapter`:
* `this`: current field value
* `input`: full input object (plus top-level alias overlays)
* `field`: `{ name, rust_name, type }`
* `vars`: adapter/surface vars (currently `{}`)
`ChatAdapter` configures MiniJinja with strict undefined behavior.
Available filters include:
* MiniJinja built-ins
* `regex_match` and `sum` helpers
* `truncate` for length-limited string rendering
If template rendering fails at runtime (for example, missing variables), `ChatAdapter` panics.
Templates are compiled per call — defs own their template strings, so there is no process-global template cache to leak per loaded program.
## Real example: Insurance claim extraction
This is what a prompt looks like for a complex nested type (from [`examples/16-insurance-claim-prompt.rs`](https://github.com/krypticmouse/DSRs/blob/main/crates/dspy-rs/examples/16-insurance-claim-prompt.rs)):
```rust theme={null}
#[derive(Signature, Clone, Debug)]
/// Extract the insurance claim information from the following text.
/// - If you are unsure about a field, leave it as null.
pub struct InsuranceClaimInfo {
#[input]
claim_text: String,
#[output]
claim: InsuranceClaim, // complex nested struct with enums
}
```
```rust theme={null}
type NaiveDate = String; // dates as YYYY-MM-DD strings
/// Basic claim information (metadata about the claim intake).
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub struct ClaimHeader {
/// Claim ID in format `CLM-XXXXXX`, where `X` is a digit.
pub claim_id: Option,
/// Date claim was reported in `YYYY-MM-DD` format.
pub report_date: Option,
/// Date incident occurred in `YYYY-MM-DD` format.
pub incident_date: Option,
/// Full name of person reporting claim.
pub reported_by: Option,
/// Channel used to report claim.
pub channel: Option,
}
/// Channel used to report a claim.
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub enum ClaimChannel {
Email,
Phone,
Portal,
InPerson,
}
/// Policy information if available.
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub struct PolicyDetails {
/// Policy number in format `POL-XXXXXXXXX`, where `X` is a digit.
pub policy_number: Option,
/// Full legal name on policy.
pub policyholder_name: Option,
/// Type of insurance coverage.
pub coverage_type: Option,
/// Policy effective start date in `YYYY-MM-DD` format.
pub effective_date: Option,
/// Policy expiration end date in `YYYY-MM-DD` format.
pub expiration_date: Option,
}
/// Type of insurance coverage.
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub enum CoverageType {
Property,
Auto,
Liability,
Health,
Travel,
Other,
}
/// An insured object involved in the claim (vehicle, building, person, etc.).
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub struct InsuredObject {
/// Unique identifier for insured object.
///
/// For vehicles, use VIN format (e.g., `VIN12345678901234567`).
/// For buildings, use `PROP-XXXXXX` format.
/// For liability, use `LIAB-XXXXXX` format.
/// For other objects, use `OBJ-XXXXXX` format,
/// where `X` is a digit.
pub object_id: Option,
/// Type of insured object.
pub object_type: InsuredObjectType,
/// Make and model for vehicles, or building type for property.
pub make_model: Option,
/// Year for vehicles or year built for buildings.
pub year: Option,
/// Full street address where object is located or originated from.
pub location_address: Option,
/// Estimated monetary value in USD without currency symbol.
pub estimated_value: Option,
}
/// Type of insured object.
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub enum InsuredObjectType {
Vehicle,
Building,
Person,
Other,
}
/// Structured incident details.
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub struct IncidentDescription {
/// Specific standardized incident type.
pub incident_type: IncidentType,
/// Standardized location type where incident occurred.
pub location_type: LocationType,
/// Estimated damage in USD without currency symbol.
pub estimated_damage_amount: Option,
/// Police report number if applicable.
pub police_report_number: Option,
}
/// Specific standardized incident type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub enum IncidentType {
RearEndCollision,
SideImpactCollision,
HeadOnCollision,
ParkingLotCollision,
HouseFire,
KitchenFire,
ElectricalFire,
BurstPipeFlood,
StormDamage,
RoofLeak,
SlipAndFall,
PropertyInjury,
ProductLiability,
TheftBurglary,
Vandalism,
}
/// Standardized location type where incident occurred.
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub enum LocationType {
Intersection,
Highway,
ParkingLot,
Driveway,
ResidentialStreet,
ResidenceInterior,
ResidenceExterior,
CommercialProperty,
PublicProperty,
}
/// Top-level insurance claim object aggregating all extracted fields.
#[derive(Debug, Clone, PartialEq, Eq)]
#[Schema]
pub struct InsuranceClaim {
/// Basic claim information.
pub header: ClaimHeader,
/// Policy information if available.
pub policy_details: Option,
/// List of insured objects involved, if applicable.
pub insured_objects: Option>,
/// Structured incident details.
pub incident_description: Option,
}
```
**Generated system message:**
```
Your input fields are:
1. `claim_text` (string)
Your output fields are:
1. `claim` (InsuranceClaim)
All interactions will be structured in the following way, with the appropriate values filled in.
[[ ## claim_text ## ]]
claim_text
[[ ## claim ## ]]
Output field `claim` should be of type: InsuranceClaim
Definitions (used below):
// Specific standardized incident type.
IncidentType
----
- RearEndCollision
- SideImpactCollision
- HeadOnCollision
- ParkingLotCollision
- HouseFire
- KitchenFire
- ElectricalFire
- BurstPipeFlood
- StormDamage
- RoofLeak
- SlipAndFall
- PropertyInjury
- ProductLiability
- TheftBurglary
- Vandalism
// Standardized location type where incident occurred.
LocationType
----
- Intersection
- Highway
- ParkingLot
- Driveway
- ResidentialStreet
- ResidenceInterior
- ResidenceExterior
- CommercialProperty
- PublicProperty
{
// Top-level insurance claim object aggregating all extracted fields.
// Basic claim information.
header: {
// Basic claim information (metadata about the claim intake).
// Claim ID in format `CLM-XXXXXX`, where `X` is a digit.
claim_id: string or null,
// Date claim was reported in `YYYY-MM-DD` format.
report_date: string or null,
// Date incident occurred in `YYYY-MM-DD` format.
incident_date: string or null,
// Full name of person reporting claim.
reported_by: string or null,
// Channel used to report claim.
channel: 'Email' or 'Phone' or 'Portal' or 'InPerson' or null,
},
// Policy information if available.
policy_details: {
// Policy information if available.
// Policy number in format `POL-XXXXXXXXX`, where `X` is a digit.
policy_number: string or null,
// Full legal name on policy.
policyholder_name: string or null,
// Type of insurance coverage.
coverage_type: 'Property' or 'Auto' or 'Liability' or 'Health' or 'Travel' or 'Other' or null,
// Policy effective start date in `YYYY-MM-DD` format.
effective_date: string or null,
// Policy expiration end date in `YYYY-MM-DD` format.
expiration_date: string or null,
} or null,
// List of insured objects involved, if applicable.
insured_objects: [
{
// An insured object involved in the claim (vehicle, building, person, etc.).
// Unique identifier for insured object.
//
// For vehicles, use VIN format (e.g., `VIN12345678901234567`).
// For buildings, use `PROP-XXXXXX` format.
// For liability, use `LIAB-XXXXXX` format.
// For other objects, use `OBJ-XXXXXX` format,
// where `X` is a digit.
object_id: string or null,
// Type of insured object.
object_type: 'Vehicle' or 'Building' or 'Person' or 'Other',
// Make and model for vehicles (use standardized manufacturer names and models),
// or building type for property.
make_model: string or null,
// Year for vehicles or year built for buildings.
year: int or null,
// Full street address where object is located or originated from.
location_address: string or null,
// Estimated monetary value in USD without currency symbol.
estimated_value: int or null,
}
] or null,
// Structured incident details.
incident_description: {
// Structured incident details.
// Specific standardized incident type.
incident_type: IncidentType,
// Standardized location type where incident occurred.
location_type: LocationType,
// Estimated damage in USD without currency symbol.
estimated_damage_amount: int or null,
// Police report number if applicable.
police_report_number: string or null,
} or null,
}
[[ ## completed ## ]]
Respond with the corresponding output fields, starting with the field `[[ ## claim ## ]]`, and then ending with the marker for `[[ ## completed ## ]]`.
In adhering to this structure, your objective is:
Extract the insurance claim information from the following text.
- If you are unsure about a field, leave it as null.
```
**Generated user message:**
```
[[ ## claim_text ## ]]
A raccoon bumped a parked scooter in a driveway. Reported by Taylor P. via phone.
```
Notice how:
* Enums with many variants become "Definitions" at the top
* Doc comments become inline `//` comments in the schema
* `Option` renders as `T or null`
* Nested objects show their full structure
* The instruction comes from the signature docstring
## Design notes
* **DSPy inspiration:** Marker protocol from DSPy's ChatAdapter
* **BAML heritage:** Schema rendering and tolerant parsing were originally built on the vendored BAML stack (`jsonish` and its schema renderer). The in-house `typesys` module (`typesys::render`, `typesys::coerce`) replaced that stack while keeping the same prompt-facing schema style.
* **Separation of concerns:** Adapter does not know about LMs - just formatting/parsing
## See also
* [Signatures](/docs/components/signatures) for field types, `#[Schema]`, and constraints
* [Predict](/docs/components/predict) for the caller that drives the adapter
* [LM](/docs/components/lm) for the client the formatted prompt is sent to
* Example: [16-insurance-claim-prompt.rs](https://github.com/krypticmouse/DSRs/blob/main/crates/dspy-rs/examples/16-insurance-claim-prompt.rs)
# Capabilities
Source: https://dsrs.herumbshandilya.com/docs/components/capabilities
Named permissions: programs declare a ceiling, tools and holes declare needs, hosts grant, and load checks the subset
A capability is a named permission: `orders:read`, `net:search`, `fs:read`. Nothing more mysterious than that, a short label for one kind of access to the world. Three parties each state their side in writing, and the statements are checked against each other at load, before a single step runs.
## Three statements, one check
| Party | Statement | Where it is written |
| ------------------ | ----------------------------------------- | -------------------------------------------------------------------------- |
| The program | Its ceiling: the most it could ever touch | `caps { ... }` in the artifact, `#[module(caps(...))]` in source |
| Each tool and hole | Its needs | `#[tool(caps("..."))]` in source, `caps [...]` on the printed tool or hole |
| The host | Its grants | `--allow` on the `dsrs` host, `RuntimeEnv::grant` in an embedding binary |
**The program declares its ceiling.** At the top of the artifact:
```text theme={null}
caps { kb:read orders:read }
```
This is not what the program will do on a given run. It is the most it could ever do. Because the declaration is a line in a reviewable text file, it is diffable data: a program that never declared network access cannot quietly grow it, because the file would change and the change would show in review like any other line.
**Every tool and hole declares its needs.** A host tool names them in its attribute:
```rust theme={null}
/// Look up an order's status by id.
#[tool(caps("orders:read"))]
async fn order_lookup(order_id: String) -> Result {
// your implementation
}
```
A tool or hole that touches nothing declares `caps []`. Each piece's needs must fit under the program's ceiling as a subset, and this is checked at load: a ceiling that says only `kb:read` cannot contain a tool that needs `orders:read`, and the violation is a load error, not an incident in production.
**The host states its grants.** Whoever runs the program has the final word. Serve the file but grant only the FAQ capability:
```bash theme={null}
dsrs serve frontdesk.dsrs --allow kb:read
```
```text theme={null}
program caps exceed host grants: missing ["orders:read"]
```
The program's caps must be a subset of the host's grants or loading refuses, up front and by name, before a token is spent. In an embedding binary the same grants come from `RuntimeEnv::grant(cap)`, and the same subset check runs inside `Interpreter::load`.
## The empty sandbox
Permission systems usually fail by omission: a deny list forgets an entry, or a check gets bypassed by a code path nobody audited. The DSRs sandbox inverts this. When a sandboxed hole or a [Code Mode](/docs/components/code-mode) script starts, its environment contains only what the host granted. An ungranted capability is not a blocked call inside the sandbox; the function for it does not exist there at all. Ungrant `orders:read` and the sandbox simply contains no `order_lookup`, so no script, however creative, can invoke it. There is nothing to bypass. Deny lists require perfect memory; empty sandboxes do not.
This is why a model writing JavaScript in the sandbox is not being trusted. It is being contained by construction: the sandbox starts empty, and only grants get placed inside.
## Local modules and loaded files
When you run your own `#[module]` directly, nobody asks you to `--allow` anything. The native parts are already in your binary, compiled from your own source, and a gate between you and code you wrote yourself withholds nothing. The module's generated `env()` therefore grants its own declared ceiling, and the declaration serves as documentation plus the fence around any sandboxed parts.
The moment the same program travels as a `.dsrs` file, trust resets to zero. A host loading the file re-checks the program's caps against its own grants, and the program gets exactly what the host allows. Same declaration, two enforcement postures, both consistent with who wrote what.
## Declarations are data
Every capability statement lives in the artifact as plain text: the `caps { ... }` ceiling at the top, and `caps [...]` on each printed tool and hole. That makes the permission surface reviewable with the same machinery as any other change. A pull request that widens a program's ceiling is a visible diff on one line, and a load failure names the exact missing set, as in the error above.
## See also
* [Tools and agents](/docs/components/tools-and-agents) for declaring needs on host and sandboxed tools
* [Holes](/docs/components/holes) for the `caps []` printed on holes
* [Runtime](/docs/components/runtime) for `RuntimeEnv::grant` and the load-time subset check
* [The .dsrs file](/docs/components/dsrs-file) for the caps grammar
* [Code Mode](/docs/components/code-mode) for the sandbox that scripts run inside
# CLI
Source: https://dsrs.herumbshandilya.com/docs/components/cli
Reference for the dsrs binary: check, fmt, the HTTP serving host, and the full print-and-serve workflow
The `dsrs` binary is the `.dsrs` toolchain: check, fmt, serve. It ships as the `dsrs-cli` crate; every subcommand is a plain library function (`dsrs_cli::check`, `dsrs_cli::fmt`, `dsrs_cli::serve`), and the binary itself is argument parsing plus process exit codes. All subcommands exit 0 on success and non-zero on failure.
```bash theme={null}
dsrs check qa.dsrs # parse, validate, print the program summary
dsrs fmt qa.dsrs --write # rewrite the file in canonical form
dsrs serve qa.dsrs --port 8080 # serve it over HTTP
```
The toolchain covers the whole journey of a program file: printed from your code, checked, served on another host, and embeddable back into a Rust build.
## `dsrs check `
Parses and validates a `.dsrs` artifact via `Program::load_dsrs`, running the full pipeline: lex and parse with positions, lowering, `Program::validate`, hash sealing. This is exactly what `Interpreter::load` would accept, which makes `check` a pre-commit gate for a human and a regeneration signal for a model loop.
On success it prints one line to stdout: `ok: program` with the program name, its 16-hex hash, the node, signature, model, and tool counts, and the caps set when non-empty. On failure the parser's error goes to stderr with the artifact path and a `line N, column M: expected ...` position, and the exit code is non-zero.
## `dsrs fmt [--write]`
Prints (or rewrites) the canonical form of an artifact. The canonical form is `Program::to_dsrs`, the same text that seals `program_hash` and that `bake` writes. Formatting is parse then print, never token shuffling, so an artifact that does not parse does not format.
| Flag | Effect |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| (none) | Prints the canonical text to stdout. |
| `--write` | Rewrites the file in place, only when the bytes differ. Reports ``formatted `` `` or `` `` already canonical`` on stderr. |
## `dsrs serve [flags]`
Serves a `.dsrs` program over HTTP. Startup is fail-fast, before the port binds: parse, apply the optional overlay (named form, verified against the program's hash and slot kinds), then `Interpreter::load` with the grants from `--allow`. Models are constructed from the artifact configs with secrets from provider environment variables; a QuickJS sandbox is added when none was supplied. Once bound, the address is printed on stderr.
| Flag | Default | Meaning |
| ------------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--host ` | `127.0.0.1` | Bind address. |
| `--port ` | `8080` | Bind port (0 binds an ephemeral port). |
| `--overlay ` | none | Overlay JSON in the named form (`{"": , ...}`), applied read-through on every run. |
| `--allow ` | none | Capability grant, repeatable: `--allow net:search --allow fs:read`. Load is refused (with the missing set printed) when the program's caps exceed the grants. |
Host tools cannot be served: a program declaring a host tool needs an embedding host that supplies the binding ([`include_program!`](/docs/components/runtime) plus your own code, or a sandboxed `js` tool instead). The load surfaces that refusal with a hint rather than a bare unbound-tool error.
### HTTP endpoints
| Endpoint | What it returns |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST /run` | Body is a JSON object of input fields; the response is `{"output": ...}`. With `?trace=1` (or `?trace=true`) the run executes inside a capture scope and the response adds `"trace_jsonl"`, the exact trace artifact text with `param_ids` attached. |
| `GET /schema` | The program's external interface: `{"program", "program_hash", "signature", "types"}`, the main signature and the type table in their serde forms. |
| `GET /program` | The canonical `.dsrs` text, as `text/plain; charset=utf-8`. |
| `GET /healthz` | `{"status": "ok"}` plus the program name and hash. |
Error responses are always `{"error": ...}` with the interpreter's own message: a non-object request body and input-surface rejections are 400, everything else (LM failures, parse failures, budget, routing) is 500.
## From code to endpoint
The full workflow: print a program out of your code, check it, format it, serve it.
### 1. Print the program
Every [`#[module]`](/docs/components/module-macro) exposes `program()`. Call `to_dsrs()` on it to get the canonical text, then save it:
```rust theme={null}
let text = qa::program().to_dsrs();
std::fs::write("qa.dsrs", text)?;
```
One note before serving: a file printed from a `#[module]` holds a placeholder model line like `model default = "unbound:default"`, because the real model was bound in your code. Open the file and point each model line at a real model, for example:
```
model default = "openai:gpt-4o-mini"
```
### 2. Check it
Errors come with line and column positions, so `check` works as a pre-commit gate:
```bash theme={null}
dsrs check qa.dsrs
# ok: program `qa` (3f9c...) - 4 nodes, 4 sigs, 1 models, 0 tools
```
### 3. Format it
```bash theme={null}
dsrs fmt qa.dsrs # print the canonical form to stdout
dsrs fmt qa.dsrs --write # rewrite the file in place
```
A file that does not parse does not format; fix `check` errors first.
### 4. Serve it
```bash theme={null}
dsrs serve qa.dsrs --port 8080
```
Model API keys come from the usual provider environment variables (for example `OPENAI_API_KEY`). The flag table above lists `--host`, `--port`, `--overlay`, and `--allow`.
### 5. Call it
```bash theme={null}
curl -s localhost:8080/run \
-H 'content-type: application/json' \
-d '{"question": "What is DSRs?"}'
# {"output": {"answer": "...", "upper": "..."}}
```
Add `?trace=1` to `POST /run` to also get a full trace of the run; the endpoint table above lists `/schema`, `/program`, and `/healthz`.
## Capabilities: needs versus allows
The program states what it needs in its `caps { ... }` block. The host states what it allows with `--allow`. Serving refuses to start when the program asks for more than the host allows, and it prints the missing set. This is on purpose: a program can never quietly get more access than you granted.
Two more refusals to know about:
* A program with host [holes](/docs/components/holes) cannot be served by `dsrs serve`, because the Rust code lives in the binary that defined it. Embed the program with `include_program!` instead; see [Runtime](/docs/components/runtime).
* Same story for host tools: the server has no implementation to bind. Sandboxed JavaScript tools serve fine, because their code travels inside the file.
## Common mistakes
**Serving a file with an unbound placeholder model.** Edit the `model` lines to real models first.
**Forgetting `--allow`.** If the file declares `caps { net:search }`, serving without `--allow net:search` refuses at startup. That is the design working, not a bug.
**Editing the file by hand and skipping `dsrs check`.** Always check after hand edits. The parser's error messages carry positions and are meant to be followed.
## See also
* [The .dsrs file](/docs/components/dsrs-file): the artifact format the toolchain operates on.
* [Program and nodes](/docs/components/program-and-nodes): what `check` validates, what `fmt` prints, and how `bake` produces new files.
* [Runtime](/docs/components/runtime): `Interpreter`, `RuntimeEnv`, capability grants, overlays, and embedding with `include_program!`.
* [Traces](/docs/components/traces): the trace artifact `POST /run?trace=1` returns.
# Code Mode
Source: https://dsrs.herumbshandilya.com/docs/components/code-mode
Reference for the run_js meta-tool, the QuickJS sandbox, ToolSource, Capability, and every ExecError and RegisterError variant
Plain JSON tool calling pays one model round trip per call: the model emits a single tool invocation, the host executes it, and the result goes back to the model before it can decide the next step. A task that needs several tool results spends a full LM turn of latency and tokens on each one, and every intermediate result flows through the model's context even when only the final value matters.
Code Mode replaces JSON tool calling with code execution. Instead of advertising N tool schemas and paying one model round trip per call, the model sees a single meta-tool named `run_js`. Its description lists your tools as a JavaScript API; the model writes a script that calls them as plain global functions, composes their results, and returns one value. One script replaces many round trips.
Everything on this page lives in the `dsrs-tools` crate. The `dspy-rs` crate re-exports `Capability`, `CodeModeTool`, `RUN_JS_TOOL_NAME`, and `SandboxConfig` behind the `code-mode` cargo feature, which is on by default. The rest of the surface (executor, sources, errors) is imported from `dsrs_tools` directly. `dsrs_tools` also re-exports `rig::tool::ToolDyn` and `rig::tool::ToolError` (as `RigToolError`) so downstream crates do not need a version-matched `rig` dependency.
## Two-tier design
| Tier | Status | Engine | Properties |
| ---- | ----------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | Implemented | QuickJS (quickjs-ng via `rquickjs`), in process | Fresh runtime and context per call (lifecycle on the order of 100 microseconds), per-call memory limit, interrupt-driven wall-clock deadline, no ambient authority: no filesystem, network, environment, or module loader. Host access happens only through injected `Capability` functions. |
| 2 | Planned | Wasmtime components | Pooled instantiation, epoch interruption, typed WIT interfaces, for tools that graduate from ephemeral to durable. |
The `Executor` trait is the seam between the tiers: subprocess, microVM, and remote executors can implement the same contract.
## `ToolSource` and the tool lifecycle
`ToolSource` is the raw material for an ephemeral tool, before validation.
| Field | Type | Meaning |
| ------------- | ------------------- | -------------------------------------------------------------------------------- |
| `name` | `String` | Unique tool name, `[A-Za-z0-9_-]{1,64}`. |
| `description` | `String` | Natural-language description shown to the model. |
| `params` | `serde_json::Value` | JSON Schema for the arguments (an object schema). |
| `js_source` | `String` | JavaScript source per the contract below. |
| `self_test` | `Option` | Optional self-test program. A tool with a failing self-test is never registered. |
| Method | Signature | What it does |
| ----------------- | ------------------------------------------------ | ------------------------------------------------------- |
| `new` | `(name, description, params, js_source) -> Self` | Constructor; `self_test` starts as `None`. |
| `with_self_test` | `(self, self_test) -> Self` | Attaches a self-test program. |
| `validate_shape` | `(&self) -> Result<(), RegisterError>` | Cheap synchronous checks on the name and params schema. |
| `required_params` | `(&self) -> Vec` | Names listed in the schema's `required` array. |
`js_source` must be a single expression that evaluates to a function taking one argument (the parsed JSON args object) and returning a JSON-serializable value or a promise of one. Helpers go inside an IIFE that returns the tool function. Named `function` declarations are wrapped in parentheses and become expressions; one trailing `;` is tolerated. The self-test runs with the global `tool` bound to the compiled function; it fails if it throws or completes with `false`.
A source only becomes callable after passing every stage of `Executor::register`:
| Stage | Check | Failure |
| ----------- | ----------------------------------------------------------------- | ------------------------------------------- |
| Shape | Name charset and length, params-schema structure, duplicate name. | `InvalidName`, `InvalidSchema`, `Duplicate` |
| Compile | The source must parse. Bytecode is cached by BLAKE3 content hash. | `Compile` |
| Instantiate | The module must evaluate to a function, in a sandbox. | `NotAFunction` |
| Self-test | If present, the test must pass inside the sandbox. | `SelfTest` |
## `Executor`, `ToolInvocation`, `RegisteredTool`
`ToolInvocation` is one call: `{ name: String, args: Value }`, built with `ToolInvocation::new(name, args)`.
`RegisteredTool` is the metadata of a tool that survived the lifecycle:
| Field | Type | Meaning |
| ------------- | -------- | -------------------------------------------------------------------------------- |
| `name` | `String` | Registered name. |
| `description` | `String` | Description from the source. |
| `parameters` | `Value` | Arguments JSON Schema from the source. |
| `source_hash` | `String` | Hex BLAKE3 hash of the JavaScript source; the bytecode-cache key. |
| `self_tested` | `bool` | `true` if an explicit self-test passed; `false` means no self-test was provided. |
`Executor` is `Send + Sync` and deliberately narrow:
| Method | Signature | What it does |
| ------------ | -------------------------------------------------------------------- | --------------------------------------------------- |
| `validate` | `(&self, &ToolSource) -> Result<(), RegisterError>` | Synchronous structural validation only; no sandbox. |
| `register` | `async (&self, ToolSource) -> Result` | The full four-stage lifecycle. |
| `execute` | `async (&self, ToolInvocation) -> Result` | Runs a registered tool with JSON args. |
| `tool` | `(&self, &str) -> Option` | Metadata for one registered tool. |
| `tools` | `(&self) -> Vec` | Metadata for every registered tool. |
| `deregister` | `(&self, &str) -> bool` | Removes a tool; `true` if it was registered. |
## `QuickJsExecutor`
The Tier-1 executor. Cheap to share: wrap it in an `Arc` and clone across tasks. It requires a Tokio runtime for its blocking pool.
| Method | What it does |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `new()` | Default `SandboxConfig`, no capabilities. |
| `with_config(config)` | Explicit `SandboxConfig`. |
| `builder()` | Returns a `QuickJsExecutorBuilder`. |
| `config()` | The active `SandboxConfig`. |
| `add_capability(cap)` | Injects a host capability; its name becomes a global JS function in every sandbox created afterward. A duplicate name is refused with `RegisterError::InvalidCapability`. |
| `capability_names()` | Injected capability names, in registration order. |
| `cache_stats()` | Bytecode-cache counters, as `CacheStats`. |
| `rig_tool(name)` | On `Arc`: wraps a registered tool as `Arc`; `None` if not registered. |
| `register_rig(source)` | On `Arc`, async: `register` plus `rig_tool` in one step. |
| `execute_blocking(invocation)` | Synchronous execution on the current thread, skipping the blocking pool. Capabilities still need a reachable Tokio runtime. Do not call from inside an async task. |
The builder sets limits and capabilities before construction:
| Builder method | What it sets |
| --------------------- | ------------------------------------------ |
| `memory_limit(bytes)` | Max heap per call. |
| `deadline(duration)` | Wall-clock budget per call. |
| `max_stack(bytes)` | Max JS stack per call. |
| `capability(cap)` | Queues a capability, validated at `build`. |
| `build()` | `Result`. |
### `SandboxConfig`
Resource limits applied to every sandbox instance. `Copy`, so it is passed by value everywhere.
| Field | Type | Default | Meaning |
| -------------- | ---------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `memory_limit` | `usize` | 32 MiB | Max heap for one call, in bytes. Exceeding it kills the call as `MemoryExceeded`. |
| `deadline` | `Duration` | 500 ms | Wall-clock budget for one call. JS execution is interrupted by the engine's interrupt handler; a capability call is host code the interrupt handler cannot reach, so the executor bounds it with the *remaining* budget via `tokio::time::timeout` — a handler that runs past it is dropped and the call surfaces in JS as a deadline timeout. |
| `max_stack` | `usize` | 512 KiB | Max JS stack, in bytes. |
### `CacheStats`
Sources compile once per unique content (BLAKE3-keyed) and the bytecode is shared across calls and tool names. `CacheStats` carries `entries: usize`, `hits: u64`, `misses: u64`. The cache is bounded at 128 entries with a deliberately simple cap-and-clear eviction (an optimizer generating thousands of candidate tool bodies stays bounded instead of leaking them all); registered tools hold their own reference to their bytecode, so eviction only costs a recompile on the next miss. `deregister` evicts the tool's entry unless another registered tool shares the same source hash.
### `run_script`
The Code Mode execution primitive: a free async function, not a method.
```rust theme={null}
pub async fn run_script(
source: &str,
capabilities: Vec,
config: SandboxConfig,
) -> Result
```
The source runs as the body of an async IIFE in a fresh, fully fenced sandbox: top-level `return` produces the result, `undefined` maps to `null`, and `await` is tolerated but only microtask-resolvable promises settle (there is no event loop; a promise waiting on timers or IO reports `PendingPromise`). Capabilities appear as plain global functions. Errors are attributed to the pseudo-tool name `RUN_JS_TOOL_NAME`; a syntax error surfaces as `ExecError::Js` so a generating model can repair the script.
## Capabilities
A `Capability` is an async Rust function injected into the sandbox as a global JS function: the only doorway out. From JavaScript the call looks synchronous (`const rows = query({q: "..."})`); the executor bridges it onto the host Tokio runtime and blocks the sandbox thread until it resolves. `Err(String)` from the handler surfaces to JS as a catchable exception.
| Constructor | Signature | What it does |
| -------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Capability::new` | `(name, description, f)` where `f: Fn(Value) -> Future