#[non_exhaustive]pub struct CompletionRequest {Show 13 fields
pub model: Option<String>,
pub chat_history: Vec<Message>,
pub documents: Vec<Document>,
pub tools: Vec<ToolDefinition>,
pub temperature: Option<f64>,
pub max_tokens: Option<u64>,
pub tool_choice: Option<ToolChoice>,
pub additional_params: Option<Value>,
pub output_schema: Option<Schema>,
pub record_telemetry_content: bool,
pub accept_unknown_finish_reasons: bool,
pub options: GenerationOptions,
pub provider_options: ProviderOptions,
}Expand description
Struct representing a general completion request that can be sent to a completion model provider.
Fields (Non-exhaustive)§
This struct is marked as non-exhaustive
Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.model: Option<String>Optional model override for this request.
chat_history: Vec<Message>The chat history to be sent to the completion model provider. The very last message is the prompt.
It must hold at least one message, and every user and assistant
message must carry content. The field is public, so this is a rule
rather than a type guarantee: Self::validate_message_content
checks it at the request boundary.
documents: Vec<Document>The documents to be sent to the completion model provider
tools: Vec<ToolDefinition>The tools to be sent to the completion model provider
temperature: Option<f64>The temperature to be sent to the completion model provider
max_tokens: Option<u64>The max tokens to be sent to the completion model provider
tool_choice: Option<ToolChoice>Whether tools are required to be used by the model provider or not before providing a response.
additional_params: Option<Value>Additional provider-specific parameters to be sent to the completion model provider
output_schema: Option<Schema>Optional JSON Schema for structured output. When set, providers that support native structured outputs will constrain the model’s response to match this schema.
record_telemetry_content: boolOpt-in for sensitive request, response, and tool-content telemetry.
Defaults to false and is excluded from serialization. Enabling it can
expose prompts, context, tool results, and model output in span attributes
and increase telemetry storage costs. Requires explicit caller consent.
Agent drivers record normalized content; direct provider coverage varies,
especially for streams consumed after the provider returns.
accept_unknown_finish_reasons: boolWhether a finish reason outside the normalized vocabulary
(FinishReason::Other) ends the turn as a normal stop instead of a
failure. Defaults to false. The response carries the choice, so its
CompletionResponse::stop, the runtimes and history replay agree.
Other also holds genuine failures, such as a malformed tool call or a
recitation block, so with this set the tool calls of such a reply run.
FinishReason::ContentFilter still fails the turn.
options: GenerationOptionsPortable generation options. Precedence, lowest first: the mapped
options, then Self::provider_options, then additional_params.
provider_options: ProviderOptionsTyped per-provider options. The wire reads only the entry of its own
provider, above the mapped options and below additional_params.
Implementations§
Source§impl CompletionRequest
impl CompletionRequest
Sourcepub fn system_instructions(&self) -> Option<&str>
pub fn system_instructions(&self) -> Option<&str>
The system instructions of this request: the content of the leading
Message::System in chat_history, which is where
Self::preamble places it.
Sourcepub fn validate_message_content(&self) -> Result<(), ProviderError>
pub fn validate_message_content(&self) -> Result<(), ProviderError>
Reject a request with no messages, a user or assistant message with no
content, or a tool result with no content blocks. The error is
ProviderError::Request and names the role and index of the first
offending message.
Every wire rejects an empty turn, so this turns a remote 400 into a
local error. It checks the request direction only: a provider may
return empty assistant content, which the reply keeps and the
runtime judges. System content is a
String and is not checked. A tool result holding one empty text
block is not empty.
Model::call,
Model::stream and their _observed
twins run it before encoding, so it covers
DynModel, every model the bus serves and the
agent runtimes built on them. The OpenAI Responses websocket session
sends without the driver and runs it on each send. Code that encodes
a request some other way should call it first.
Sourcepub fn output_schema_name(&self) -> Option<String>
pub fn output_schema_name(&self) -> Option<String>
Extracts a name from the output schema’s "title" field, falling back to "response_schema".
Useful for providers that require a name alongside the JSON Schema (e.g., OpenAI).
Sourcepub fn normalized_documents(&self) -> Option<Message>
pub fn normalized_documents(&self) -> Option<Message>
Returns documents normalized into a message (if any).
Most providers do not accept documents directly as input, so it needs to convert into a
Message so that it can be incorporated into chat_history.
Source§impl CompletionRequest
impl CompletionRequest
Sourcepub fn new(prompt: impl Into<Message>) -> Self
pub fn new(prompt: impl Into<Message>) -> Self
A request whose conversation is the one user message prompt, with
no preamble, documents or tools. The setters below add to it and
check nothing; Self::validate_message_content checks the content
when the request is sent.
Each setter changes the request’s public fields as it is called, so
order matters where two setters touch the same field: a second
Self::preamble adds a second system message, and
Self::additional_params with a tools key (or None) replaces
provider tools added before it. Set additional_params first.
use rig_core::completion::CompletionRequest;
let request = CompletionRequest::new("Who are you?")
.preamble("You are a concise assistant.")
.temperature(0.5);
assert_eq!(request.chat_history.len(), 2);
assert_eq!(request.temperature, Some(0.5));Sourcepub fn preamble(self, preamble: impl Into<String>) -> Self
pub fn preamble(self, preamble: impl Into<String>) -> Self
Put preamble first in the conversation, as a Message::System,
ahead of any system message already there.
Sourcepub fn model<S: Into<String>>(self, model: impl Into<Option<S>>) -> Self
pub fn model<S: Into<String>>(self, model: impl Into<Option<S>>) -> Self
Override the model for this request.
Sourcepub fn message(self, message: Message) -> Self
pub fn message(self, message: Message) -> Self
Add message to the conversation, before the prompt (its last
message).
Sourcepub fn messages(self, messages: impl IntoIterator<Item = Message>) -> Self
pub fn messages(self, messages: impl IntoIterator<Item = Message>) -> Self
Add messages to the conversation in order, before the prompt (its
last message).
Sourcepub fn documents(self, documents: impl IntoIterator<Item = Document>) -> Self
pub fn documents(self, documents: impl IntoIterator<Item = Document>) -> Self
Add documents in order.
Sourcepub fn tool(self, tool: ToolDefinition) -> Self
pub fn tool(self, tool: ToolDefinition) -> Self
Add a tool.
Sourcepub fn tools(self, tools: Vec<ToolDefinition>) -> Self
pub fn tools(self, tools: Vec<ToolDefinition>) -> Self
Add tools in order.
Sourcepub fn provider_tool(self, tool: ProviderToolDefinition) -> Self
pub fn provider_tool(self, tool: ProviderToolDefinition) -> Self
Add a provider-hosted tool: appended to additional_params.tools,
so a later Self::additional_params with a tools key replaces
it.
Sourcepub fn provider_tools(self, tools: Vec<ProviderToolDefinition>) -> Self
pub fn provider_tools(self, tools: Vec<ProviderToolDefinition>) -> Self
Add provider-hosted tools in order: appended to
additional_params.tools.
Sourcepub fn additional_params(
self,
additional_params: impl Into<Option<Value>>,
) -> Self
pub fn additional_params( self, additional_params: impl Into<Option<Value>>, ) -> Self
Merge provider-specific parameters into the request’s, key by key;
None clears them, provider tools included. Provider conversion determines precedence over typed fields,
and a key that overrides a typed field this request sets is logged.
Sourcepub fn temperature(self, temperature: impl Into<Option<f64>>) -> Self
pub fn temperature(self, temperature: impl Into<Option<f64>>) -> Self
Set, or with None clear, the temperature.
Sourcepub fn max_tokens(self, max_tokens: impl Into<Option<u64>>) -> Self
pub fn max_tokens(self, max_tokens: impl Into<Option<u64>>) -> Self
Set, or with None clear, the output-token limit. Provider-specific
defaults and requirements apply.
Sourcepub fn tool_choice(self, tool_choice: ToolChoice) -> Self
pub fn tool_choice(self, tool_choice: ToolChoice) -> Self
Set the tool-selection policy.
Sourcepub fn output_schema(self, schema: impl Into<Option<Schema>>) -> Self
pub fn output_schema(self, schema: impl Into<Option<Schema>>) -> Self
Set, or with None clear, a native structured-output schema for
providers that support one. The returned content is not
deserialized.
Sourcepub fn record_content_telemetry(self, enabled: bool) -> Self
pub fn record_content_telemetry(self, enabled: bool) -> Self
Opt in to sensitive content telemetry, off by default. See
Self::record_telemetry_content for what that exposes.
Sourcepub fn accept_unknown_finish_reasons(self, accept: bool) -> Self
pub fn accept_unknown_finish_reasons(self, accept: bool) -> Self
Accept, or with false refuse, finish reasons outside the normalized
vocabulary as a normal stop. See
Self::accept_unknown_finish_reasons for what that lets through.
Sourcepub fn options(self, options: GenerationOptions) -> Self
pub fn options(self, options: GenerationOptions) -> Self
Replace the portable generation options with options, a reusable
value. Calls apply in order: this replaces every field, so a
shortcut such as Self::seed called before it is lost, and one
called after it sets its one field on top.
use rig_core::completion::{CompletionRequest, Effort, GenerationOptions};
let shared = GenerationOptions::new().reasoning(Effort::High).seed(1);
let request = CompletionRequest::new("hi").seed(7).options(shared.clone()).seed(2);
assert_eq!(request.options, shared.seed(2));Sourcepub fn reasoning(self, reasoning: impl Into<Reasoning>) -> Self
pub fn reasoning(self, reasoning: impl Into<Reasoning>) -> Self
Set the reasoning level or budget in Self::options, as
GenerationOptions::reasoning does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn cache(self, cache: CacheRetention) -> Self
pub fn cache(self, cache: CacheRetention) -> Self
Set the cache retention in Self::options, as
GenerationOptions::cache does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn service_tier(self, tier: ServiceTier) -> Self
pub fn service_tier(self, tier: ServiceTier) -> Self
Set the service tier in Self::options, as
GenerationOptions::service_tier does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn verbosity(self, verbosity: Verbosity) -> Self
pub fn verbosity(self, verbosity: Verbosity) -> Self
Set the answer verbosity in Self::options, as
GenerationOptions::verbosity does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn parallel_tool_calls(self, parallel: bool) -> Self
pub fn parallel_tool_calls(self, parallel: bool) -> Self
Set whether the model may call several tools in one turn in Self::options, as
GenerationOptions::parallel_tool_calls does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn top_p(self, top_p: f64) -> Self
pub fn top_p(self, top_p: f64) -> Self
Set the nucleus sampling probability mass in Self::options, as
GenerationOptions::top_p does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn seed(self, seed: u64) -> Self
pub fn seed(self, seed: u64) -> Self
Set the sampling seed in Self::options, as
GenerationOptions::seed does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn stop<S: Into<String>>(self, stop: impl IntoIterator<Item = S>) -> Self
pub fn stop<S: Into<String>>(self, stop: impl IntoIterator<Item = S>) -> Self
Set the stop sequences in Self::options, as
GenerationOptions::stop does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn on_unsupported(self, policy: OnUnsupported) -> Self
pub fn on_unsupported(self, policy: OnUnsupported) -> Self
Set what happens to an option the wire or model cannot honour in Self::options, as
GenerationOptions::on_unsupported does,
keeping its other fields. See
Self::options for the order of calls.
Sourcepub fn provider_options(self, options: ProviderOptions) -> Self
pub fn provider_options(self, options: ProviderOptions) -> Self
Replace the typed per-provider options.
Calls apply in order: this replaces every entry, so an entry set by
an earlier Self::provider_option is lost, and a later
Self::provider_option replaces its provider’s entry on top.
Sourcepub fn provider_option<O: ExtensionOptions>(self, options: O) -> Self
pub fn provider_option<O: ExtensionOptions>(self, options: O) -> Self
Store options as the entry of their provider
(ExtensionOptions::Ext), replacing that provider’s entry and
keeping every other, as ProviderOptions::set does. Options that
do not serialize fail the request’s encode.
The entry is always stored under O::Ext’s key, the built-in
provider the options type belongs to. A third-party provider whose
extension reuses a built-in options type (say OpenAiOptions for an
OpenAI-compatible gateway) must store them with
ProviderOptions::with::<P> instead, or its
wire never reads them.
use rig_core::completion::{CompletionRequest, ProviderOptions};
use rig_core::providers::openrouter::extension::{
OpenRouterExt, OpenRouterOptions, ProviderPreferences,
};
let request = CompletionRequest::new("hi").provider_option(
OpenRouterOptions::new().provider(ProviderPreferences::new().allow_fallbacks(false)),
);
assert!(request.provider_options.contains::<OpenRouterExt>());Sourcepub fn messages_for_telemetry(&self) -> Vec<Message>
pub fn messages_for_telemetry(&self) -> Vec<Message>
The input messages telemetry records: the conversation with the documents inserted after any leading system messages.
Trait Implementations§
Source§impl Clone for CompletionRequest
impl Clone for CompletionRequest
Source§impl Debug for CompletionRequest
impl Debug for CompletionRequest
Source§impl<'de> Deserialize<'de> for CompletionRequest
impl<'de> Deserialize<'de> for CompletionRequest
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl From<&str> for CompletionRequest
impl From<&str> for CompletionRequest
Source§impl From<Message> for CompletionRequest
impl From<Message> for CompletionRequest
Source§impl From<String> for CompletionRequest
impl From<String> for CompletionRequest
Source§impl From<Vec<Message>> for CompletionRequest
The conversation as given, ending with the prompt. An empty one fails
CompletionRequest::validate_message_content.
impl From<Vec<Message>> for CompletionRequest
The conversation as given, ending with the prompt. An empty one fails
CompletionRequest::validate_message_content.
Auto Trait Implementations§
impl Freeze for CompletionRequest
impl RefUnwindSafe for CompletionRequest
impl Send for CompletionRequest
impl Sync for CompletionRequest
impl Unpin for CompletionRequest
impl UnsafeUnpin for CompletionRequest
impl UnwindSafe for CompletionRequest
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more