Skip to main content

rig_agent/
extractor.rs

1//! Typed extraction through an agent's `submit` output tool, with configurable retries.
2//!
3//! ```no_run
4//! use rig_agent::extractor::ExtractorBuilder;
5//! use rig_core::{Model, providers::openai::{self, OpenAI}};
6//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
7//! #[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
8//! struct Person { name: String, age: u8 }
9//! let model = OpenAI::from_env()?.completion(openai::GPT_4O);
10//! let extractor = ExtractorBuilder::<Person>::new(model).retries(2).build();
11//! let person = extractor.extract("John is 30.").await?.output;
12//! # Ok(())
13//! # }
14//! ```
15
16use std::marker::PhantomData;
17
18use schemars::JsonSchema;
19use serde::de::DeserializeOwned;
20
21use rig_core::{
22    message::{Message, ToolChoice},
23    vector_store::{VectorStoreIndex, request::DynamicSearchFilter},
24    wasm_compat::{WasmCompatSend, WasmCompatSync},
25};
26
27use crate::agent::{Agent, AgentBuilder, AgentHook, OutputMode, TypedRun};
28
29const SUBMIT_TOOL_NAME: &str = "submit";
30
31/// An agent configured for structured extraction: every [`extract`](Self::extract)
32/// is a one-call [`TypedRun`] in output-tool mode with this extractor's retry
33/// budget.
34pub struct Extractor<T>
35where
36    T: JsonSchema + DeserializeOwned + WasmCompatSend + WasmCompatSync,
37{
38    agent: Agent,
39    retries: usize,
40    _t: PhantomData<T>,
41}
42
43impl<T> Extractor<T>
44where
45    T: JsonSchema + DeserializeOwned + WasmCompatSend + WasmCompatSync,
46{
47    /// Extract structured data from `text`.
48    ///
49    /// The returned run supports history, a per-run model, and retry overrides,
50    /// and can be awaited for a
51    /// [`TypedPromptResponse<T>`](crate::agent::TypedPromptResponse). The
52    /// model must call the `submit` tool; a run in which it does not is an
53    /// empty response and, within the retry budget, is retried from scratch.
54    /// Usage accumulates across attempts, including attempts that received a
55    /// billed response but failed extraction; attempts whose completion call
56    /// itself errored contribute no usage.
57    pub fn extract(&self, text: impl Into<Message>) -> TypedRun<T> {
58        let runner = self.agent.prompt(text).max_turns(1).output_tool(
59            SUBMIT_TOOL_NAME,
60            "Submit the structured data you extracted from the provided text.",
61            false,
62        );
63        TypedRun::output_tool(runner).retries(self.retries)
64    }
65}
66
67/// Builder for the Extractor
68pub struct ExtractorBuilder<T>
69where
70    T: JsonSchema + DeserializeOwned + WasmCompatSend + WasmCompatSync + 'static,
71{
72    agent_builder: AgentBuilder,
73    _t: PhantomData<T>,
74    retries: usize,
75}
76
77/// Generate setters forwarding to the matching inner [`AgentBuilder`] methods.
78macro_rules! forward_agent_builder {
79    ($( $(#[$attr:meta])* $name:ident $([$gen:ident : $($bound:tt)+])?
80        ( $($arg:ident : $ty:ty),* );)+) => {$(
81        $(#[$attr])*
82        pub fn $name $(<$gen>)? (mut self, $($arg: $ty),*) -> Self
83        $(where $gen: $($bound)+)?
84        {
85            self.agent_builder = self.agent_builder.$name($($arg),*);
86            self
87        }
88    )+};
89}
90
91impl<T> ExtractorBuilder<T>
92where
93    T: JsonSchema + DeserializeOwned + WasmCompatSend + WasmCompatSync + 'static,
94{
95    /// An extractor of `T` over `model`.
96    pub fn new(model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>) -> Self {
97        Self::from_agent_builder(AgentBuilder::new(model))
98    }
99
100    /// Configure an agent builder for extraction of `T`, replacing its preamble,
101    /// output schema, tool choice, and output mode. The tool choice is always
102    /// [`ToolChoice::Required`], since an extraction is one turn that must call
103    /// the `submit` tool.
104    pub fn from_agent_builder(builder: AgentBuilder) -> Self {
105        Self {
106            agent_builder: builder
107                .preamble("\
108                    You are an AI assistant whose purpose is to extract structured data from the provided text.\n\
109                    You will have access to a `submit` function that defines the structure of the data to extract from the provided text.\n\
110                    Use the `submit` function to submit the structured data.\n\
111                    Be sure to fill out every field and ALWAYS CALL THE `submit` function, even with default values!!!.
112                ")
113                .output_schema::<T>()
114                .tool_choice(ToolChoice::Required)
115                .output_mode(OutputMode::Tool),
116            retries: 0,
117            _t: PhantomData,
118        }
119    }
120
121    /// Append instructions to the extractor's preamble. The extraction
122    /// preamble itself is fixed (it tells the model to call the output
123    /// tool); this adds to it, as [`AgentBuilder::append_preamble`] does,
124    /// and never replaces it.
125    pub fn append_preamble(mut self, preamble: &str) -> Self {
126        self.agent_builder = self.agent_builder.append_preamble(&format!(
127            "\n=============== ADDITIONAL INSTRUCTIONS ===============\n{preamble}"
128        ));
129        self
130    }
131
132    forward_agent_builder! {
133        /// Add a context document to the extractor
134        context(doc: &str);
135
136        /// Set provider-specific parameters for every extraction attempt.
137        additional_params(params: serde_json::Value);
138
139        /// Set the maximum number of tokens for the completion
140        max_tokens(max_tokens: u64);
141
142        /// Add a provider-independent lifecycle hook to every extraction attempt.
143        ///
144        /// Completion-response hooks receive canonical Rig content, usage, prompt,
145        /// and identity fields, just like hooks attached directly to an agent.
146        add_hook[H: AgentHook + 'static](hook: H);
147    }
148
149    /// Retrieve `samples` documents from `index` for every extraction.
150    ///
151    /// This delegates to [`AgentBuilder::dynamic_context`] and therefore uses
152    /// the same completion-call hook lifecycle as an agent.
153    pub fn dynamic_context<I, F>(mut self, samples: usize, index: I) -> Self
154    where
155        I: VectorStoreIndex<Filter = F> + 'static,
156        F: DynamicSearchFilter + WasmCompatSend + WasmCompatSync + 'static,
157    {
158        self.agent_builder = self.agent_builder.dynamic_context(samples, index);
159        self
160    }
161
162    /// Set the maximum number of retries for the extractor.
163    pub fn retries(mut self, retries: usize) -> Self {
164        self.retries = retries;
165        self
166    }
167
168    /// Build the Extractor
169    pub fn build(self) -> Extractor<T> {
170        Extractor {
171            agent: self.agent_builder.build(),
172            _t: PhantomData,
173            retries: self.retries,
174        }
175    }
176}
177
178#[cfg(test)]
179mod tests;