ThreadRequestBuilder

Struct ThreadRequestBuilder 

Source
pub struct ThreadRequestBuilder { /* private fields */ }
Expand description

Builder for creating a thread with initial messages and metadata.

§Examples

use openai_ergonomic::{Builder};
use openai_ergonomic::builders::threads::{
    MessageAttachment, ThreadMessageBuilder, ThreadRequestBuilder,
};

let thread_request = ThreadRequestBuilder::new()
    .user_message("Summarise the attached doc")
    .message_builder(
        ThreadMessageBuilder::assistant("Sure, I'll reference it.")
            .attachment(MessageAttachment::for_file_search("file-xyz")),
    )
    .unwrap()
    .build()
    .unwrap();

assert!(thread_request.messages.is_some());

Implementations§

Source§

impl ThreadRequestBuilder

Source

pub fn new() -> Self

Create a new empty thread builder.

Examples found in repository?
examples/threads.rs (line 109)
85async fn main() -> Result<(), Box<dyn std::error::Error>> {
86    println!(" OpenAI Ergonomic - Comprehensive Threads Example\n");
87
88    // Initialize client from environment variables
89    println!(" Initializing OpenAI client...");
90    let client = match Client::from_env() {
91        Ok(c) => {
92            println!(" Client initialized successfully\n");
93            c.build()
94        }
95        Err(e) => {
96            eprintln!(" Failed to initialize client: {}", e);
97            eprintln!(" Make sure OPENAI_API_KEY is set");
98            return Ok(());
99        }
100    };
101
102    // Example 1: Create a simple thread
103    println!();
104    println!(" Example 1: Create Simple Thread");
105    println!("\n");
106
107    println!("Creating new thread...");
108
109    let builder = ThreadRequestBuilder::new();
110
111    println!("\n Note: This would create a real thread with your API key.");
112    println!("   Commented out to avoid accidental API calls.\n");
113
114    // Uncomment to actually create thread:
115    // match client.threads().create(builder).await {
116    //     Ok(thread) => {
117    //         println!(" Thread created successfully!");
118    //         println!("  Thread ID: {}", thread.id);
119    //         println!("  Created At: {}", thread.created_at);
120    //     }
121    //     Err(e) => {
122    //         eprintln!(" Failed to create thread: {}", e);
123    //     }
124    // }
125
126    // Simulate thread creation for demonstration
127    let demo_thread = ThreadInfo::new("thread_demo123");
128    println!(" Demo Thread Created:");
129    demo_thread.display();
130
131    // Example 2: Create thread with metadata
132    println!("\n");
133    println!(" Example 2: Create Thread with Metadata");
134    println!("\n");
135
136    println!("Creating thread with metadata...");
137
138    let builder_with_metadata = ThreadRequestBuilder::new()
139        .metadata("user_id", "user_12345")
140        .metadata("session_id", "session_abc")
141        .metadata("context", "customer_support");
142
143    println!("  Metadata:");
144    println!("    user_id: user_12345");
145    println!("    session_id: session_abc");
146    println!("    context: customer_support");
147
148    // Uncomment to actually create thread:
149    // match client.threads().create(builder_with_metadata).await {
150    //     Ok(thread) => {
151    //         println!("\n Thread with metadata created!");
152    //         println!("  Thread ID: {}", thread.id);
153    //     }
154    //     Err(e) => {
155    //         eprintln!(" Failed to create thread: {}", e);
156    //     }
157    // }
158
159    let demo_thread_with_meta = ThreadInfo::new("thread_demo456")
160        .with_metadata("user_id", "user_12345")
161        .with_metadata("session_id", "session_abc")
162        .with_metadata("context", "customer_support");
163
164    println!("\n Demo Thread Created:");
165    demo_thread_with_meta.display();
166
167    // Example 3: Create thread with initial messages
168    println!("\n");
169    println!(" Example 3: Create Thread with Initial Messages");
170    println!("\n");
171
172    println!("Creating thread with initial messages...");
173
174    // Note: The ThreadRequestBuilder supports adding messages during creation
175    let builder_with_messages =
176        ThreadRequestBuilder::new().metadata("conversation_type", "onboarding");
177
178    println!("  Initial message: 'Hello, I need help getting started'");
179
180    // In a real implementation, you would add messages like:
181    // .message("user", "Hello, I need help getting started")
182
183    println!("\n Note: Messages can be added during thread creation or afterwards");
184
185    // Example 4: Thread lifecycle management
186    println!("\n");
187    println!(" Example 4: Thread Lifecycle");
188    println!("\n");
189
190    println!("Typical thread lifecycle:");
191    println!("  1. Create thread (ThreadRequestBuilder)");
192    println!("  2. Add messages to thread");
193    println!("  3. Create runs to process messages");
194    println!("  4. Retrieve assistant responses");
195    println!("  5. Continue conversation");
196    println!("  6. Thread persists until deleted");
197
198    // Example 5: Thread use cases
199    println!("\n");
200    println!(" Example 5: Common Thread Use Cases");
201    println!("\n");
202
203    println!(" Customer Support:");
204    println!("  • Create thread per customer session");
205    println!("  • Metadata: customer_id, ticket_id");
206    println!("  • Maintain conversation history");
207    println!("  • Allow agents to review past interactions\n");
208
209    println!(" Chatbot Conversations:");
210    println!("  • One thread per user session");
211    println!("  • Metadata: user_id, session_start");
212    println!("  • Preserve context across messages");
213    println!("  • Support multi-turn conversations\n");
214
215    println!(" Document Q&A:");
216    println!("  • Thread per document discussion");
217    println!("  • Metadata: document_id, user_id");
218    println!("  • Allow follow-up questions");
219    println!("  • Maintain question history\n");
220
221    println!(" Tutoring/Education:");
222    println!("  • Thread per learning session");
223    println!("  • Metadata: student_id, subject, lesson");
224    println!("  • Track learning progression");
225    println!("  • Review past explanations");
226
227    // Example 6: Thread metadata strategies
228    println!("\n");
229    println!(" Example 6: Metadata Strategies");
230    println!("\n");
231
232    println!("Recommended metadata fields:\n");
233
234    println!(" Identification:");
235    println!("  user_id: Identify the user");
236    println!("  session_id: Track specific sessions");
237    println!("  organization_id: Multi-tenant applications\n");
238
239    println!(" Classification:");
240    println!("  category: customer_support, sales, etc.");
241    println!("  priority: low, medium, high, urgent");
242    println!("  language: en, es, fr, etc.\n");
243
244    println!("⏰ Temporal:");
245    println!("  session_start: When conversation began");
246    println!("  last_active: Last interaction time");
247    println!("  expires_at: When to auto-cleanup\n");
248
249    println!(" Business Context:");
250    println!("  product_id: Related product");
251    println!("  ticket_id: Support ticket number");
252    println!("  campaign_id: Marketing campaign");
253
254    // Example 7: Thread best practices
255    println!("\n");
256    println!(" Example 7: Best Practices");
257    println!("\n");
258
259    println!(" Do:");
260    println!("  • Create one thread per conversation");
261    println!("  • Add meaningful metadata for filtering");
262    println!("  • Reuse threads for ongoing conversations");
263    println!("  • Clean up old/expired threads");
264    println!("  • Use metadata for analytics\n");
265
266    println!(" Don't:");
267    println!("  • Create new threads for each message");
268    println!("  • Store sensitive data in metadata");
269    println!("  • Let threads accumulate indefinitely");
270    println!("  • Use threads for one-off requests");
271    println!("  • Mix different conversations in one thread");
272
273    // Summary
274    println!("\n");
275    println!(" Summary");
276    println!("\n");
277
278    println!(" Threads API examples completed!");
279    println!("\n Key Takeaways:");
280    println!("  • Threads maintain conversation state");
281    println!("  • Metadata enables organization and filtering");
282    println!("  • One thread per conversation is recommended");
283    println!("  • Threads persist until explicitly deleted");
284    println!("  • Perfect for multi-turn conversations");
285
286    println!("\n Integration Pattern:");
287    println!("  1. Create thread at conversation start");
288    println!("  2. Store thread ID in your database");
289    println!("  3. Add messages as user interacts");
290    println!("  4. Create runs to get assistant responses");
291    println!("  5. Retrieve messages to display conversation");
292    println!("  6. Reuse thread for entire conversation");
293
294    println!("\n Related APIs:");
295    println!("  • Messages API: Add/retrieve messages in threads");
296    println!("  • Runs API: Process messages with assistants");
297    println!("  • Assistants API: Create AI assistants");
298    println!("  • Vector Stores: Add knowledge to assistants");
299
300    println!("\n Example completed successfully!");
301
302    Ok(())
303}
Source

pub fn user_message(self, content: impl Into<String>) -> Self

Seed the thread with an initial user message.

Source

pub fn assistant_message(self, content: impl Into<String>) -> Self

Seed the thread with an assistant message.

Source

pub fn message_request(self, message: CreateMessageRequest) -> Self

Add a fully configured message request.

Source

pub fn message_builder(self, builder: ThreadMessageBuilder) -> Result<Self>

Add a thread message builder.

Source

pub fn metadata(self, key: impl Into<String>, value: impl Into<String>) -> Self

Add metadata to the thread.

Examples found in repository?
examples/threads.rs (line 139)
85async fn main() -> Result<(), Box<dyn std::error::Error>> {
86    println!(" OpenAI Ergonomic - Comprehensive Threads Example\n");
87
88    // Initialize client from environment variables
89    println!(" Initializing OpenAI client...");
90    let client = match Client::from_env() {
91        Ok(c) => {
92            println!(" Client initialized successfully\n");
93            c.build()
94        }
95        Err(e) => {
96            eprintln!(" Failed to initialize client: {}", e);
97            eprintln!(" Make sure OPENAI_API_KEY is set");
98            return Ok(());
99        }
100    };
101
102    // Example 1: Create a simple thread
103    println!();
104    println!(" Example 1: Create Simple Thread");
105    println!("\n");
106
107    println!("Creating new thread...");
108
109    let builder = ThreadRequestBuilder::new();
110
111    println!("\n Note: This would create a real thread with your API key.");
112    println!("   Commented out to avoid accidental API calls.\n");
113
114    // Uncomment to actually create thread:
115    // match client.threads().create(builder).await {
116    //     Ok(thread) => {
117    //         println!(" Thread created successfully!");
118    //         println!("  Thread ID: {}", thread.id);
119    //         println!("  Created At: {}", thread.created_at);
120    //     }
121    //     Err(e) => {
122    //         eprintln!(" Failed to create thread: {}", e);
123    //     }
124    // }
125
126    // Simulate thread creation for demonstration
127    let demo_thread = ThreadInfo::new("thread_demo123");
128    println!(" Demo Thread Created:");
129    demo_thread.display();
130
131    // Example 2: Create thread with metadata
132    println!("\n");
133    println!(" Example 2: Create Thread with Metadata");
134    println!("\n");
135
136    println!("Creating thread with metadata...");
137
138    let builder_with_metadata = ThreadRequestBuilder::new()
139        .metadata("user_id", "user_12345")
140        .metadata("session_id", "session_abc")
141        .metadata("context", "customer_support");
142
143    println!("  Metadata:");
144    println!("    user_id: user_12345");
145    println!("    session_id: session_abc");
146    println!("    context: customer_support");
147
148    // Uncomment to actually create thread:
149    // match client.threads().create(builder_with_metadata).await {
150    //     Ok(thread) => {
151    //         println!("\n Thread with metadata created!");
152    //         println!("  Thread ID: {}", thread.id);
153    //     }
154    //     Err(e) => {
155    //         eprintln!(" Failed to create thread: {}", e);
156    //     }
157    // }
158
159    let demo_thread_with_meta = ThreadInfo::new("thread_demo456")
160        .with_metadata("user_id", "user_12345")
161        .with_metadata("session_id", "session_abc")
162        .with_metadata("context", "customer_support");
163
164    println!("\n Demo Thread Created:");
165    demo_thread_with_meta.display();
166
167    // Example 3: Create thread with initial messages
168    println!("\n");
169    println!(" Example 3: Create Thread with Initial Messages");
170    println!("\n");
171
172    println!("Creating thread with initial messages...");
173
174    // Note: The ThreadRequestBuilder supports adding messages during creation
175    let builder_with_messages =
176        ThreadRequestBuilder::new().metadata("conversation_type", "onboarding");
177
178    println!("  Initial message: 'Hello, I need help getting started'");
179
180    // In a real implementation, you would add messages like:
181    // .message("user", "Hello, I need help getting started")
182
183    println!("\n Note: Messages can be added during thread creation or afterwards");
184
185    // Example 4: Thread lifecycle management
186    println!("\n");
187    println!(" Example 4: Thread Lifecycle");
188    println!("\n");
189
190    println!("Typical thread lifecycle:");
191    println!("  1. Create thread (ThreadRequestBuilder)");
192    println!("  2. Add messages to thread");
193    println!("  3. Create runs to process messages");
194    println!("  4. Retrieve assistant responses");
195    println!("  5. Continue conversation");
196    println!("  6. Thread persists until deleted");
197
198    // Example 5: Thread use cases
199    println!("\n");
200    println!(" Example 5: Common Thread Use Cases");
201    println!("\n");
202
203    println!(" Customer Support:");
204    println!("  • Create thread per customer session");
205    println!("  • Metadata: customer_id, ticket_id");
206    println!("  • Maintain conversation history");
207    println!("  • Allow agents to review past interactions\n");
208
209    println!(" Chatbot Conversations:");
210    println!("  • One thread per user session");
211    println!("  • Metadata: user_id, session_start");
212    println!("  • Preserve context across messages");
213    println!("  • Support multi-turn conversations\n");
214
215    println!(" Document Q&A:");
216    println!("  • Thread per document discussion");
217    println!("  • Metadata: document_id, user_id");
218    println!("  • Allow follow-up questions");
219    println!("  • Maintain question history\n");
220
221    println!(" Tutoring/Education:");
222    println!("  • Thread per learning session");
223    println!("  • Metadata: student_id, subject, lesson");
224    println!("  • Track learning progression");
225    println!("  • Review past explanations");
226
227    // Example 6: Thread metadata strategies
228    println!("\n");
229    println!(" Example 6: Metadata Strategies");
230    println!("\n");
231
232    println!("Recommended metadata fields:\n");
233
234    println!(" Identification:");
235    println!("  user_id: Identify the user");
236    println!("  session_id: Track specific sessions");
237    println!("  organization_id: Multi-tenant applications\n");
238
239    println!(" Classification:");
240    println!("  category: customer_support, sales, etc.");
241    println!("  priority: low, medium, high, urgent");
242    println!("  language: en, es, fr, etc.\n");
243
244    println!("⏰ Temporal:");
245    println!("  session_start: When conversation began");
246    println!("  last_active: Last interaction time");
247    println!("  expires_at: When to auto-cleanup\n");
248
249    println!(" Business Context:");
250    println!("  product_id: Related product");
251    println!("  ticket_id: Support ticket number");
252    println!("  campaign_id: Marketing campaign");
253
254    // Example 7: Thread best practices
255    println!("\n");
256    println!(" Example 7: Best Practices");
257    println!("\n");
258
259    println!(" Do:");
260    println!("  • Create one thread per conversation");
261    println!("  • Add meaningful metadata for filtering");
262    println!("  • Reuse threads for ongoing conversations");
263    println!("  • Clean up old/expired threads");
264    println!("  • Use metadata for analytics\n");
265
266    println!(" Don't:");
267    println!("  • Create new threads for each message");
268    println!("  • Store sensitive data in metadata");
269    println!("  • Let threads accumulate indefinitely");
270    println!("  • Use threads for one-off requests");
271    println!("  • Mix different conversations in one thread");
272
273    // Summary
274    println!("\n");
275    println!(" Summary");
276    println!("\n");
277
278    println!(" Threads API examples completed!");
279    println!("\n Key Takeaways:");
280    println!("  • Threads maintain conversation state");
281    println!("  • Metadata enables organization and filtering");
282    println!("  • One thread per conversation is recommended");
283    println!("  • Threads persist until explicitly deleted");
284    println!("  • Perfect for multi-turn conversations");
285
286    println!("\n Integration Pattern:");
287    println!("  1. Create thread at conversation start");
288    println!("  2. Store thread ID in your database");
289    println!("  3. Add messages as user interacts");
290    println!("  4. Create runs to get assistant responses");
291    println!("  5. Retrieve messages to display conversation");
292    println!("  6. Reuse thread for entire conversation");
293
294    println!("\n Related APIs:");
295    println!("  • Messages API: Add/retrieve messages in threads");
296    println!("  • Runs API: Process messages with assistants");
297    println!("  • Assistants API: Create AI assistants");
298    println!("  • Vector Stores: Add knowledge to assistants");
299
300    println!("\n Example completed successfully!");
301
302    Ok(())
303}
Source

pub fn metadata_map(self, metadata: HashMap<String, String>) -> Self

Replace thread metadata with a full map.

Source

pub fn clear_metadata(self) -> Self

Remove metadata by sending an explicit null.

Source

pub fn messages(&self) -> &[CreateMessageRequest]

Access the configured messages.

Trait Implementations§

Source§

impl Builder<CreateThreadRequest> for ThreadRequestBuilder

Source§

fn build(self) -> Result<CreateThreadRequest>

Build the final request type.
Source§

impl Clone for ThreadRequestBuilder

Source§

fn clone(&self) -> ThreadRequestBuilder

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ThreadRequestBuilder

Source§

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

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

impl Default for ThreadRequestBuilder

Source§

fn default() -> ThreadRequestBuilder

Returns the “default value” for a type. 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<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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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: 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: 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> 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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

impl<T> ErasedDestructor for T
where T: 'static,