1use std::marker::PhantomData;
17
18use schemars::JsonSchema;
19use serde::{Serialize, 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, ModelRef, OutputMode, TypedRun};
28
29const SUBMIT_TOOL_NAME: &str = "submit";
30
31pub 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 pub fn with_model_label(mut self, label: impl Into<ModelRef>) -> Self {
50 self.agent.set_model_label(label);
51 self
52 }
53
54 pub fn with_model(
56 mut self,
57 model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>,
58 ) -> Self {
59 self.agent.set_model(model);
60 self
61 }
62
63 pub fn agent(&self) -> &Agent {
65 &self.agent
66 }
67
68 pub fn extract(&self, text: impl Into<Message>) -> TypedRun<T> {
79 let runner = self.agent.prompt(text).max_turns(1).output_tool(
80 SUBMIT_TOOL_NAME,
81 "Submit the structured data you extracted from the provided text.",
82 false,
83 );
84 TypedRun::output_tool(runner).retries(self.retries)
85 }
86}
87
88pub struct ExtractorBuilder<T>
90where
91 T: JsonSchema + DeserializeOwned + Serialize + WasmCompatSend + WasmCompatSync + 'static,
92{
93 agent_builder: AgentBuilder,
94 _t: PhantomData<T>,
95 retries: Option<usize>,
96}
97
98macro_rules! forward_agent_builder {
100 ($( $(#[$attr:meta])* $name:ident $([$gen:ident : $($bound:tt)+])?
101 ( $($arg:ident : $ty:ty),* );)+) => {$(
102 $(#[$attr])*
103 pub fn $name $(<$gen>)? (mut self, $($arg: $ty),*) -> Self
104 $(where $gen: $($bound)+)?
105 {
106 self.agent_builder = self.agent_builder.$name($($arg),*);
107 self
108 }
109 )+};
110}
111
112impl<T> ExtractorBuilder<T>
113where
114 T: JsonSchema + DeserializeOwned + Serialize + WasmCompatSend + WasmCompatSync + 'static,
115{
116 pub fn new(model: impl Into<rig_core::DynModel<rig_core::operation::Completion>>) -> Self {
118 Self::from_agent_builder(AgentBuilder::new(model))
119 }
120
121 pub fn from_agent_builder(builder: AgentBuilder) -> Self {
126 Self {
127 agent_builder: builder
128 .preamble("\
129 You are an AI assistant whose purpose is to extract structured data from the provided text.\n\
130 You will have access to a `submit` function that defines the structure of the data to extract from the provided text.\n\
131 Use the `submit` function to submit the structured data.\n\
132 Be sure to fill out every field and ALWAYS CALL THE `submit` function, even with default values!!!.
133 ")
134 .output_schema::<T>()
135 .tool_choice(ToolChoice::Required)
136 .output_mode(OutputMode::Tool),
137 retries: None,
138 _t: PhantomData,
139 }
140 }
141
142 pub fn append_preamble(mut self, preamble: &str) -> Self {
147 self.agent_builder = self.agent_builder.append_preamble(&format!(
148 "\n=============== ADDITIONAL INSTRUCTIONS ===============\n{preamble}"
149 ));
150 self
151 }
152
153 forward_agent_builder! {
154 context(doc: &str);
156
157 additional_params(params: serde_json::Value);
159
160 max_tokens(max_tokens: u64);
162
163 add_hook[H: AgentHook + 'static](hook: H);
168 }
169
170 pub fn dynamic_context<I, F>(mut self, samples: usize, index: I) -> Self
175 where
176 I: VectorStoreIndex<Filter = F> + 'static,
177 F: DynamicSearchFilter + WasmCompatSend + WasmCompatSync + 'static,
178 {
179 self.agent_builder = self.agent_builder.dynamic_context(samples, index);
180 self
181 }
182
183 pub fn retries(mut self, retries: usize) -> Self {
185 self.retries = Some(retries);
186 self
187 }
188
189 pub fn build(self) -> Extractor<T> {
191 Extractor {
192 agent: self.agent_builder.build(),
193 _t: PhantomData,
194 retries: self.retries.unwrap_or(0),
195 }
196 }
197}
198
199#[cfg(test)]
200mod tests;