1#![allow(clippy::uninlined_format_args)]
33#![allow(clippy::no_effect_underscore_binding)]
34#![allow(clippy::doc_markdown)]
35#![allow(clippy::cast_possible_wrap)]
36#![allow(clippy::missing_docs_in_private_items)]
37#![allow(clippy::too_many_lines)]
38#![allow(clippy::cast_possible_truncation)]
39#![allow(clippy::cast_lossless)]
40#![allow(unused_variables)]
41#![allow(missing_docs)]
42#![allow(dead_code)]
43
44use openai_ergonomic::{builders::threads::ThreadRequestBuilder, Client};
45
46#[derive(Debug, Clone)]
48pub struct ThreadInfo {
49 pub id: String,
50 pub created_at: i64,
51 pub metadata: std::collections::HashMap<String, String>,
52}
53
54impl ThreadInfo {
55 pub fn new(id: impl Into<String>) -> Self {
56 Self {
57 id: id.into(),
58 created_at: std::time::SystemTime::now()
59 .duration_since(std::time::UNIX_EPOCH)
60 .unwrap()
61 .as_secs() as i64,
62 metadata: std::collections::HashMap::new(),
63 }
64 }
65
66 #[must_use]
67 pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
68 self.metadata.insert(key.into(), value.into());
69 self
70 }
71
72 pub fn display(&self) {
73 println!(" Thread ID: {}", self.id);
74 println!(" Created At: {}", self.created_at);
75 if !self.metadata.is_empty() {
76 println!(" Metadata:");
77 for (key, value) in &self.metadata {
78 println!(" {}: {}", key, value);
79 }
80 }
81 }
82}
83
84#[tokio::main]
85async fn main() -> Result<(), Box<dyn std::error::Error>> {
86 println!("š OpenAI Ergonomic - Comprehensive Threads Example\n");
87
88 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 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 let demo_thread = ThreadInfo::new("thread_demo123");
128 println!("š Demo Thread Created:");
129 demo_thread.display();
130
131 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 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 println!("\nāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā");
169 println!("š Example 3: Create Thread with Initial Messages");
170 println!("āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā\n");
171
172 println!("Creating thread with initial messages...");
173
174 let builder_with_messages =
176 ThreadRequestBuilder::new().metadata("conversation_type", "onboarding");
177
178 println!(" Initial message: 'Hello, I need help getting started'");
179
180 println!("\nš” Note: Messages can be added during thread creation or afterwards");
184
185 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 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 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 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 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}