Expand description
Provider-agnostic model, message, conversation, tool, and vector-store contracts.
Provider configurations build endpoint wires, and a Model binds a
wire to a driver::Transport; a DynModel is a model erased to
its operation, for consumers that store one. Companion crates supply
transports, agent runtimes, and external storage integrations.
rig-core does not force serde_json’s preserve_order or float_roundtrip.
Without them, schema properties and JSON text in prompts, embeddings and
tool results use sorted object keys, and parsed floats can differ in their
low bits. Restore the previous configuration in your application’s
dependencies with
serde_json = { version = "1", features = ["preserve_order", "float_roundtrip"] }.
Cargo unifies these features: rig-cassette with traffic (including
rig-traffic) enables both; rig-claude-cloak, rig-mcp-client and
rig-mongodb through BSON enable preserve_order. Rig has no forwarding feature for either setting.
use rig_core::DynModel;
use rig_core::completion::{CompletionRequest, CompletionResponse};
use rig_core::error::ProviderError;
use rig_core::operation::Completion;
async fn ask(model: &DynModel<Completion>) -> Result<CompletionResponse, ProviderError> {
let request = CompletionRequest::new("Who are you?");
model.call(request).await
}Re-exports§
pub use completion::message;pub use driver::DynModel;pub use driver::Model;pub use embeddings::Embed;pub use error::ErrorKind;pub use error::ErrorReport;pub use error::ProviderError;pub use schemars;pub use serde;pub use serde_json;
Modules§
- audio_
generation audio - Text-to-speech requests and normalized audio responses.
- catalog
- Model facts by provider and model id: limits, input modalities, reasoning, caching, prices.
- client
- Provider clients and environment configuration helpers. A provider’s
client (such as
crate::providers::openai::OpenAI) puts its configuration on a transport and builds the models it serves; each is re-exported from its provider module. - completion
- Provider-agnostic completion requests and responses. A provider’s wire
translates
CompletionRequestinto its own request and normalizes the reply asCompletionResponse; aModelsends it. - conversation
- One conversation model for all of rig:
Conversation, its edits asChanges,TurnRecords kept as asides, andpairingof tool calls with their results. - driver
- Calls a model. A
Modelpairs aWire(what to send and how to read the reply) with aTransport(how the payload travels). Itsstreamyields any operation’s events as aStreamed, and itscallis that stream, finished: one decoder, one fold and one response constructor for both. The_observedtwins take the observation context a recorder records under. - effect
- Serializable effect requests, handler descriptions, outcomes, and recording data.
HandlerKeyidentifies a destination;EffectKindandAnswereddescribe the exchange. Host-defined operations useCustomEffect. - embeddings
- Provider-agnostic embedding abstractions.
- error
- The provider error type, serializable error reports, and shared retry classifications for the effect protocol. Reports preserve classifications, available provider metadata, and textual source chains.
- http_
client - Transport-independent HTTP requests, lazy response bodies, and errors.
- id
- Non-cryptographic random identifiers, process-local run counters, and caller-supplied conversation keys. Do not use generated IDs as secrets.
- image_
generation image - Image-generation requests, normalized responses, and model interfaces.
- loaders
- Local document loaders for model and embedding input, with optional error skipping.
FileLoaderreads paths or bytes. Thepdfandepubfeatures enable extraction by page or chapter with source numbering. - markers
- Missing and provided states for type-safe builders.
- model
- Model metadata returned by providers with model listing support.
- observe
- Typed runtime and policy observations, separate from effect replay records.
Witnessreceives facts andObservationLogretains a bounded trace. Optional timestamps come from a host-suppliedClock, not replay identity. - operation
- The operations a
Wirecan perform. - prelude
- Common model-construction, completion, embedding, tool, and vector-store imports.
- providers
- Provider clients, their configurations, and model identifiers.
- redact
- Finding and redacting secrets in text a host logs, shows or shares: API keys and tokens by their known shapes, private key blocks, and values assigned to secret-named variables.
- rerank
- Provider-agnostic reranking abstractions.
- serve
- Handlers return a
Reply: an outcome or an owned stream.Dispatchcarries identity, requested delivery mode and scopes.ErasedHandleris the shared registry boundary; drivers own polling and cancellation. Provider and tool authors retain their domain traits throughadapters.Reply::writtenoffers a writer that mints stream block identities. - streaming
- Completion events, and
Streamed, the one stream every reply arrives as. - structured_
output - Model-facing structured-output policy shared by the agent runtimes: the synthetic output tool’s name and description, the instructions and reprompts the model sees, and the required-field check on an answer.
- telemetry
- GenAI tracing spans, completion-parent adoption, and opt-in content recording.
- test_
utils test-utils - Test utilities for deterministic completion-model tests.
- tool
- Tool authoring contracts, dispatch context, and canonical execution values.
Toolis the tool trait; each call gets aToolContext. - transcription
- Audio transcription requests, normalized responses, and model interfaces.
- vector_
store - Vector-store insertion and similarity-search interfaces.
VectorStoreIndeximplementations also implementToolwhen their filter is deserializable and uses JSON values. - wasm_
compat - Target-dependent thread bounds, boxed futures, and executor-independent timers.
- wire
- Operations, provider wires and their decoders. An
Operationnames what goes in, what comes out event by event and what ends a reply, and itsFoldturns one reply’s events and end into the response. AWiredescribes a provider endpoint as plain data, encodes requests without transport access, and names a freshDecoderfor each reply. A decoder is told nothing about how the reply arrives, so buffered and streamed replies go through the same decoder and fold. - ws_
client websocket - Transport-independent websocket handshakes, connections, and frames. Backends preserve rejected upgrades as HTTP errors with status, headers, and body.
Macros§
- completion_
parent_ span - Declares a completion-parent span with the marker and all required fields.
Defaults to the current span as parent. An optional
parent: <expr>betweentargetandnameaccepts any parent supported bytracing::info_span!, includingNone. - streaming_
conformance_ suite test-utilsand not (target_os=unknownand WebAssembly)
Structs§
- Provider
Response Error - A raw provider error body with captured transport metadata.
Callers must supply the provider’s actual payload, not a generated diagnostic.
Serialization omits headers and route; deserialization restores them as
None.
Functions§
- millis
- Milliseconds since the Unix epoch at
at, also on the web; 0 before it. - now_ms
- Milliseconds since the Unix epoch, also on the web.
Attribute Macros§
- rig_
tool derive - Generates a tool type, parameter struct, and uppercase static from a function
returning
Result<T, E>, implementingrig_core::tool::Tool. The function may take the call’s&mut ToolContext. Imported context names need#[rig(context)]; qualified Rig paths are recognized directly. The context is excluded from model arguments.
Derive Macros§
- Context
Value derive - Derives
rig_core::tool::ContextValuewith the type name as its default key.#[context(key = "...")]overrides the key. The type must support serde serialization and deserialization. - Embed
derive - Derives
rig_core::embeddings::Embedusing fields marked with#[embed].