Skip to main content

GenerationConfig

Struct GenerationConfig 

Source
pub struct GenerationConfig {
    pub temperature: Option<f64>,
    pub max_tokens: Option<i32>,
    pub top_p: Option<f64>,
    pub top_k: Option<i32>,
    pub stop_sequences: Option<Vec<String>>,
    pub json_mode: Option<bool>,
    pub json_schema: Option<Value>,
    pub max_tool_rounds: Option<usize>,
    pub prompt_caching: Option<bool>,
}
Expand description

Configuration for text generation.

Every field is optional; unset fields are simply omitted from the provider request, so the provider default applies.

§Examples

use rai_sdk::{GenerationConfig, JsonSchema};
use serde::Deserialize;

#[derive(Deserialize, JsonSchema)]
#[schemars(crate = "rai_sdk::schemars")]
struct Summary {
    headline: String,
    bullets: Vec<String>,
}

// Free-form generation.
let creative = GenerationConfig::new().with_temperature(0.9);

// Schema-constrained generation derived from a Rust type.
let strict = GenerationConfig::new()
    .with_temperature(0.0)
    .with_json_schema_for::<Summary>()?;

Fields§

§temperature: Option<f64>

Temperature for sampling (0.0 to 2.0 typically).

§max_tokens: Option<i32>

Maximum number of tokens to generate.

§top_p: Option<f64>

Top-p (nucleus) sampling.

§top_k: Option<i32>

Top-k sampling (not supported by all providers).

§stop_sequences: Option<Vec<String>>

Stop sequences.

§json_mode: Option<bool>

Whether to request JSON output (provider-dependent).

§json_schema: Option<Value>

JSON Schema for structured output (provider-dependent).

§max_tool_rounds: Option<usize>

Maximum number of tool execution rounds before failing.

§prompt_caching: Option<bool>

Whether Anthropic prompt caching is enabled.

Implementations§

Source§

impl GenerationConfig

Source

pub fn new() -> Self

Start with an empty config — add only the overrides you need.

Source

pub fn with_temperature(self, temperature: f64) -> Self

Set the sampling temperature. Higher values are more random.

Ignored for OpenAI reasoning (o-series) models, which do not accept it.

Source

pub fn with_max_tokens(self, max_tokens: i32) -> Self

Cap the number of tokens the model may generate.

Source

pub fn with_top_p(self, top_p: f64) -> Self

Set nucleus (top-p) sampling.

Ignored for OpenAI reasoning (o-series) models.

Source

pub fn with_top_k(self, top_k: i32) -> Self

Set top-k sampling. Only sent to providers that support it.

Source

pub fn with_stop_sequences(self, stop_sequences: Vec<String>) -> Self

Stop generating as soon as one of these sequences is produced.

Source

pub fn with_json_mode(self, json_mode: bool) -> Self

Ask the provider for syntactically valid JSON without constraining its shape.

A JSON schema set through GenerationConfig::with_json_schema or GenerationConfig::with_json_schema_for takes precedence over this flag.

Source

pub fn with_json_schema(self, json_schema: Value) -> Self

Constrain the response with a hand-written JSON Schema.

Prefer GenerationConfig::with_json_schema_for when the shape is already expressed as a Rust type.

Source

pub fn with_json_schema_for<T>(self) -> Result<Self>
where T: JsonSchema,

Generate a JSON Schema from a Rust type and normalize object schemas for strict structured-output providers.

The schema is generated with inline_subschemas = true and no top-level "$schema" key, so non-recursive nested types are inlined directly rather than emitting "$defs"/"$ref". This matters because Gemini’s generation_config.response_schema (reachable in this SDK through the OpenRouter provider) rejects schemas containing "$schema", "$defs", or "$ref" keys with a 400 INVALID_ARGUMENT error. See the crate-internal schema normalizer’s documentation for the limits of this approach with recursive types.

§Errors

Returns Error::Serialization if the schema generated for T cannot be converted to a JSON value.

Source

pub fn with_max_tool_rounds(self, max_tool_rounds: usize) -> Self

Limit how many request/tool-execution rounds a single generate() call may run before failing with Error::ToolLoopLimitExceeded.

Source

pub fn with_prompt_caching(self, enabled: bool) -> Self

Enable or disable Anthropic prompt caching for this request.

When enabled, Anthropic requests mark the system prompt and the final tool definition as ephemeral cache breakpoints. Other providers silently ignore this setting.

§Examples
use rai_sdk::GenerationConfig;

let config = GenerationConfig::new().with_prompt_caching(true);
assert_eq!(config.prompt_caching, Some(true));
Source

pub fn tool_round_limit(&self) -> usize

The effective maximum number of tool-calling rounds (defaults to 8).

Trait Implementations§

Source§

impl Clone for GenerationConfig

Source§

fn clone(&self) -> GenerationConfig

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for GenerationConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for GenerationConfig

Source§

fn default() -> GenerationConfig

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for GenerationConfig

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for GenerationConfig

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more