Skip to main content

ExtractionMetadata

Struct ExtractionMetadata 

Source
#[non_exhaustive]
pub struct ExtractionMetadata { pub mode: ExtractionMode, pub passes: u32, pub repaired: bool, pub enforcement: SchemaEnforcement, pub degradations: Vec<Warning>, pub usage: Option<Usage>, pub auto_fallback: Option<AutoFallback>, pub undeclared_key_rejections: u32, }
Available on crate feature extract only.
Expand description

How an extraction ran: its mode and the record of its passes.

Reported on success (Extracted::metadata) and on failure (ExtractFailure::metadata).

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§mode: ExtractionMode

The mode that was used.

§passes: u32

Number of provider calls made by the extraction (1 plus retries).

0 when it failed before calling the provider, and for Extractor::parse, which parses a response the caller already has. A call that failed with a provider error returned no response and is not counted (see from_error), even a stream that failed mid-way, whose usage so far is still in usage.

§repaired: bool

The value was parsed after local repair.

§enforcement: SchemaEnforcement

How far the provider reported constraining the output to the schema of T, from the warnings it reported on the field the mode relies on (see SchemaEnforcement and the module docs). The least enforced pass wins.

This reflects the adapter’s own report, not a verified grammar guarantee. NotEnforced when no pass was made, including for Extractor::parse, which cannot know what the request asked for.

§degradations: Vec<Warning>

The warnings counted for enforcement, from every pass and from a stream that failed mid-way, each distinct warning once: the warnings about the response format (RequestField::ResponseFormat) in Native mode, or about the tools (RequestField::Tools) in ForcedTool mode.

The response keeps every warning (ChatResponse::warnings), including those about other fields, which are not counted.

§usage: Option<Usage>

Token usage summed over every pass, including the passes whose output could not be used (see Usage’s Add). None when nothing reported usage.

It also holds the usage a stream reported before it failed mid-way (ExtractionStream::finish). That stream returned no response and is not a pass, so the record of a failed stream can pair passes 0 with billed usage.

§auto_fallback: Option<AutoFallback>

The refusal that made an Auto extraction switch from native output to forced-tool mode, when it did (see the module docs). mode is then ForcedTool.

The refused attempt sent nothing and is not counted in passes.

§undeclared_key_rejections: u32

How many passes were rejected for a key the schema of T does not declare (see undeclared keys), whether the extraction asked again or failed. Each one asked again is a billed pass, so this is the cost of the check.

Implementations§

Source§

impl ExtractionMetadata

Source

pub fn new(mode: ExtractionMode) -> Self

The record of an extraction in mode that has made no provider calls yet.

Source

pub fn from_error(error: &Error) -> Option<Self>

The pass record attached to a provider error that ended an extraction.

Extraction returns provider errors unchanged (so Error::is_retryable, Error::retry_after and the variant stay what the provider reported) and attaches the record of the passes made before the error to its context, under allama.extraction in ErrorContext::metadata. It is attached on every provider error from ExtractExt::extract, ExtractExt::extract_stream, ExtractionStream::finish and the Extractor methods, including one on the first call (passes 0). For an error that ended a failover it is on that error’s own context, not on the errors it fell back from.

None when the error carries no record: it did not come from an extraction, or its variant has no context (Error::Serialization). An Error::Extract carries its record in ExtractFailure::metadata instead.

use allama::extract::{ExtractionMetadata, ExtractionMode, Extractor};
use allama::mock::{ChatResponseBuilder, MockProvider};
use allama::schemars::{self, JsonSchema};
use allama::{ChatRequest, Error};

#[derive(Debug, serde::Deserialize, JsonSchema)]
struct Person {
    name: String,
}

let provider = MockProvider::build(|b| {
    b.response(ChatResponseBuilder::new().text("not json").usage(500, 50).build())
        .error(Error::rate_limited("slow down"))
});
let request = ChatRequest::new("m")
    .user("Ada wrote the first program.")
    .with_option(ExtractionMode::Native);
let error = Extractor::new()
    .retries(1)
    .extract::<_, Person>(&provider, &request)
    .await
    .unwrap_err();
assert!(matches!(error, Error::RateLimited { .. })); // not reclassified
let metadata = ExtractionMetadata::from_error(&error).unwrap();
assert_eq!(metadata.passes, 1);
assert_eq!(metadata.usage.and_then(|u| u.input_tokens), Some(500));

Trait Implementations§

Source§

impl Clone for ExtractionMetadata

Source§

fn clone(&self) -> Self

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 ExtractionMetadata

Shows the mode, passes and enforcement, and the other fields when they are set.

Source§

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

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

impl<'de> Deserialize<'de> for ExtractionMetadata

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 Eq for ExtractionMetadata

Source§

impl PartialEq for ExtractionMetadata

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for ExtractionMetadata

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
Source§

impl StructuralPartialEq for ExtractionMetadata

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<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> 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 = !

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

fn try_from(value: U) -> Result<T, !>

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